repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
ciena-blueplanet/bunsen-core | src/reducer.js | function (state, action) {
return _.defaults({
isValidating: action.isValidating,
lastAction: IS_VALIDATING
}, state)
} | javascript | function (state, action) {
return _.defaults({
isValidating: action.isValidating,
lastAction: IS_VALIDATING
}, state)
} | [
"function",
"(",
"state",
",",
"action",
")",
"{",
"return",
"_",
".",
"defaults",
"(",
"{",
"isValidating",
":",
"action",
".",
"isValidating",
",",
"lastAction",
":",
"IS_VALIDATING",
"}",
",",
"state",
")",
"}"
] | Update is validating result
@param {State} state - state to update
@param {Action} action - action
@returns {State} - updated state | [
"Update",
"is",
"validating",
"result"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/reducer.js#L394-L399 | train |
|
NLeSC/spot | src/pages/analyze.js | addWidgetForFilter | function addWidgetForFilter (view, filter, editModeHint) {
var gridster = view._widgetsGridster;
var row = filter.row || 1;
var col = filter.col || 1;
var sizeX = filter.size_x || 3;
var sizeY = filter.size_y || 3;
var el = gridster.add_widget('<div class="widgetOuterFrame"></div>', sizeX, sizeY, col, row);
var frameView = new WidgetFrameView({
model: filter
});
// render, and render content of widget frame
view.renderSubview(frameView, el[0]);
frameView.renderContent();
// link element and view so we can:
// a) on remove, get to the HTMLElement from the WidgetFrameView
// b) on resize, get to the WidgetFrameView from the HTMLElement
frameView.gridsterHook = el[0];
$(el[0]).data('spotWidgetFrameView', frameView);
// try to initialize and render possibly present data
// only follow editModeHint when the widget is configured, default to true
var chartView = frameView.widget;
chartView.model.updateConfiguration();
if (chartView.model.isConfigured) {
if (!filter.isInitialized) {
filter.initDataFilter();
}
if (!chartView.isInitialized) {
chartView.initChart();
}
chartView.update();
frameView.editMode = editModeHint;
} else {
// widget is not configured, ignore editModeHint
// and always go to edit mode
frameView.editMode = true;
}
filter.on('newData', function () {
chartView.update();
});
} | javascript | function addWidgetForFilter (view, filter, editModeHint) {
var gridster = view._widgetsGridster;
var row = filter.row || 1;
var col = filter.col || 1;
var sizeX = filter.size_x || 3;
var sizeY = filter.size_y || 3;
var el = gridster.add_widget('<div class="widgetOuterFrame"></div>', sizeX, sizeY, col, row);
var frameView = new WidgetFrameView({
model: filter
});
// render, and render content of widget frame
view.renderSubview(frameView, el[0]);
frameView.renderContent();
// link element and view so we can:
// a) on remove, get to the HTMLElement from the WidgetFrameView
// b) on resize, get to the WidgetFrameView from the HTMLElement
frameView.gridsterHook = el[0];
$(el[0]).data('spotWidgetFrameView', frameView);
// try to initialize and render possibly present data
// only follow editModeHint when the widget is configured, default to true
var chartView = frameView.widget;
chartView.model.updateConfiguration();
if (chartView.model.isConfigured) {
if (!filter.isInitialized) {
filter.initDataFilter();
}
if (!chartView.isInitialized) {
chartView.initChart();
}
chartView.update();
frameView.editMode = editModeHint;
} else {
// widget is not configured, ignore editModeHint
// and always go to edit mode
frameView.editMode = true;
}
filter.on('newData', function () {
chartView.update();
});
} | [
"function",
"addWidgetForFilter",
"(",
"view",
",",
"filter",
",",
"editModeHint",
")",
"{",
"var",
"gridster",
"=",
"view",
".",
"_widgetsGridster",
";",
"var",
"row",
"=",
"filter",
".",
"row",
"||",
"1",
";",
"var",
"col",
"=",
"filter",
".",
"col",
"||",
"1",
";",
"var",
"sizeX",
"=",
"filter",
".",
"size_x",
"||",
"3",
";",
"var",
"sizeY",
"=",
"filter",
".",
"size_y",
"||",
"3",
";",
"var",
"el",
"=",
"gridster",
".",
"add_widget",
"(",
"'<div class=\"widgetOuterFrame\"></div>'",
",",
"sizeX",
",",
"sizeY",
",",
"col",
",",
"row",
")",
";",
"var",
"frameView",
"=",
"new",
"WidgetFrameView",
"(",
"{",
"model",
":",
"filter",
"}",
")",
";",
"// render, and render content of widget frame",
"view",
".",
"renderSubview",
"(",
"frameView",
",",
"el",
"[",
"0",
"]",
")",
";",
"frameView",
".",
"renderContent",
"(",
")",
";",
"// link element and view so we can:",
"// a) on remove, get to the HTMLElement from the WidgetFrameView",
"// b) on resize, get to the WidgetFrameView from the HTMLElement",
"frameView",
".",
"gridsterHook",
"=",
"el",
"[",
"0",
"]",
";",
"$",
"(",
"el",
"[",
"0",
"]",
")",
".",
"data",
"(",
"'spotWidgetFrameView'",
",",
"frameView",
")",
";",
"// try to initialize and render possibly present data",
"// only follow editModeHint when the widget is configured, default to true",
"var",
"chartView",
"=",
"frameView",
".",
"widget",
";",
"chartView",
".",
"model",
".",
"updateConfiguration",
"(",
")",
";",
"if",
"(",
"chartView",
".",
"model",
".",
"isConfigured",
")",
"{",
"if",
"(",
"!",
"filter",
".",
"isInitialized",
")",
"{",
"filter",
".",
"initDataFilter",
"(",
")",
";",
"}",
"if",
"(",
"!",
"chartView",
".",
"isInitialized",
")",
"{",
"chartView",
".",
"initChart",
"(",
")",
";",
"}",
"chartView",
".",
"update",
"(",
")",
";",
"frameView",
".",
"editMode",
"=",
"editModeHint",
";",
"}",
"else",
"{",
"// widget is not configured, ignore editModeHint",
"// and always go to edit mode",
"frameView",
".",
"editMode",
"=",
"true",
";",
"}",
"filter",
".",
"on",
"(",
"'newData'",
",",
"function",
"(",
")",
"{",
"chartView",
".",
"update",
"(",
")",
";",
"}",
")",
";",
"}"
] | Add a widget to the analyze page for the given filter
view {View} Ampersand View instance of the analyze page
filter {Filter} Spot filter instance to create the widget for
editModeHint {boolean} Try to start plot in editMode (ie. accepts dnd of facets) [true] or in interaction mode (false) | [
"Add",
"a",
"widget",
"to",
"the",
"analyze",
"page",
"for",
"the",
"given",
"filter"
] | 8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417 | https://github.com/NLeSC/spot/blob/8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417/src/pages/analyze.js#L83-L128 | train |
ciena-blueplanet/bunsen-core | src/validator/custom-formats/time.js | inRange | function inRange (value, min, max) {
const int = parseInt(value, 10)
return (
`${int}` === `${value.replace(/^0/, '')}` &&
int >= min &&
int <= max
)
} | javascript | function inRange (value, min, max) {
const int = parseInt(value, 10)
return (
`${int}` === `${value.replace(/^0/, '')}` &&
int >= min &&
int <= max
)
} | [
"function",
"inRange",
"(",
"value",
",",
"min",
",",
"max",
")",
"{",
"const",
"int",
"=",
"parseInt",
"(",
"value",
",",
"10",
")",
"return",
"(",
"`",
"${",
"int",
"}",
"`",
"===",
"`",
"${",
"value",
".",
"replace",
"(",
"/",
"^0",
"/",
",",
"''",
")",
"}",
"`",
"&&",
"int",
">=",
"min",
"&&",
"int",
"<=",
"max",
")",
"}"
] | Determine if value is within a numeric range
@param {String|Number} value - value to check
@param {Number} min - start of range (inclusive)
@param {Number} max - end of range (inclusive)
@returns {Boolean} whether or not value is within range | [
"Determine",
"if",
"value",
"is",
"within",
"a",
"numeric",
"range"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/validator/custom-formats/time.js#L8-L16 | train |
helpers/helper-md | index.js | markdown | function markdown(options) {
return new Remarkable(extend({
breaks: false,
html: true,
langPrefix: 'lang-',
linkify: true,
typographer: false,
xhtmlOut: false
}, options));
} | javascript | function markdown(options) {
return new Remarkable(extend({
breaks: false,
html: true,
langPrefix: 'lang-',
linkify: true,
typographer: false,
xhtmlOut: false
}, options));
} | [
"function",
"markdown",
"(",
"options",
")",
"{",
"return",
"new",
"Remarkable",
"(",
"extend",
"(",
"{",
"breaks",
":",
"false",
",",
"html",
":",
"true",
",",
"langPrefix",
":",
"'lang-'",
",",
"linkify",
":",
"true",
",",
"typographer",
":",
"false",
",",
"xhtmlOut",
":",
"false",
"}",
",",
"options",
")",
")",
";",
"}"
] | Shared settings for remarkable
@param {Object} `options`
@return {Object}
@api private | [
"Shared",
"settings",
"for",
"remarkable"
] | 6bf823b4264c341903c1b85676610bb3dbe6bcc2 | https://github.com/helpers/helper-md/blob/6bf823b4264c341903c1b85676610bb3dbe6bcc2/index.js#L108-L117 | train |
NLeSC/spot | src/widgets/views/util.js | partitionValueToIndex | function partitionValueToIndex (partition, value) {
var group;
if (!partition) {
// no(sub)partitioning return first element
return 0;
}
// with (sub)partitioning
group = partition.groups.get(value, 'value');
if (group) {
// string in partition
return group.groupIndex;
} else {
// string not in partition
return -1;
}
} | javascript | function partitionValueToIndex (partition, value) {
var group;
if (!partition) {
// no(sub)partitioning return first element
return 0;
}
// with (sub)partitioning
group = partition.groups.get(value, 'value');
if (group) {
// string in partition
return group.groupIndex;
} else {
// string not in partition
return -1;
}
} | [
"function",
"partitionValueToIndex",
"(",
"partition",
",",
"value",
")",
"{",
"var",
"group",
";",
"if",
"(",
"!",
"partition",
")",
"{",
"// no(sub)partitioning return first element",
"return",
"0",
";",
"}",
"// with (sub)partitioning",
"group",
"=",
"partition",
".",
"groups",
".",
"get",
"(",
"value",
",",
"'value'",
")",
";",
"if",
"(",
"group",
")",
"{",
"// string in partition",
"return",
"group",
".",
"groupIndex",
";",
"}",
"else",
"{",
"// string not in partition",
"return",
"-",
"1",
";",
"}",
"}"
] | Get the index in chartjs datastructures from the group value
with proper fallbacks
@params {Partition} partition (optional)
@params {Object} value value
@returns {number|null} index | [
"Get",
"the",
"index",
"in",
"chartjs",
"datastructures",
"from",
"the",
"group",
"value",
"with",
"proper",
"fallbacks"
] | 8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417 | https://github.com/NLeSC/spot/blob/8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417/src/widgets/views/util.js#L10-L28 | train |
ciena-blueplanet/bunsen-core | src/validator/model.js | _validateArray | function _validateArray (path, model, validateModelType) {
const results = []
let subPath = `${path}/items`
if (_.isPlainObject(model.items)) {
if (model.items.type === 'object') {
results.push(validateSubModel(subPath, model.items, validateModelType))
}
} else if (Array.isArray(model.items)) {
_.forEach(model.items, (item, index) => {
const itemSubPath = `${subPath}/${index}`
results.push(validateSubModel(itemSubPath, item, validateModelType))
})
}
return aggregateResults(results)
} | javascript | function _validateArray (path, model, validateModelType) {
const results = []
let subPath = `${path}/items`
if (_.isPlainObject(model.items)) {
if (model.items.type === 'object') {
results.push(validateSubModel(subPath, model.items, validateModelType))
}
} else if (Array.isArray(model.items)) {
_.forEach(model.items, (item, index) => {
const itemSubPath = `${subPath}/${index}`
results.push(validateSubModel(itemSubPath, item, validateModelType))
})
}
return aggregateResults(results)
} | [
"function",
"_validateArray",
"(",
"path",
",",
"model",
",",
"validateModelType",
")",
"{",
"const",
"results",
"=",
"[",
"]",
"let",
"subPath",
"=",
"`",
"${",
"path",
"}",
"`",
"if",
"(",
"_",
".",
"isPlainObject",
"(",
"model",
".",
"items",
")",
")",
"{",
"if",
"(",
"model",
".",
"items",
".",
"type",
"===",
"'object'",
")",
"{",
"results",
".",
"push",
"(",
"validateSubModel",
"(",
"subPath",
",",
"model",
".",
"items",
",",
"validateModelType",
")",
")",
"}",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"model",
".",
"items",
")",
")",
"{",
"_",
".",
"forEach",
"(",
"model",
".",
"items",
",",
"(",
"item",
",",
"index",
")",
"=>",
"{",
"const",
"itemSubPath",
"=",
"`",
"${",
"subPath",
"}",
"${",
"index",
"}",
"`",
"results",
".",
"push",
"(",
"validateSubModel",
"(",
"itemSubPath",
",",
"item",
",",
"validateModelType",
")",
")",
"}",
")",
"}",
"return",
"aggregateResults",
"(",
"results",
")",
"}"
] | Validate the array definition
@param {String} path - the path to the field from the root of the model
@param {BunsenModel} model - the model to validate
@param {Function} validateModelType - function to validate model type
@returns {BunsenValidationResult} the results of the model validation | [
"Validate",
"the",
"array",
"definition"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/validator/model.js#L90-L105 | train |
ciena-blueplanet/bunsen-core | src/actions.js | getDefaults | function getDefaults (value, path, model, resolveRef) {
const schema = findSchema(model, path, resolveRef)
const schemaDefault = _.clone(schema.default)
if (model.type === 'object') {
const subSchemaDefaults = {}
_.forIn(schema.properties, function (subSchema, propName) {
const defaults = getDefaults(
value && value[propName],
null,
subSchema,
resolveRef
)
if (defaults !== undefined) {
subSchemaDefaults[propName] = defaults
}
})
if (Object.keys(subSchemaDefaults).length > 0) {
return _.defaults({}, schemaDefault, subSchemaDefaults)
}
return schemaDefault
} else if (value !== undefined) {
return value
}
return schemaDefault
} | javascript | function getDefaults (value, path, model, resolveRef) {
const schema = findSchema(model, path, resolveRef)
const schemaDefault = _.clone(schema.default)
if (model.type === 'object') {
const subSchemaDefaults = {}
_.forIn(schema.properties, function (subSchema, propName) {
const defaults = getDefaults(
value && value[propName],
null,
subSchema,
resolveRef
)
if (defaults !== undefined) {
subSchemaDefaults[propName] = defaults
}
})
if (Object.keys(subSchemaDefaults).length > 0) {
return _.defaults({}, schemaDefault, subSchemaDefaults)
}
return schemaDefault
} else if (value !== undefined) {
return value
}
return schemaDefault
} | [
"function",
"getDefaults",
"(",
"value",
",",
"path",
",",
"model",
",",
"resolveRef",
")",
"{",
"const",
"schema",
"=",
"findSchema",
"(",
"model",
",",
"path",
",",
"resolveRef",
")",
"const",
"schemaDefault",
"=",
"_",
".",
"clone",
"(",
"schema",
".",
"default",
")",
"if",
"(",
"model",
".",
"type",
"===",
"'object'",
")",
"{",
"const",
"subSchemaDefaults",
"=",
"{",
"}",
"_",
".",
"forIn",
"(",
"schema",
".",
"properties",
",",
"function",
"(",
"subSchema",
",",
"propName",
")",
"{",
"const",
"defaults",
"=",
"getDefaults",
"(",
"value",
"&&",
"value",
"[",
"propName",
"]",
",",
"null",
",",
"subSchema",
",",
"resolveRef",
")",
"if",
"(",
"defaults",
"!==",
"undefined",
")",
"{",
"subSchemaDefaults",
"[",
"propName",
"]",
"=",
"defaults",
"}",
"}",
")",
"if",
"(",
"Object",
".",
"keys",
"(",
"subSchemaDefaults",
")",
".",
"length",
">",
"0",
")",
"{",
"return",
"_",
".",
"defaults",
"(",
"{",
"}",
",",
"schemaDefault",
",",
"subSchemaDefaults",
")",
"}",
"return",
"schemaDefault",
"}",
"else",
"if",
"(",
"value",
"!==",
"undefined",
")",
"{",
"return",
"value",
"}",
"return",
"schemaDefault",
"}"
] | Returns the value with defaults provided by the schema
@param {Object} value - a complex object/array (the bunsen form value)
@param {String} path - path to retrieve the sub schema of the model given
@param {Object} model - bunsen model schema
@param {Function} resolveRef - function to resolve references
@returns {Object} the value with defaults applied | [
"Returns",
"the",
"value",
"with",
"defaults",
"provided",
"by",
"the",
"schema"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/actions.js#L146-L172 | train |
ciena-blueplanet/bunsen-core | src/actions.js | getDefaultedValue | function getDefaultedValue ({inputValue, previousValue, bunsenId, renderModel, mergeDefaults}) {
const isInputValueEmpty = isEmptyValue(inputValue)
if (previousValue !== undefined) {
return inputValue
}
const resolveRef = schemaFromRef(renderModel.definitions)
const defaultValue = getDefaults(inputValue, bunsenId, renderModel, resolveRef)
const hasDefaults = defaultValue !== undefined
const isUpdatingAll = bunsenId === null
const shouldApplyDefaults = isInputValueEmpty && hasDefaults ||
!isInputValueEmpty && hasDefaults && isUpdatingAll && mergeDefaults
const shouldClear = isInputValueEmpty && isUpdatingAll && !hasDefaults
if (shouldApplyDefaults) {
const schema = findSchema(renderModel, bunsenId, resolveRef)
return schema.type === 'object' ? _.defaults({}, inputValue, defaultValue) : defaultValue
} else if (shouldClear) {
return {}
}
return inputValue
} | javascript | function getDefaultedValue ({inputValue, previousValue, bunsenId, renderModel, mergeDefaults}) {
const isInputValueEmpty = isEmptyValue(inputValue)
if (previousValue !== undefined) {
return inputValue
}
const resolveRef = schemaFromRef(renderModel.definitions)
const defaultValue = getDefaults(inputValue, bunsenId, renderModel, resolveRef)
const hasDefaults = defaultValue !== undefined
const isUpdatingAll = bunsenId === null
const shouldApplyDefaults = isInputValueEmpty && hasDefaults ||
!isInputValueEmpty && hasDefaults && isUpdatingAll && mergeDefaults
const shouldClear = isInputValueEmpty && isUpdatingAll && !hasDefaults
if (shouldApplyDefaults) {
const schema = findSchema(renderModel, bunsenId, resolveRef)
return schema.type === 'object' ? _.defaults({}, inputValue, defaultValue) : defaultValue
} else if (shouldClear) {
return {}
}
return inputValue
} | [
"function",
"getDefaultedValue",
"(",
"{",
"inputValue",
",",
"previousValue",
",",
"bunsenId",
",",
"renderModel",
",",
"mergeDefaults",
"}",
")",
"{",
"const",
"isInputValueEmpty",
"=",
"isEmptyValue",
"(",
"inputValue",
")",
"if",
"(",
"previousValue",
"!==",
"undefined",
")",
"{",
"return",
"inputValue",
"}",
"const",
"resolveRef",
"=",
"schemaFromRef",
"(",
"renderModel",
".",
"definitions",
")",
"const",
"defaultValue",
"=",
"getDefaults",
"(",
"inputValue",
",",
"bunsenId",
",",
"renderModel",
",",
"resolveRef",
")",
"const",
"hasDefaults",
"=",
"defaultValue",
"!==",
"undefined",
"const",
"isUpdatingAll",
"=",
"bunsenId",
"===",
"null",
"const",
"shouldApplyDefaults",
"=",
"isInputValueEmpty",
"&&",
"hasDefaults",
"||",
"!",
"isInputValueEmpty",
"&&",
"hasDefaults",
"&&",
"isUpdatingAll",
"&&",
"mergeDefaults",
"const",
"shouldClear",
"=",
"isInputValueEmpty",
"&&",
"isUpdatingAll",
"&&",
"!",
"hasDefaults",
"if",
"(",
"shouldApplyDefaults",
")",
"{",
"const",
"schema",
"=",
"findSchema",
"(",
"renderModel",
",",
"bunsenId",
",",
"resolveRef",
")",
"return",
"schema",
".",
"type",
"===",
"'object'",
"?",
"_",
".",
"defaults",
"(",
"{",
"}",
",",
"inputValue",
",",
"defaultValue",
")",
":",
"defaultValue",
"}",
"else",
"if",
"(",
"shouldClear",
")",
"{",
"return",
"{",
"}",
"}",
"return",
"inputValue",
"}"
] | Returns the default value for the given model
@param {Object} inputValue - form value at the given bunsen path
@param {Object} previousValue - the previous form value at the given bunsen path
@param {String} bunsenId - the bunsen path id
@param {Object} renderModel - the bunsen model without conditions
@param {Boolean} mergeDefaults - whether to force a default value on a non-empty value
/* eslint-disable complexity | [
"Returns",
"the",
"default",
"value",
"for",
"the",
"given",
"model"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/actions.js#L198-L222 | train |
ciena-blueplanet/bunsen-core | src/actions.js | fieldValidation | function fieldValidation (dispatch, getState, fieldValidators, formValue, initialFormValue, all) {
let fieldsBeingValidated = []
const allValidationPromises = []
fieldValidators.forEach(validator => {
/**
* Field validator definition
* @property {String} field field to validate
* @property {String[]} fields fields to validate
* @property {Function} validator validation function to validate field/fields. Must return field within error/warning
* @property {Function[]} validators validation functions to validate field/fields. Must return field within error/warning
*/
const {field, fields, validator: validatorFunc, validators: validatorFuncs} = validator
const fieldsToValidate = fields || [field]
fieldsBeingValidated = fieldsBeingValidated.concat(fieldsToValidate)
fieldsToValidate.forEach((field) => {
let fieldValidationPromises = []
const newValue = _.get(formValue, field)
const oldValue = _.get(initialFormValue, field)
// Check if field value has changed
if (!_.isEqual(newValue, oldValue) || !initialFormValue) {
dispatchFieldIsValidating(dispatch, field, true)
const validations = validatorFuncs || [validatorFunc]
// Send validator formValue, the field we're validating against, and the field's value
validations.forEach((validatorFunc, index) => {
const fieldValidationPromise = validatorFunc(formValue, field, newValue)
.then((result) => {
const {
fieldValidationResult: {
errors: currentErrors = [],
warnings: currentWarnings = []
} = {}
} = getState()
const validationId = `${field}-${index}`
const filterOutValidationId = (item) => item.validationId !== validationId
const filteredOutErrors = currentErrors.filter(filterOutValidationId)
const filteredOutWarnings = currentWarnings.filter(filterOutValidationId)
// No need to use `aggregateResults as we should never have isRequired
const {
errors = [], warnings = []
} = result.value
const attachValidationId = (item) => {
return _.assign({
validationId,
field
}, item)
}
const newErrors = filteredOutErrors.concat(errors.map(attachValidationId))
const errorsMappedToDotNotation = mapErrorsFromValidation(newErrors)
dispatch({
fieldErrors: errorsMappedToDotNotation,
type: VALIDATION_RESOLVED,
fieldValidationResult: {
errors: newErrors,
warnings: filteredOutWarnings.concat(warnings.map(attachValidationId))
}
})
return result
})
allValidationPromises.push(fieldValidationPromise)
fieldValidationPromises.push(fieldValidationPromise)
})
}
if (fieldValidationPromises.length >= 1) {
all(fieldValidationPromises).then(() => {
dispatchFieldIsValidating(dispatch, field, false)
})
}
})
})
return allValidationPromises
} | javascript | function fieldValidation (dispatch, getState, fieldValidators, formValue, initialFormValue, all) {
let fieldsBeingValidated = []
const allValidationPromises = []
fieldValidators.forEach(validator => {
/**
* Field validator definition
* @property {String} field field to validate
* @property {String[]} fields fields to validate
* @property {Function} validator validation function to validate field/fields. Must return field within error/warning
* @property {Function[]} validators validation functions to validate field/fields. Must return field within error/warning
*/
const {field, fields, validator: validatorFunc, validators: validatorFuncs} = validator
const fieldsToValidate = fields || [field]
fieldsBeingValidated = fieldsBeingValidated.concat(fieldsToValidate)
fieldsToValidate.forEach((field) => {
let fieldValidationPromises = []
const newValue = _.get(formValue, field)
const oldValue = _.get(initialFormValue, field)
// Check if field value has changed
if (!_.isEqual(newValue, oldValue) || !initialFormValue) {
dispatchFieldIsValidating(dispatch, field, true)
const validations = validatorFuncs || [validatorFunc]
// Send validator formValue, the field we're validating against, and the field's value
validations.forEach((validatorFunc, index) => {
const fieldValidationPromise = validatorFunc(formValue, field, newValue)
.then((result) => {
const {
fieldValidationResult: {
errors: currentErrors = [],
warnings: currentWarnings = []
} = {}
} = getState()
const validationId = `${field}-${index}`
const filterOutValidationId = (item) => item.validationId !== validationId
const filteredOutErrors = currentErrors.filter(filterOutValidationId)
const filteredOutWarnings = currentWarnings.filter(filterOutValidationId)
// No need to use `aggregateResults as we should never have isRequired
const {
errors = [], warnings = []
} = result.value
const attachValidationId = (item) => {
return _.assign({
validationId,
field
}, item)
}
const newErrors = filteredOutErrors.concat(errors.map(attachValidationId))
const errorsMappedToDotNotation = mapErrorsFromValidation(newErrors)
dispatch({
fieldErrors: errorsMappedToDotNotation,
type: VALIDATION_RESOLVED,
fieldValidationResult: {
errors: newErrors,
warnings: filteredOutWarnings.concat(warnings.map(attachValidationId))
}
})
return result
})
allValidationPromises.push(fieldValidationPromise)
fieldValidationPromises.push(fieldValidationPromise)
})
}
if (fieldValidationPromises.length >= 1) {
all(fieldValidationPromises).then(() => {
dispatchFieldIsValidating(dispatch, field, false)
})
}
})
})
return allValidationPromises
} | [
"function",
"fieldValidation",
"(",
"dispatch",
",",
"getState",
",",
"fieldValidators",
",",
"formValue",
",",
"initialFormValue",
",",
"all",
")",
"{",
"let",
"fieldsBeingValidated",
"=",
"[",
"]",
"const",
"allValidationPromises",
"=",
"[",
"]",
"fieldValidators",
".",
"forEach",
"(",
"validator",
"=>",
"{",
"/**\n * Field validator definition\n * @property {String} field field to validate\n * @property {String[]} fields fields to validate\n * @property {Function} validator validation function to validate field/fields. Must return field within error/warning\n * @property {Function[]} validators validation functions to validate field/fields. Must return field within error/warning\n */",
"const",
"{",
"field",
",",
"fields",
",",
"validator",
":",
"validatorFunc",
",",
"validators",
":",
"validatorFuncs",
"}",
"=",
"validator",
"const",
"fieldsToValidate",
"=",
"fields",
"||",
"[",
"field",
"]",
"fieldsBeingValidated",
"=",
"fieldsBeingValidated",
".",
"concat",
"(",
"fieldsToValidate",
")",
"fieldsToValidate",
".",
"forEach",
"(",
"(",
"field",
")",
"=>",
"{",
"let",
"fieldValidationPromises",
"=",
"[",
"]",
"const",
"newValue",
"=",
"_",
".",
"get",
"(",
"formValue",
",",
"field",
")",
"const",
"oldValue",
"=",
"_",
".",
"get",
"(",
"initialFormValue",
",",
"field",
")",
"// Check if field value has changed",
"if",
"(",
"!",
"_",
".",
"isEqual",
"(",
"newValue",
",",
"oldValue",
")",
"||",
"!",
"initialFormValue",
")",
"{",
"dispatchFieldIsValidating",
"(",
"dispatch",
",",
"field",
",",
"true",
")",
"const",
"validations",
"=",
"validatorFuncs",
"||",
"[",
"validatorFunc",
"]",
"// Send validator formValue, the field we're validating against, and the field's value",
"validations",
".",
"forEach",
"(",
"(",
"validatorFunc",
",",
"index",
")",
"=>",
"{",
"const",
"fieldValidationPromise",
"=",
"validatorFunc",
"(",
"formValue",
",",
"field",
",",
"newValue",
")",
".",
"then",
"(",
"(",
"result",
")",
"=>",
"{",
"const",
"{",
"fieldValidationResult",
":",
"{",
"errors",
":",
"currentErrors",
"=",
"[",
"]",
",",
"warnings",
":",
"currentWarnings",
"=",
"[",
"]",
"}",
"=",
"{",
"}",
"}",
"=",
"getState",
"(",
")",
"const",
"validationId",
"=",
"`",
"${",
"field",
"}",
"${",
"index",
"}",
"`",
"const",
"filterOutValidationId",
"=",
"(",
"item",
")",
"=>",
"item",
".",
"validationId",
"!==",
"validationId",
"const",
"filteredOutErrors",
"=",
"currentErrors",
".",
"filter",
"(",
"filterOutValidationId",
")",
"const",
"filteredOutWarnings",
"=",
"currentWarnings",
".",
"filter",
"(",
"filterOutValidationId",
")",
"// No need to use `aggregateResults as we should never have isRequired",
"const",
"{",
"errors",
"=",
"[",
"]",
",",
"warnings",
"=",
"[",
"]",
"}",
"=",
"result",
".",
"value",
"const",
"attachValidationId",
"=",
"(",
"item",
")",
"=>",
"{",
"return",
"_",
".",
"assign",
"(",
"{",
"validationId",
",",
"field",
"}",
",",
"item",
")",
"}",
"const",
"newErrors",
"=",
"filteredOutErrors",
".",
"concat",
"(",
"errors",
".",
"map",
"(",
"attachValidationId",
")",
")",
"const",
"errorsMappedToDotNotation",
"=",
"mapErrorsFromValidation",
"(",
"newErrors",
")",
"dispatch",
"(",
"{",
"fieldErrors",
":",
"errorsMappedToDotNotation",
",",
"type",
":",
"VALIDATION_RESOLVED",
",",
"fieldValidationResult",
":",
"{",
"errors",
":",
"newErrors",
",",
"warnings",
":",
"filteredOutWarnings",
".",
"concat",
"(",
"warnings",
".",
"map",
"(",
"attachValidationId",
")",
")",
"}",
"}",
")",
"return",
"result",
"}",
")",
"allValidationPromises",
".",
"push",
"(",
"fieldValidationPromise",
")",
"fieldValidationPromises",
".",
"push",
"(",
"fieldValidationPromise",
")",
"}",
")",
"}",
"if",
"(",
"fieldValidationPromises",
".",
"length",
">=",
"1",
")",
"{",
"all",
"(",
"fieldValidationPromises",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"dispatchFieldIsValidating",
"(",
"dispatch",
",",
"field",
",",
"false",
")",
"}",
")",
"}",
"}",
")",
"}",
")",
"return",
"allValidationPromises",
"}"
] | Field validation. Only validate if field has changed.
Meant for expensive validations like server side validation
@function fieldValidation
@param {Function} dispatch Redux store dispatch
@param {Function} getState Function that returns current state of store
@param {Array<Object>} fieldValidators Array of field validators
@param {Object} formValue value of what changed
@param {Object} initialFormValue initial value before change
@param {Function} all framework specific Promise.all method
@returns {Array<Promise>} Array of field validation promises | [
"Field",
"validation",
".",
"Only",
"validate",
"if",
"field",
"has",
"changed",
".",
"Meant",
"for",
"expensive",
"validations",
"like",
"server",
"side",
"validation"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/actions.js#L310-L386 | train |
ciena-blueplanet/bunsen-core | src/actions.js | _guardPromiseAll | function _guardPromiseAll (promises, all, callback) {
if (promises.length === 0) {
callback()
} else {
all(promises).then(() => {
callback()
})
}
} | javascript | function _guardPromiseAll (promises, all, callback) {
if (promises.length === 0) {
callback()
} else {
all(promises).then(() => {
callback()
})
}
} | [
"function",
"_guardPromiseAll",
"(",
"promises",
",",
"all",
",",
"callback",
")",
"{",
"if",
"(",
"promises",
".",
"length",
"===",
"0",
")",
"{",
"callback",
"(",
")",
"}",
"else",
"{",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"callback",
"(",
")",
"}",
")",
"}",
"}"
] | Simple function to guard Promise.all
@function _guardPromiseAll
@param {Array<Promise>} promises Array of promises
@param {Function} all Promise all function
@param {Function} callback Function to call after all promises finished | [
"Simple",
"function",
"to",
"guard",
"Promise",
".",
"all"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/actions.js#L403-L411 | train |
ciena-blueplanet/bunsen-core | src/generator.js | getPropertyOrder | function getPropertyOrder (properties) {
const primitiveProps = []
const complexProps = []
_.forIn(properties, (prop, propName) => {
if (prop.type === 'object' || prop.type === 'array') {
complexProps.push(propName)
} else {
primitiveProps.push(propName)
}
})
return primitiveProps.concat(complexProps)
} | javascript | function getPropertyOrder (properties) {
const primitiveProps = []
const complexProps = []
_.forIn(properties, (prop, propName) => {
if (prop.type === 'object' || prop.type === 'array') {
complexProps.push(propName)
} else {
primitiveProps.push(propName)
}
})
return primitiveProps.concat(complexProps)
} | [
"function",
"getPropertyOrder",
"(",
"properties",
")",
"{",
"const",
"primitiveProps",
"=",
"[",
"]",
"const",
"complexProps",
"=",
"[",
"]",
"_",
".",
"forIn",
"(",
"properties",
",",
"(",
"prop",
",",
"propName",
")",
"=>",
"{",
"if",
"(",
"prop",
".",
"type",
"===",
"'object'",
"||",
"prop",
".",
"type",
"===",
"'array'",
")",
"{",
"complexProps",
".",
"push",
"(",
"propName",
")",
"}",
"else",
"{",
"primitiveProps",
".",
"push",
"(",
"propName",
")",
"}",
"}",
")",
"return",
"primitiveProps",
".",
"concat",
"(",
"complexProps",
")",
"}"
] | Take the properties of an object and put primitive types above non-primitive types
@param {BunsenModelSet} properties - the properties for the model (key-value)
@returns {String[]} an array of property names in the order we should display them | [
"Take",
"the",
"properties",
"of",
"an",
"object",
"and",
"put",
"primitive",
"types",
"above",
"non",
"-",
"primitive",
"types"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/generator.js#L11-L24 | train |
ciena-blueplanet/bunsen-core | src/generator.js | addModelCell | function addModelCell (propertyName, model, cellDefinitions) {
const cell = {}
var defName = propertyName
var counter = 1
while (defName in cellDefinitions) {
defName = `${propertyName}${counter}`
counter++
}
cellDefinitions[defName] = cell
const props = getPropertyOrder(model.properties)
const children = props.map((propName) => {
// we have a circular dependency
/* eslint-disable no-use-before-define */
return addModel(propName, model.properties[propName], cellDefinitions)
/* eslint-enable no-use-before-define */
})
if (model.dependencies) {
_.forIn(model.dependencies, (dep, depName) => {
const depProps = getPropertyOrder(dep.properties)
const depChildren = depProps.map((propName) => {
// we have a circular dependency
/* eslint-disable no-use-before-define */
return addDependentModel(propName, depName, dep.properties[propName], cellDefinitions)
/* eslint-enable no-use-before-define */
})
children.push.apply(children, depChildren)
})
}
cell.children = children
return defName
} | javascript | function addModelCell (propertyName, model, cellDefinitions) {
const cell = {}
var defName = propertyName
var counter = 1
while (defName in cellDefinitions) {
defName = `${propertyName}${counter}`
counter++
}
cellDefinitions[defName] = cell
const props = getPropertyOrder(model.properties)
const children = props.map((propName) => {
// we have a circular dependency
/* eslint-disable no-use-before-define */
return addModel(propName, model.properties[propName], cellDefinitions)
/* eslint-enable no-use-before-define */
})
if (model.dependencies) {
_.forIn(model.dependencies, (dep, depName) => {
const depProps = getPropertyOrder(dep.properties)
const depChildren = depProps.map((propName) => {
// we have a circular dependency
/* eslint-disable no-use-before-define */
return addDependentModel(propName, depName, dep.properties[propName], cellDefinitions)
/* eslint-enable no-use-before-define */
})
children.push.apply(children, depChildren)
})
}
cell.children = children
return defName
} | [
"function",
"addModelCell",
"(",
"propertyName",
",",
"model",
",",
"cellDefinitions",
")",
"{",
"const",
"cell",
"=",
"{",
"}",
"var",
"defName",
"=",
"propertyName",
"var",
"counter",
"=",
"1",
"while",
"(",
"defName",
"in",
"cellDefinitions",
")",
"{",
"defName",
"=",
"`",
"${",
"propertyName",
"}",
"${",
"counter",
"}",
"`",
"counter",
"++",
"}",
"cellDefinitions",
"[",
"defName",
"]",
"=",
"cell",
"const",
"props",
"=",
"getPropertyOrder",
"(",
"model",
".",
"properties",
")",
"const",
"children",
"=",
"props",
".",
"map",
"(",
"(",
"propName",
")",
"=>",
"{",
"// we have a circular dependency",
"/* eslint-disable no-use-before-define */",
"return",
"addModel",
"(",
"propName",
",",
"model",
".",
"properties",
"[",
"propName",
"]",
",",
"cellDefinitions",
")",
"/* eslint-enable no-use-before-define */",
"}",
")",
"if",
"(",
"model",
".",
"dependencies",
")",
"{",
"_",
".",
"forIn",
"(",
"model",
".",
"dependencies",
",",
"(",
"dep",
",",
"depName",
")",
"=>",
"{",
"const",
"depProps",
"=",
"getPropertyOrder",
"(",
"dep",
".",
"properties",
")",
"const",
"depChildren",
"=",
"depProps",
".",
"map",
"(",
"(",
"propName",
")",
"=>",
"{",
"// we have a circular dependency",
"/* eslint-disable no-use-before-define */",
"return",
"addDependentModel",
"(",
"propName",
",",
"depName",
",",
"dep",
".",
"properties",
"[",
"propName",
"]",
",",
"cellDefinitions",
")",
"/* eslint-enable no-use-before-define */",
"}",
")",
"children",
".",
"push",
".",
"apply",
"(",
"children",
",",
"depChildren",
")",
"}",
")",
"}",
"cell",
".",
"children",
"=",
"children",
"return",
"defName",
"}"
] | Add a model cell for the given model
@param {String} propertyName - the name of the property that holds the model
@param {BunsenModel} model - the model to add a cell for
@param {BunsenCell[]} cellDefinitions - the cells set to add the model cell to
@returns {String} the cell name | [
"Add",
"a",
"model",
"cell",
"for",
"the",
"given",
"model"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/generator.js#L78-L113 | train |
jacob-meacham/serverless-plugin-offline-kinesis-events | example/put_records.js | run | async function run() {
// Read the records
const records = await BB.all(process.argv.slice(2).map(f => readAsync(f)))
// Write them to Kinesis
return BB.map(records, record => kinesis.putRecord({
Data: JSON.stringify(yaml.safeLoad(record)),
PartitionKey: '0',
StreamName: process.env.LAMBDA_KINESIS_STREAM_NAME
}).promise())
} | javascript | async function run() {
// Read the records
const records = await BB.all(process.argv.slice(2).map(f => readAsync(f)))
// Write them to Kinesis
return BB.map(records, record => kinesis.putRecord({
Data: JSON.stringify(yaml.safeLoad(record)),
PartitionKey: '0',
StreamName: process.env.LAMBDA_KINESIS_STREAM_NAME
}).promise())
} | [
"async",
"function",
"run",
"(",
")",
"{",
"// Read the records",
"const",
"records",
"=",
"await",
"BB",
".",
"all",
"(",
"process",
".",
"argv",
".",
"slice",
"(",
"2",
")",
".",
"map",
"(",
"f",
"=>",
"readAsync",
"(",
"f",
")",
")",
")",
"// Write them to Kinesis",
"return",
"BB",
".",
"map",
"(",
"records",
",",
"record",
"=>",
"kinesis",
".",
"putRecord",
"(",
"{",
"Data",
":",
"JSON",
".",
"stringify",
"(",
"yaml",
".",
"safeLoad",
"(",
"record",
")",
")",
",",
"PartitionKey",
":",
"'0'",
",",
"StreamName",
":",
"process",
".",
"env",
".",
"LAMBDA_KINESIS_STREAM_NAME",
"}",
")",
".",
"promise",
"(",
")",
")",
"}"
] | Load the record | [
"Load",
"the",
"record"
] | 343a7fa29c269a00553f24a56207bffd764001c3 | https://github.com/jacob-meacham/serverless-plugin-offline-kinesis-events/blob/343a7fa29c269a00553f24a56207bffd764001c3/example/put_records.js#L24-L33 | train |
ciena-blueplanet/bunsen-core | src/normalize-model-and-view.js | appendModelPath | function appendModelPath (modelPath, id, internal) {
const addedModelPath = getModelPath(id)
if (internal) {
if (modelPath === '') {
return `properties._internal.${addedModelPath}`
}
return `${modelPath}.properties._internal.${addedModelPath}`
}
if (modelPath === '') {
return addedModelPath
}
return `${modelPath}.${addedModelPath}`
} | javascript | function appendModelPath (modelPath, id, internal) {
const addedModelPath = getModelPath(id)
if (internal) {
if (modelPath === '') {
return `properties._internal.${addedModelPath}`
}
return `${modelPath}.properties._internal.${addedModelPath}`
}
if (modelPath === '') {
return addedModelPath
}
return `${modelPath}.${addedModelPath}`
} | [
"function",
"appendModelPath",
"(",
"modelPath",
",",
"id",
",",
"internal",
")",
"{",
"const",
"addedModelPath",
"=",
"getModelPath",
"(",
"id",
")",
"if",
"(",
"internal",
")",
"{",
"if",
"(",
"modelPath",
"===",
"''",
")",
"{",
"return",
"`",
"${",
"addedModelPath",
"}",
"`",
"}",
"return",
"`",
"${",
"modelPath",
"}",
"${",
"addedModelPath",
"}",
"`",
"}",
"if",
"(",
"modelPath",
"===",
"''",
")",
"{",
"return",
"addedModelPath",
"}",
"return",
"`",
"${",
"modelPath",
"}",
"${",
"addedModelPath",
"}",
"`",
"}"
] | Create a path to add within a model
@param {String} modelPath Path to current place within the model
@param {String} id Id specified in the cell
@param {Boolean} internal True if we want to add an internal model
@returns {String} Path to add within the model | [
"Create",
"a",
"path",
"to",
"add",
"within",
"a",
"model"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/normalize-model-and-view.js#L38-L50 | train |
ciena-blueplanet/bunsen-core | src/normalize-model-and-view.js | extendCell | function extendCell (cell, cellDefinitions) {
cell = _.clone(cell)
while (cell.extends) {
const extendedCell = cellDefinitions[cell.extends]
if (!_.isObject(extendedCell)) {
throw new Error(`'${cell.extends}' is not a valid model definition`)
}
delete cell.extends
cell = _.defaults(cell, extendedCell)
}
return cell
} | javascript | function extendCell (cell, cellDefinitions) {
cell = _.clone(cell)
while (cell.extends) {
const extendedCell = cellDefinitions[cell.extends]
if (!_.isObject(extendedCell)) {
throw new Error(`'${cell.extends}' is not a valid model definition`)
}
delete cell.extends
cell = _.defaults(cell, extendedCell)
}
return cell
} | [
"function",
"extendCell",
"(",
"cell",
",",
"cellDefinitions",
")",
"{",
"cell",
"=",
"_",
".",
"clone",
"(",
"cell",
")",
"while",
"(",
"cell",
".",
"extends",
")",
"{",
"const",
"extendedCell",
"=",
"cellDefinitions",
"[",
"cell",
".",
"extends",
"]",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"extendedCell",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"cell",
".",
"extends",
"}",
"`",
")",
"}",
"delete",
"cell",
".",
"extends",
"cell",
"=",
"_",
".",
"defaults",
"(",
"cell",
",",
"extendedCell",
")",
"}",
"return",
"cell",
"}"
] | Copies a cell. If the cell extends cell definions, properties from teh extended cell
are copied into the new cell.
@param {BunsenCell} cell Cell to build up with cell definitions
@param {Object} cellDefinitions Cell definitions available in the view
@returns {BunsenCell} The expanded cell | [
"Copies",
"a",
"cell",
".",
"If",
"the",
"cell",
"extends",
"cell",
"definions",
"properties",
"from",
"teh",
"extended",
"cell",
"are",
"copied",
"into",
"the",
"new",
"cell",
"."
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/normalize-model-and-view.js#L60-L71 | train |
ciena-blueplanet/bunsen-core | src/normalize-model-and-view.js | normalizeArrayOptions | function normalizeArrayOptions (cell, cellDefinitions) {
const arrayOptions = _.clone(cell.arrayOptions)
if (arrayOptions.itemCell) {
if (Array.isArray(arrayOptions.itemCell)) {
arrayOptions.itemCell = arrayOptions.itemCell.map(cell => normalizeCell(cell, cellDefinitions))
} else {
arrayOptions.itemCell = normalizeCell(arrayOptions.itemCell, cellDefinitions)
}
}
if (arrayOptions.tupleCells) {
arrayOptions.tupleCells = arrayOptions.tupleCells.map(cell => normalizeCell(cell, cellDefinitions))
}
return arrayOptions
} | javascript | function normalizeArrayOptions (cell, cellDefinitions) {
const arrayOptions = _.clone(cell.arrayOptions)
if (arrayOptions.itemCell) {
if (Array.isArray(arrayOptions.itemCell)) {
arrayOptions.itemCell = arrayOptions.itemCell.map(cell => normalizeCell(cell, cellDefinitions))
} else {
arrayOptions.itemCell = normalizeCell(arrayOptions.itemCell, cellDefinitions)
}
}
if (arrayOptions.tupleCells) {
arrayOptions.tupleCells = arrayOptions.tupleCells.map(cell => normalizeCell(cell, cellDefinitions))
}
return arrayOptions
} | [
"function",
"normalizeArrayOptions",
"(",
"cell",
",",
"cellDefinitions",
")",
"{",
"const",
"arrayOptions",
"=",
"_",
".",
"clone",
"(",
"cell",
".",
"arrayOptions",
")",
"if",
"(",
"arrayOptions",
".",
"itemCell",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"arrayOptions",
".",
"itemCell",
")",
")",
"{",
"arrayOptions",
".",
"itemCell",
"=",
"arrayOptions",
".",
"itemCell",
".",
"map",
"(",
"cell",
"=>",
"normalizeCell",
"(",
"cell",
",",
"cellDefinitions",
")",
")",
"}",
"else",
"{",
"arrayOptions",
".",
"itemCell",
"=",
"normalizeCell",
"(",
"arrayOptions",
".",
"itemCell",
",",
"cellDefinitions",
")",
"}",
"}",
"if",
"(",
"arrayOptions",
".",
"tupleCells",
")",
"{",
"arrayOptions",
".",
"tupleCells",
"=",
"arrayOptions",
".",
"tupleCells",
".",
"map",
"(",
"cell",
"=>",
"normalizeCell",
"(",
"cell",
",",
"cellDefinitions",
")",
")",
"}",
"return",
"arrayOptions",
"}"
] | Normalizes cells within arrayOptions
@param {BunsenCell} cell Cell with arrayOptions to normalize
@param {Object} cellDefinitions Hash of cell definitions
@returns {Object} The normalized arrayOptions | [
"Normalizes",
"cells",
"within",
"arrayOptions"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/normalize-model-and-view.js#L113-L126 | train |
ciena-blueplanet/bunsen-core | src/normalize-model-and-view.js | pluckFromArrayOptions | function pluckFromArrayOptions (cell, modelPath, models, cellDefinitions) {
if (cell.arrayOptions.tupleCells) {
cell.arrayOptions.tupleCells.forEach(function (cell, index) {
pluckModels(cell, modelPath.concat(index), models, cellDefinitions)
})
}
if (cell.arrayOptions.itemCell) {
const itemCell = cell.arrayOptions.itemCell
if (Array.isArray(itemCell)) {
itemCell.forEach(function (cell, index) {
pluckModels(cell, modelPath.concat(index), models, cellDefinitions)
})
} else {
pluckModels(itemCell, modelPath.concat('0'), models, cellDefinitions)
}
}
} | javascript | function pluckFromArrayOptions (cell, modelPath, models, cellDefinitions) {
if (cell.arrayOptions.tupleCells) {
cell.arrayOptions.tupleCells.forEach(function (cell, index) {
pluckModels(cell, modelPath.concat(index), models, cellDefinitions)
})
}
if (cell.arrayOptions.itemCell) {
const itemCell = cell.arrayOptions.itemCell
if (Array.isArray(itemCell)) {
itemCell.forEach(function (cell, index) {
pluckModels(cell, modelPath.concat(index), models, cellDefinitions)
})
} else {
pluckModels(itemCell, modelPath.concat('0'), models, cellDefinitions)
}
}
} | [
"function",
"pluckFromArrayOptions",
"(",
"cell",
",",
"modelPath",
",",
"models",
",",
"cellDefinitions",
")",
"{",
"if",
"(",
"cell",
".",
"arrayOptions",
".",
"tupleCells",
")",
"{",
"cell",
".",
"arrayOptions",
".",
"tupleCells",
".",
"forEach",
"(",
"function",
"(",
"cell",
",",
"index",
")",
"{",
"pluckModels",
"(",
"cell",
",",
"modelPath",
".",
"concat",
"(",
"index",
")",
",",
"models",
",",
"cellDefinitions",
")",
"}",
")",
"}",
"if",
"(",
"cell",
".",
"arrayOptions",
".",
"itemCell",
")",
"{",
"const",
"itemCell",
"=",
"cell",
".",
"arrayOptions",
".",
"itemCell",
"if",
"(",
"Array",
".",
"isArray",
"(",
"itemCell",
")",
")",
"{",
"itemCell",
".",
"forEach",
"(",
"function",
"(",
"cell",
",",
"index",
")",
"{",
"pluckModels",
"(",
"cell",
",",
"modelPath",
".",
"concat",
"(",
"index",
")",
",",
"models",
",",
"cellDefinitions",
")",
"}",
")",
"}",
"else",
"{",
"pluckModels",
"(",
"itemCell",
",",
"modelPath",
".",
"concat",
"(",
"'0'",
")",
",",
"models",
",",
"cellDefinitions",
")",
"}",
"}",
"}"
] | Collects schemas from a cell's array options to add to the model in a hash.
@param {BunsenCell} cell BunsenCell with array options
@param {BunsenModelPath} modelPath Current path within the model
@param {Object} models Hash containing schemas to add
@param {Object} cellDefinitions Hash containing cell definitions | [
"Collects",
"schemas",
"from",
"a",
"cell",
"s",
"array",
"options",
"to",
"add",
"to",
"the",
"model",
"in",
"a",
"hash",
"."
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/normalize-model-and-view.js#L191-L207 | train |
ciena-blueplanet/bunsen-core | src/normalize-model-and-view.js | pluckModels | function pluckModels (cell, modelPath, models, cellDefinitions) {
cell = extendCell(cell, cellDefinitions)
if (_.isObject(cell.model)) {
const addedPath = appendModelPath(modelPath.modelPath(), cell.id, cell.internal)
models[addedPath] = cell.model
} else if (cell.children) { // recurse on objects
cell.children.forEach((cell) => {
const newPath = typeof cell.model === 'string' ? modelPath.concat(cell.model) : modelPath
pluckModels(cell, newPath, models, cellDefinitions)
})
} else if (cell.arrayOptions) { // recurse on arrays
pluckFromArrayOptions(cell, modelPath, models, cellDefinitions)
}
} | javascript | function pluckModels (cell, modelPath, models, cellDefinitions) {
cell = extendCell(cell, cellDefinitions)
if (_.isObject(cell.model)) {
const addedPath = appendModelPath(modelPath.modelPath(), cell.id, cell.internal)
models[addedPath] = cell.model
} else if (cell.children) { // recurse on objects
cell.children.forEach((cell) => {
const newPath = typeof cell.model === 'string' ? modelPath.concat(cell.model) : modelPath
pluckModels(cell, newPath, models, cellDefinitions)
})
} else if (cell.arrayOptions) { // recurse on arrays
pluckFromArrayOptions(cell, modelPath, models, cellDefinitions)
}
} | [
"function",
"pluckModels",
"(",
"cell",
",",
"modelPath",
",",
"models",
",",
"cellDefinitions",
")",
"{",
"cell",
"=",
"extendCell",
"(",
"cell",
",",
"cellDefinitions",
")",
"if",
"(",
"_",
".",
"isObject",
"(",
"cell",
".",
"model",
")",
")",
"{",
"const",
"addedPath",
"=",
"appendModelPath",
"(",
"modelPath",
".",
"modelPath",
"(",
")",
",",
"cell",
".",
"id",
",",
"cell",
".",
"internal",
")",
"models",
"[",
"addedPath",
"]",
"=",
"cell",
".",
"model",
"}",
"else",
"if",
"(",
"cell",
".",
"children",
")",
"{",
"// recurse on objects",
"cell",
".",
"children",
".",
"forEach",
"(",
"(",
"cell",
")",
"=>",
"{",
"const",
"newPath",
"=",
"typeof",
"cell",
".",
"model",
"===",
"'string'",
"?",
"modelPath",
".",
"concat",
"(",
"cell",
".",
"model",
")",
":",
"modelPath",
"pluckModels",
"(",
"cell",
",",
"newPath",
",",
"models",
",",
"cellDefinitions",
")",
"}",
")",
"}",
"else",
"if",
"(",
"cell",
".",
"arrayOptions",
")",
"{",
"// recurse on arrays",
"pluckFromArrayOptions",
"(",
"cell",
",",
"modelPath",
",",
"models",
",",
"cellDefinitions",
")",
"}",
"}"
] | Collects schemas from a cell to add to the model in a hash. Keys in the hash are
the schema's path withinthe bunsen model.
@param {BunsenCell} cell BunsenCell with array options
@param {BunsenModelPath} modelPath Current path within the model
@param {Object} models Hash containing schemas to add
@param {Object} cellDefinitions Hash containing cell definitions | [
"Collects",
"schemas",
"from",
"a",
"cell",
"to",
"add",
"to",
"the",
"model",
"in",
"a",
"hash",
".",
"Keys",
"in",
"the",
"hash",
"are",
"the",
"schema",
"s",
"path",
"withinthe",
"bunsen",
"model",
"."
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/normalize-model-and-view.js#L218-L231 | train |
ciena-blueplanet/bunsen-core | src/normalize-model-and-view.js | aggregateModels | function aggregateModels (view, modelPath) {
const models = {}
view.cells.forEach(function (cell) {
const newPath = typeof cell.model === 'string' ? modelPath.concat(cell.model) : modelPath
pluckModels(cell, newPath, models, view.cellDefinitions)
})
return models
} | javascript | function aggregateModels (view, modelPath) {
const models = {}
view.cells.forEach(function (cell) {
const newPath = typeof cell.model === 'string' ? modelPath.concat(cell.model) : modelPath
pluckModels(cell, newPath, models, view.cellDefinitions)
})
return models
} | [
"function",
"aggregateModels",
"(",
"view",
",",
"modelPath",
")",
"{",
"const",
"models",
"=",
"{",
"}",
"view",
".",
"cells",
".",
"forEach",
"(",
"function",
"(",
"cell",
")",
"{",
"const",
"newPath",
"=",
"typeof",
"cell",
".",
"model",
"===",
"'string'",
"?",
"modelPath",
".",
"concat",
"(",
"cell",
".",
"model",
")",
":",
"modelPath",
"pluckModels",
"(",
"cell",
",",
"newPath",
",",
"models",
",",
"view",
".",
"cellDefinitions",
")",
"}",
")",
"return",
"models",
"}"
] | Collects schemas from a cell to add to the model in a hash.
@param {BunsenView} view View to check for additional schemas
@param {BunsenModelPath} modelPath Path to start within the model
@returns {Object} Hash of schemas. The keys are paths within the model | [
"Collects",
"schemas",
"from",
"a",
"cell",
"to",
"add",
"to",
"the",
"model",
"in",
"a",
"hash",
"."
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/normalize-model-and-view.js#L240-L247 | train |
ciena-blueplanet/bunsen-core | src/normalize-model-and-view.js | expandModel | function expandModel (model, view) {
const modelPath = new BunsenModelPath(model)
const modelExpansions = aggregateModels(view, modelPath)
let newModel = model
_.forEach(modelExpansions, (propertyModel, path) => {
newModel = addBunsenModelProperty(newModel, propertyModel, path)
})
return newModel
} | javascript | function expandModel (model, view) {
const modelPath = new BunsenModelPath(model)
const modelExpansions = aggregateModels(view, modelPath)
let newModel = model
_.forEach(modelExpansions, (propertyModel, path) => {
newModel = addBunsenModelProperty(newModel, propertyModel, path)
})
return newModel
} | [
"function",
"expandModel",
"(",
"model",
",",
"view",
")",
"{",
"const",
"modelPath",
"=",
"new",
"BunsenModelPath",
"(",
"model",
")",
"const",
"modelExpansions",
"=",
"aggregateModels",
"(",
"view",
",",
"modelPath",
")",
"let",
"newModel",
"=",
"model",
"_",
".",
"forEach",
"(",
"modelExpansions",
",",
"(",
"propertyModel",
",",
"path",
")",
"=>",
"{",
"newModel",
"=",
"addBunsenModelProperty",
"(",
"newModel",
",",
"propertyModel",
",",
"path",
")",
"}",
")",
"return",
"newModel",
"}"
] | Adds to an existing bunsen model with schemas defined in the view
@param {BunsenModel} model Model to expand
@param {BunsenView} view View containing additional schema
@returns {BunsenModel} Expanded version of the model | [
"Adds",
"to",
"an",
"existing",
"bunsen",
"model",
"with",
"schemas",
"defined",
"in",
"the",
"view"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/normalize-model-and-view.js#L256-L264 | train |
godaddy/asset-system | examples/web/server.js | svgs | function svgs(req, res) {
const bundle = new Bundle(
req.url.slice(1, -5).split('-').map(function map(name) {
return assets[name];
})
);
bundle.run(function (err, output) {
if (err) throw err;
res.setHeader('Content-Length', Buffer(output).length);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(output);
});
} | javascript | function svgs(req, res) {
const bundle = new Bundle(
req.url.slice(1, -5).split('-').map(function map(name) {
return assets[name];
})
);
bundle.run(function (err, output) {
if (err) throw err;
res.setHeader('Content-Length', Buffer(output).length);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(output);
});
} | [
"function",
"svgs",
"(",
"req",
",",
"res",
")",
"{",
"const",
"bundle",
"=",
"new",
"Bundle",
"(",
"req",
".",
"url",
".",
"slice",
"(",
"1",
",",
"-",
"5",
")",
".",
"split",
"(",
"'-'",
")",
".",
"map",
"(",
"function",
"map",
"(",
"name",
")",
"{",
"return",
"assets",
"[",
"name",
"]",
";",
"}",
")",
")",
";",
"bundle",
".",
"run",
"(",
"function",
"(",
"err",
",",
"output",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"res",
".",
"setHeader",
"(",
"'Content-Length'",
",",
"Buffer",
"(",
"output",
")",
".",
"length",
")",
";",
"res",
".",
"writeHead",
"(",
"200",
",",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"end",
"(",
"output",
")",
";",
"}",
")",
";",
"}"
] | Serve the bundle.svgs.
@param {Request} req HTTP request.
@param {Response} res HTTP response.
@private | [
"Serve",
"the",
"bundle",
".",
"svgs",
"."
] | 897fe43f48e65b132f489aea4ba6d74d688a62f8 | https://github.com/godaddy/asset-system/blob/897fe43f48e65b132f489aea4ba6d74d688a62f8/examples/web/server.js#L22-L37 | train |
godaddy/asset-system | examples/web/server.js | html | function html(req, res) {
fs.readFile(path.join(__dirname, 'index.html'), function read(err, file) {
if (err) throw err;
res.setHeader('Content-Length', file.length);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(file);
});
} | javascript | function html(req, res) {
fs.readFile(path.join(__dirname, 'index.html'), function read(err, file) {
if (err) throw err;
res.setHeader('Content-Length', file.length);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(file);
});
} | [
"function",
"html",
"(",
"req",
",",
"res",
")",
"{",
"fs",
".",
"readFile",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'index.html'",
")",
",",
"function",
"read",
"(",
"err",
",",
"file",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"res",
".",
"setHeader",
"(",
"'Content-Length'",
",",
"file",
".",
"length",
")",
";",
"res",
".",
"writeHead",
"(",
"200",
",",
"{",
"'Content-Type'",
":",
"'text/html'",
"}",
")",
";",
"res",
".",
"end",
"(",
"file",
")",
";",
"}",
")",
";",
"}"
] | Serve the index.html
@param {Request} req HTTP request.
@param {Response} res HTTP response.
@private | [
"Serve",
"the",
"index",
".",
"html"
] | 897fe43f48e65b132f489aea4ba6d74d688a62f8 | https://github.com/godaddy/asset-system/blob/897fe43f48e65b132f489aea4ba6d74d688a62f8/examples/web/server.js#L46-L55 | train |
godaddy/asset-system | examples/web/server.js | client | function client(req, res) {
const compiler = webpack(config);
compiler.outputFileSystem = fsys;
compiler.run((err, stats) => {
const file = fsys.readFileSync(path.join(__dirname, 'dist', 'client.js'));
res.setHeader('Content-Length', file.length);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(file);
});
} | javascript | function client(req, res) {
const compiler = webpack(config);
compiler.outputFileSystem = fsys;
compiler.run((err, stats) => {
const file = fsys.readFileSync(path.join(__dirname, 'dist', 'client.js'));
res.setHeader('Content-Length', file.length);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(file);
});
} | [
"function",
"client",
"(",
"req",
",",
"res",
")",
"{",
"const",
"compiler",
"=",
"webpack",
"(",
"config",
")",
";",
"compiler",
".",
"outputFileSystem",
"=",
"fsys",
";",
"compiler",
".",
"run",
"(",
"(",
"err",
",",
"stats",
")",
"=>",
"{",
"const",
"file",
"=",
"fsys",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'dist'",
",",
"'client.js'",
")",
")",
";",
"res",
".",
"setHeader",
"(",
"'Content-Length'",
",",
"file",
".",
"length",
")",
";",
"res",
".",
"writeHead",
"(",
"200",
",",
"{",
"'Content-Type'",
":",
"'text/javascript'",
"}",
")",
";",
"res",
".",
"end",
"(",
"file",
")",
";",
"}",
")",
";",
"}"
] | Serve the index.js client bundle.
@param {Request} req HTTP request.
@param {Response} res HTTP response.
@private | [
"Serve",
"the",
"index",
".",
"js",
"client",
"bundle",
"."
] | 897fe43f48e65b132f489aea4ba6d74d688a62f8 | https://github.com/godaddy/asset-system/blob/897fe43f48e65b132f489aea4ba6d74d688a62f8/examples/web/server.js#L64-L76 | train |
ciena-blueplanet/bunsen-core | src/conversion/view-v1-to-v2.js | convertObjectCell | function convertObjectCell (cell) {
return _.chain(cell.rows)
.map(rowsToCells)
.assign(_.pick(cell, CARRY_OVER_PROPERTIES))
.value()
} | javascript | function convertObjectCell (cell) {
return _.chain(cell.rows)
.map(rowsToCells)
.assign(_.pick(cell, CARRY_OVER_PROPERTIES))
.value()
} | [
"function",
"convertObjectCell",
"(",
"cell",
")",
"{",
"return",
"_",
".",
"chain",
"(",
"cell",
".",
"rows",
")",
".",
"map",
"(",
"rowsToCells",
")",
".",
"assign",
"(",
"_",
".",
"pick",
"(",
"cell",
",",
"CARRY_OVER_PROPERTIES",
")",
")",
".",
"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 | [
"Converts",
"an",
"complex",
"container",
"cell",
"for",
"an",
"object",
"into",
"a",
"v2",
"cell"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/conversion/view-v1-to-v2.js#L23-L28 | train |
ciena-blueplanet/bunsen-core | src/conversion/view-v1-to-v2.js | convertArrayCell | function convertArrayCell (cell) {
const {item} = cell
const arrayOptions = _.chain(item)
.pick(ARRAY_CELL_PROPERTIES)
.assign({
itemCell: convertCell(item)
})
.value()
return {
arrayOptions,
model: cell.model
}
} | javascript | function convertArrayCell (cell) {
const {item} = cell
const arrayOptions = _.chain(item)
.pick(ARRAY_CELL_PROPERTIES)
.assign({
itemCell: convertCell(item)
})
.value()
return {
arrayOptions,
model: cell.model
}
} | [
"function",
"convertArrayCell",
"(",
"cell",
")",
"{",
"const",
"{",
"item",
"}",
"=",
"cell",
"const",
"arrayOptions",
"=",
"_",
".",
"chain",
"(",
"item",
")",
".",
"pick",
"(",
"ARRAY_CELL_PROPERTIES",
")",
".",
"assign",
"(",
"{",
"itemCell",
":",
"convertCell",
"(",
"item",
")",
"}",
")",
".",
"value",
"(",
")",
"return",
"{",
"arrayOptions",
",",
"model",
":",
"cell",
".",
"model",
"}",
"}"
] | 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 | [
"Converts",
"a",
"container",
"cell",
"that",
"displays",
"an",
"array",
"into",
"a",
"v2",
"cell"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/conversion/view-v1-to-v2.js#L36-L48 | train |
ciena-blueplanet/bunsen-core | src/conversion/view-v1-to-v2.js | convertRenderer | 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)
} | javascript | 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)
} | [
"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",
")",
"}"
] | 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 | [
"Converts",
"v1",
"renderer",
"information",
"to",
"v2",
"for",
"a",
"cell"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/conversion/view-v1-to-v2.js#L69-L83 | train |
ciena-blueplanet/bunsen-core | src/conversion/view-v1-to-v2.js | grabClassNames | function grabClassNames (cell) {
const classNames = _.pickBy({
cell: cell.className,
value: cell.inputClassName,
label: cell.labelClassName
})
if (_.size(classNames) > 0) {
return classNames
}
} | javascript | function grabClassNames (cell) {
const classNames = _.pickBy({
cell: cell.className,
value: cell.inputClassName,
label: cell.labelClassName
})
if (_.size(classNames) > 0) {
return classNames
}
} | [
"function",
"grabClassNames",
"(",
"cell",
")",
"{",
"const",
"classNames",
"=",
"_",
".",
"pickBy",
"(",
"{",
"cell",
":",
"cell",
".",
"className",
",",
"value",
":",
"cell",
".",
"inputClassName",
",",
"label",
":",
"cell",
".",
"labelClassName",
"}",
")",
"if",
"(",
"_",
".",
"size",
"(",
"classNames",
")",
">",
"0",
")",
"{",
"return",
"classNames",
"}",
"}"
] | Creates class name block for v2 cell
@param {object} cell Cell to get class names from
@returns {object} Class name block for the cell | [
"Creates",
"class",
"name",
"block",
"for",
"v2",
"cell"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/conversion/view-v1-to-v2.js#L91-L100 | train |
ciena-blueplanet/bunsen-core | src/conversion/view-v1-to-v2.js | rowsToCells | function rowsToCells (rows) {
if (!rows) {
return {}
}
const children = rows
.map((row) => {
return {
children: _.map(row, convertCell)
}
})
return {
children
}
} | javascript | function rowsToCells (rows) {
if (!rows) {
return {}
}
const children = rows
.map((row) => {
return {
children: _.map(row, convertCell)
}
})
return {
children
}
} | [
"function",
"rowsToCells",
"(",
"rows",
")",
"{",
"if",
"(",
"!",
"rows",
")",
"{",
"return",
"{",
"}",
"}",
"const",
"children",
"=",
"rows",
".",
"map",
"(",
"(",
"row",
")",
"=>",
"{",
"return",
"{",
"children",
":",
"_",
".",
"map",
"(",
"row",
",",
"convertCell",
")",
"}",
"}",
")",
"return",
"{",
"children",
"}",
"}"
] | 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 | [
"Converts",
"rows",
"of",
"v1",
"cells",
"to",
"v2",
"cells",
".",
"Simplifies",
"the",
"row",
"structure",
"when",
"possible",
"."
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/conversion/view-v1-to-v2.js#L143-L158 | train |
godaddy/asset-system | packages/bundle/dimensions/index.js | warning | function warning(lines) {
lines.unshift(''); // Extra whitespace at the start.
lines.push(''); // Extra whitespace at the end.
lines.forEach(function each(line) {
console.error('asset-bundle:warning', line);
});
} | javascript | function warning(lines) {
lines.unshift(''); // Extra whitespace at the start.
lines.push(''); // Extra whitespace at the end.
lines.forEach(function each(line) {
console.error('asset-bundle:warning', line);
});
} | [
"function",
"warning",
"(",
"lines",
")",
"{",
"lines",
".",
"unshift",
"(",
"''",
")",
";",
"// Extra whitespace at the start.",
"lines",
".",
"push",
"(",
"''",
")",
";",
"// Extra whitespace at the end.",
"lines",
".",
"forEach",
"(",
"function",
"each",
"(",
"line",
")",
"{",
"console",
".",
"error",
"(",
"'asset-bundle:warning'",
",",
"line",
")",
";",
"}",
")",
";",
"}"
] | Really stupid simple warning output.
@param {Array} lines The messages that needs to be spammed.
@private | [
"Really",
"stupid",
"simple",
"warning",
"output",
"."
] | 897fe43f48e65b132f489aea4ba6d74d688a62f8 | https://github.com/godaddy/asset-system/blob/897fe43f48e65b132f489aea4ba6d74d688a62f8/packages/bundle/dimensions/index.js#L12-L19 | train |
godaddy/asset-system | packages/bundle/dimensions/index.js | viewBox | function viewBox(details) {
svg.viewBox = `${details.x || 0} ${details.y || 0} ${details.width} ${details.height}`;
fn(null, svg);
} | javascript | function viewBox(details) {
svg.viewBox = `${details.x || 0} ${details.y || 0} ${details.width} ${details.height}`;
fn(null, svg);
} | [
"function",
"viewBox",
"(",
"details",
")",
"{",
"svg",
".",
"viewBox",
"=",
"`",
"${",
"details",
".",
"x",
"||",
"0",
"}",
"${",
"details",
".",
"y",
"||",
"0",
"}",
"${",
"details",
".",
"width",
"}",
"${",
"details",
".",
"height",
"}",
"`",
";",
"fn",
"(",
"null",
",",
"svg",
")",
";",
"}"
] | Compile a viewBox from the given.
@param {Object} details The width/height for the viewBox.
@private | [
"Compile",
"a",
"viewBox",
"from",
"the",
"given",
"."
] | 897fe43f48e65b132f489aea4ba6d74d688a62f8 | https://github.com/godaddy/asset-system/blob/897fe43f48e65b132f489aea4ba6d74d688a62f8/packages/bundle/dimensions/index.js#L36-L40 | train |
NLeSC/spot | src/widgets/models/slot.js | function () {
var filter = this.collection.parent.filter;
if (!filter || !this.isFilled) {
return false;
}
filter.releaseDataFilter();
if (this.type === 'partition') {
var partition = filter.partitions.get(this.rank, 'rank');
filter.partitions.remove(partition);
} else if (this.type === 'aggregate') {
var aggregate = filter.aggregates.get(this.rank, 'rank');
filter.aggregates.remove(aggregate);
}
this.isFilled = false;
return true;
} | javascript | function () {
var filter = this.collection.parent.filter;
if (!filter || !this.isFilled) {
return false;
}
filter.releaseDataFilter();
if (this.type === 'partition') {
var partition = filter.partitions.get(this.rank, 'rank');
filter.partitions.remove(partition);
} else if (this.type === 'aggregate') {
var aggregate = filter.aggregates.get(this.rank, 'rank');
filter.aggregates.remove(aggregate);
}
this.isFilled = false;
return true;
} | [
"function",
"(",
")",
"{",
"var",
"filter",
"=",
"this",
".",
"collection",
".",
"parent",
".",
"filter",
";",
"if",
"(",
"!",
"filter",
"||",
"!",
"this",
".",
"isFilled",
")",
"{",
"return",
"false",
";",
"}",
"filter",
".",
"releaseDataFilter",
"(",
")",
";",
"if",
"(",
"this",
".",
"type",
"===",
"'partition'",
")",
"{",
"var",
"partition",
"=",
"filter",
".",
"partitions",
".",
"get",
"(",
"this",
".",
"rank",
",",
"'rank'",
")",
";",
"filter",
".",
"partitions",
".",
"remove",
"(",
"partition",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"type",
"===",
"'aggregate'",
")",
"{",
"var",
"aggregate",
"=",
"filter",
".",
"aggregates",
".",
"get",
"(",
"this",
".",
"rank",
",",
"'rank'",
")",
";",
"filter",
".",
"aggregates",
".",
"remove",
"(",
"aggregate",
")",
";",
"}",
"this",
".",
"isFilled",
"=",
"false",
";",
"return",
"true",
";",
"}"
] | Remove facet from the slot
@returns {boolean} succes True if something was removed | [
"Remove",
"facet",
"from",
"the",
"slot"
] | 8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417 | https://github.com/NLeSC/spot/blob/8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417/src/widgets/models/slot.js#L55-L71 | train |
|
jacob-meacham/serverless-plugin-offline-kinesis-events | src/index.js | getWebpackRunnableLambda | function getWebpackRunnableLambda(slsWebpack, stats, functionName) {
const handler = slsWebpack.loadHandler(stats, functionName, true)
const context = slsWebpack.getContext(functionName)
return wrapHandler(handler, context)
} | javascript | function getWebpackRunnableLambda(slsWebpack, stats, functionName) {
const handler = slsWebpack.loadHandler(stats, functionName, true)
const context = slsWebpack.getContext(functionName)
return wrapHandler(handler, context)
} | [
"function",
"getWebpackRunnableLambda",
"(",
"slsWebpack",
",",
"stats",
",",
"functionName",
")",
"{",
"const",
"handler",
"=",
"slsWebpack",
".",
"loadHandler",
"(",
"stats",
",",
"functionName",
",",
"true",
")",
"const",
"context",
"=",
"slsWebpack",
".",
"getContext",
"(",
"functionName",
")",
"return",
"wrapHandler",
"(",
"handler",
",",
"context",
")",
"}"
] | Based on ServerlessWebpack.run
@param stats | [
"Based",
"on",
"ServerlessWebpack",
".",
"run"
] | 343a7fa29c269a00553f24a56207bffd764001c3 | https://github.com/jacob-meacham/serverless-plugin-offline-kinesis-events/blob/343a7fa29c269a00553f24a56207bffd764001c3/src/index.js#L23-L27 | train |
NLeSC/spot | src/widgets/views/chartjs1d.js | onClick | function onClick (ev, elements) {
var model = this._Ampersandview.model;
var partition = model.filter.partitions.get(1, 'rank');
if (elements.length > 0) {
partition.updateSelection(partition.groups.models[elements[0]._index]);
model.filter.updateDataFilter();
app.me.dataview.getData();
}
} | javascript | function onClick (ev, elements) {
var model = this._Ampersandview.model;
var partition = model.filter.partitions.get(1, 'rank');
if (elements.length > 0) {
partition.updateSelection(partition.groups.models[elements[0]._index]);
model.filter.updateDataFilter();
app.me.dataview.getData();
}
} | [
"function",
"onClick",
"(",
"ev",
",",
"elements",
")",
"{",
"var",
"model",
"=",
"this",
".",
"_Ampersandview",
".",
"model",
";",
"var",
"partition",
"=",
"model",
".",
"filter",
".",
"partitions",
".",
"get",
"(",
"1",
",",
"'rank'",
")",
";",
"if",
"(",
"elements",
".",
"length",
">",
"0",
")",
"{",
"partition",
".",
"updateSelection",
"(",
"partition",
".",
"groups",
".",
"models",
"[",
"elements",
"[",
"0",
"]",
".",
"_index",
"]",
")",
";",
"model",
".",
"filter",
".",
"updateDataFilter",
"(",
")",
";",
"app",
".",
"me",
".",
"dataview",
".",
"getData",
"(",
")",
";",
"}",
"}"
] | Called by Chartjs, this -> chart instance | [
"Called",
"by",
"Chartjs",
"this",
"-",
">",
"chart",
"instance"
] | 8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417 | https://github.com/NLeSC/spot/blob/8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417/src/widgets/views/chartjs1d.js#L10-L19 | train |
NLeSC/spot | src/colors.js | getColor | function getColor (i) {
i = parseInt(i);
if (i < 0 || i >= colors.length) {
// pick a color from the scale defined above
return scale(((i - colors.length) * (211 / 971)) % 1);
} else {
return chroma(colors[i]);
}
} | javascript | function getColor (i) {
i = parseInt(i);
if (i < 0 || i >= colors.length) {
// pick a color from the scale defined above
return scale(((i - colors.length) * (211 / 971)) % 1);
} else {
return chroma(colors[i]);
}
} | [
"function",
"getColor",
"(",
"i",
")",
"{",
"i",
"=",
"parseInt",
"(",
"i",
")",
";",
"if",
"(",
"i",
"<",
"0",
"||",
"i",
">=",
"colors",
".",
"length",
")",
"{",
"// pick a color from the scale defined above",
"return",
"scale",
"(",
"(",
"(",
"i",
"-",
"colors",
".",
"length",
")",
"*",
"(",
"211",
"/",
"971",
")",
")",
"%",
"1",
")",
";",
"}",
"else",
"{",
"return",
"chroma",
"(",
"colors",
"[",
"i",
"]",
")",
";",
"}",
"}"
] | Get i-th color
@param {number} color number
@returns {Object} color | [
"Get",
"i",
"-",
"th",
"color"
] | 8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417 | https://github.com/NLeSC/spot/blob/8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417/src/colors.js#L21-L29 | train |
uzyn/web3-loader | index.js | init | function init(loader) {
var loaderConfig = loaderUtils.getLoaderConfig(loader, 'web3Loader');
web3 = require('./lib/web3')(loaderConfig.provider);
config = mergeConfig(loaderConfig);
isDebug = loader.debug;
} | javascript | function init(loader) {
var loaderConfig = loaderUtils.getLoaderConfig(loader, 'web3Loader');
web3 = require('./lib/web3')(loaderConfig.provider);
config = mergeConfig(loaderConfig);
isDebug = loader.debug;
} | [
"function",
"init",
"(",
"loader",
")",
"{",
"var",
"loaderConfig",
"=",
"loaderUtils",
".",
"getLoaderConfig",
"(",
"loader",
",",
"'web3Loader'",
")",
";",
"web3",
"=",
"require",
"(",
"'./lib/web3'",
")",
"(",
"loaderConfig",
".",
"provider",
")",
";",
"config",
"=",
"mergeConfig",
"(",
"loaderConfig",
")",
";",
"isDebug",
"=",
"loader",
".",
"debug",
";",
"}"
] | Initialize the loader with web3 and config | [
"Initialize",
"the",
"loader",
"with",
"web3",
"and",
"config"
] | 54055e95fd37bc23b0aed4a6b7f182890b7f3cf4 | https://github.com/uzyn/web3-loader/blob/54055e95fd37bc23b0aed4a6b7f182890b7f3cf4/index.js#L48-L53 | train |
uzyn/web3-loader | index.js | mergeConfig | function mergeConfig(loaderConfig) {
var defaultConfig = {
// Web3
provider: 'http://localhost:8545',
// For deployment
from: web3.eth.accounts[0],
gasLimit: web3.eth.getBlock(web3.eth.defaultBlock).gasLimit,
// Specify contract constructor parameters, if any.
// constructorParams: {
// ContractOne: [ 'param1_value', 'param2_value' ]
// }
constructorParams: {},
// To use deployed contracts instead of redeploying, include contract addresses in config
// deployedContracts: {
// ContractOne: '0x...........',
// ContractTwo: '0x...........',
// }
deployedContracts: {}
};
var mergedConfig = loaderConfig;
for (var key in defaultConfig) {
if (!mergedConfig.hasOwnProperty(key)) {
mergedConfig[key] = defaultConfig[key];
}
}
return mergedConfig;
} | javascript | function mergeConfig(loaderConfig) {
var defaultConfig = {
// Web3
provider: 'http://localhost:8545',
// For deployment
from: web3.eth.accounts[0],
gasLimit: web3.eth.getBlock(web3.eth.defaultBlock).gasLimit,
// Specify contract constructor parameters, if any.
// constructorParams: {
// ContractOne: [ 'param1_value', 'param2_value' ]
// }
constructorParams: {},
// To use deployed contracts instead of redeploying, include contract addresses in config
// deployedContracts: {
// ContractOne: '0x...........',
// ContractTwo: '0x...........',
// }
deployedContracts: {}
};
var mergedConfig = loaderConfig;
for (var key in defaultConfig) {
if (!mergedConfig.hasOwnProperty(key)) {
mergedConfig[key] = defaultConfig[key];
}
}
return mergedConfig;
} | [
"function",
"mergeConfig",
"(",
"loaderConfig",
")",
"{",
"var",
"defaultConfig",
"=",
"{",
"// Web3",
"provider",
":",
"'http://localhost:8545'",
",",
"// For deployment",
"from",
":",
"web3",
".",
"eth",
".",
"accounts",
"[",
"0",
"]",
",",
"gasLimit",
":",
"web3",
".",
"eth",
".",
"getBlock",
"(",
"web3",
".",
"eth",
".",
"defaultBlock",
")",
".",
"gasLimit",
",",
"// Specify contract constructor parameters, if any.",
"// constructorParams: {",
"// ContractOne: [ 'param1_value', 'param2_value' ]",
"// }",
"constructorParams",
":",
"{",
"}",
",",
"// To use deployed contracts instead of redeploying, include contract addresses in config",
"// deployedContracts: {",
"// ContractOne: '0x...........',",
"// ContractTwo: '0x...........',",
"// }",
"deployedContracts",
":",
"{",
"}",
"}",
";",
"var",
"mergedConfig",
"=",
"loaderConfig",
";",
"for",
"(",
"var",
"key",
"in",
"defaultConfig",
")",
"{",
"if",
"(",
"!",
"mergedConfig",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"mergedConfig",
"[",
"key",
"]",
"=",
"defaultConfig",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"mergedConfig",
";",
"}"
] | Merge loaderConfig and default configurations | [
"Merge",
"loaderConfig",
"and",
"default",
"configurations"
] | 54055e95fd37bc23b0aed4a6b7f182890b7f3cf4 | https://github.com/uzyn/web3-loader/blob/54055e95fd37bc23b0aed4a6b7f182890b7f3cf4/index.js#L58-L88 | train |
uzyn/web3-loader | index.js | deploy | function deploy(contract, callback, contractMap) {
// Reuse existing contract address
if (config.deployedContracts.hasOwnProperty(contract.name)) {
contract.address = config.deployedContracts[contract.name];
return callback(null, contract);
}
linkBytecode(contract, contractMap);
// Deploy a new one
var params = resolveConstructorParams(contract, contractMap);
logDebug('Constructor params ' + contract.name + ':', params);
if(contract.bytecode && !contract.bytecode.startsWith('0x')) {
contract.bytecode = '0x' + contract.bytecode;
}
params.push({
from: config.from,
data: contract.bytecode,
gas: config.gasLimit,
});
params.push(function (err, deployed) {
if (err) {
return callback(err);
}
if (typeof deployed.address !== 'undefined') {
contract.address = deployed.address;
return callback(null, contract);
}
});
var web3Contract = web3.eth.contract(contract.abi);
web3Contract.new.apply(web3Contract, params);
} | javascript | function deploy(contract, callback, contractMap) {
// Reuse existing contract address
if (config.deployedContracts.hasOwnProperty(contract.name)) {
contract.address = config.deployedContracts[contract.name];
return callback(null, contract);
}
linkBytecode(contract, contractMap);
// Deploy a new one
var params = resolveConstructorParams(contract, contractMap);
logDebug('Constructor params ' + contract.name + ':', params);
if(contract.bytecode && !contract.bytecode.startsWith('0x')) {
contract.bytecode = '0x' + contract.bytecode;
}
params.push({
from: config.from,
data: contract.bytecode,
gas: config.gasLimit,
});
params.push(function (err, deployed) {
if (err) {
return callback(err);
}
if (typeof deployed.address !== 'undefined') {
contract.address = deployed.address;
return callback(null, contract);
}
});
var web3Contract = web3.eth.contract(contract.abi);
web3Contract.new.apply(web3Contract, params);
} | [
"function",
"deploy",
"(",
"contract",
",",
"callback",
",",
"contractMap",
")",
"{",
"// Reuse existing contract address",
"if",
"(",
"config",
".",
"deployedContracts",
".",
"hasOwnProperty",
"(",
"contract",
".",
"name",
")",
")",
"{",
"contract",
".",
"address",
"=",
"config",
".",
"deployedContracts",
"[",
"contract",
".",
"name",
"]",
";",
"return",
"callback",
"(",
"null",
",",
"contract",
")",
";",
"}",
"linkBytecode",
"(",
"contract",
",",
"contractMap",
")",
";",
"// Deploy a new one",
"var",
"params",
"=",
"resolveConstructorParams",
"(",
"contract",
",",
"contractMap",
")",
";",
"logDebug",
"(",
"'Constructor params '",
"+",
"contract",
".",
"name",
"+",
"':'",
",",
"params",
")",
";",
"if",
"(",
"contract",
".",
"bytecode",
"&&",
"!",
"contract",
".",
"bytecode",
".",
"startsWith",
"(",
"'0x'",
")",
")",
"{",
"contract",
".",
"bytecode",
"=",
"'0x'",
"+",
"contract",
".",
"bytecode",
";",
"}",
"params",
".",
"push",
"(",
"{",
"from",
":",
"config",
".",
"from",
",",
"data",
":",
"contract",
".",
"bytecode",
",",
"gas",
":",
"config",
".",
"gasLimit",
",",
"}",
")",
";",
"params",
".",
"push",
"(",
"function",
"(",
"err",
",",
"deployed",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"if",
"(",
"typeof",
"deployed",
".",
"address",
"!==",
"'undefined'",
")",
"{",
"contract",
".",
"address",
"=",
"deployed",
".",
"address",
";",
"return",
"callback",
"(",
"null",
",",
"contract",
")",
";",
"}",
"}",
")",
";",
"var",
"web3Contract",
"=",
"web3",
".",
"eth",
".",
"contract",
"(",
"contract",
".",
"abi",
")",
";",
"web3Contract",
".",
"new",
".",
"apply",
"(",
"web3Contract",
",",
"params",
")",
";",
"}"
] | Deploy contracts, if it is not already deployed | [
"Deploy",
"contracts",
"if",
"it",
"is",
"not",
"already",
"deployed"
] | 54055e95fd37bc23b0aed4a6b7f182890b7f3cf4 | https://github.com/uzyn/web3-loader/blob/54055e95fd37bc23b0aed4a6b7f182890b7f3cf4/index.js#L93-L125 | train |
ciena-blueplanet/bunsen-core | src/validator/index.js | _validateRootAttributes | function _validateRootAttributes (view, model, cellValidator) {
const results = [
_validateCells(view, model, cellValidator)
]
const knownAttributes = ['version', 'type', 'cells', 'cellDefinitions']
const unknownAttributes = _.difference(Object.keys(view), knownAttributes)
results.push({
errors: [],
warnings: _.map(unknownAttributes, (attr) => {
return {
path: '#',
message: `Unrecognized attribute "${attr}"`
}
})
})
return aggregateResults(results)
} | javascript | function _validateRootAttributes (view, model, cellValidator) {
const results = [
_validateCells(view, model, cellValidator)
]
const knownAttributes = ['version', 'type', 'cells', 'cellDefinitions']
const unknownAttributes = _.difference(Object.keys(view), knownAttributes)
results.push({
errors: [],
warnings: _.map(unknownAttributes, (attr) => {
return {
path: '#',
message: `Unrecognized attribute "${attr}"`
}
})
})
return aggregateResults(results)
} | [
"function",
"_validateRootAttributes",
"(",
"view",
",",
"model",
",",
"cellValidator",
")",
"{",
"const",
"results",
"=",
"[",
"_validateCells",
"(",
"view",
",",
"model",
",",
"cellValidator",
")",
"]",
"const",
"knownAttributes",
"=",
"[",
"'version'",
",",
"'type'",
",",
"'cells'",
",",
"'cellDefinitions'",
"]",
"const",
"unknownAttributes",
"=",
"_",
".",
"difference",
"(",
"Object",
".",
"keys",
"(",
"view",
")",
",",
"knownAttributes",
")",
"results",
".",
"push",
"(",
"{",
"errors",
":",
"[",
"]",
",",
"warnings",
":",
"_",
".",
"map",
"(",
"unknownAttributes",
",",
"(",
"attr",
")",
"=>",
"{",
"return",
"{",
"path",
":",
"'#'",
",",
"message",
":",
"`",
"${",
"attr",
"}",
"`",
"}",
"}",
")",
"}",
")",
"return",
"aggregateResults",
"(",
"results",
")",
"}"
] | Validate the root attributes of the view
@param {BunsenView} view - the view to validate
@param {BunsenModel} model - the JSON schema that the cells will reference
@param {CellValidator} cellValidator - the validator instance for a cell in the current view
@returns {BunsenValidationResult} any errors found | [
"Validate",
"the",
"root",
"attributes",
"of",
"the",
"view"
] | 993c67e314e2b75003a1ff4c2f0cb667715562b2 | https://github.com/ciena-blueplanet/bunsen-core/blob/993c67e314e2b75003a1ff4c2f0cb667715562b2/src/validator/index.js#L79-L97 | train |
NLeSC/spot | src/app.js | function () {
// Create and attach our main view
this.mainView = new MainView({
model: this.me,
el: document.body
});
// this kicks off our backbutton tracking (browser history)
// and will cause the first matching handler in the router
// to fire.
this.router.history.start({
root: '/',
pushState: true
});
} | javascript | function () {
// Create and attach our main view
this.mainView = new MainView({
model: this.me,
el: document.body
});
// this kicks off our backbutton tracking (browser history)
// and will cause the first matching handler in the router
// to fire.
this.router.history.start({
root: '/',
pushState: true
});
} | [
"function",
"(",
")",
"{",
"// Create and attach our main view",
"this",
".",
"mainView",
"=",
"new",
"MainView",
"(",
"{",
"model",
":",
"this",
".",
"me",
",",
"el",
":",
"document",
".",
"body",
"}",
")",
";",
"// this kicks off our backbutton tracking (browser history)",
"// and will cause the first matching handler in the router",
"// to fire.",
"this",
".",
"router",
".",
"history",
".",
"start",
"(",
"{",
"root",
":",
"'/'",
",",
"pushState",
":",
"true",
"}",
")",
";",
"}"
] | This is where it all starts | [
"This",
"is",
"where",
"it",
"all",
"starts"
] | 8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417 | https://github.com/NLeSC/spot/blob/8e02b6e0b80a21a7fe5c62b48bf121c0f2b8e417/src/app.js#L82-L96 | train |
|
kenodressel/mysql-to-rest | controllers/api.js | function (i) {
if (i >= columns.length) {
insertIntoDB();
return;
}
var dbField = columns[i];
var field = dbField.Field;
//Check required fields
if (dbField.Null === 'NO' &&
dbField.Default === '' &&
dbField.Extra !== 'auto_increment' &&
dbField.Extra.search('on update')===-1) {
//Check if field not set
if (undefOrEmpty(req.body[field])) {
return sendError(res,"Field " + field + " is NOT NULL but not specified in this request");
} else {
//Check if the set values are roughly okay
value = checkIfSentvaluesAreSufficient(req,dbField);
console.log(value);
if(value !== false) {
//Value seems okay, go to the next field
insertJson[field] = value;
iterator(i + 1);
} else {
return sendError(res,'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field] );
}
}
} else {
//Check for not required fields
//Skip auto_incremented fields
if(dbField.Extra === 'auto_increment') {
iterator(i + 1);
} else {
//Check if the field was provided by the client
var defined = false;
if(dbField.Default == "FILE") {
if(req.files.hasOwnProperty(dbField.Field)) {
defined = true;
}
} else {
if(typeof req.body[field] !== "undefined") {
defined = true;
}
}
//If it was provided, check if the values are okay
if(defined) {
value = checkIfSentvaluesAreSufficient(req,dbField);
if(value !== false) {
insertJson[field] = value;
iterator(i + 1);
} else {
if(dbField.Default == "FILE") {
return sendError(res, 'Value for field ' + field + ' is not sufficient. Either the file is to large or an other error occured');
} else {
return sendError(res, 'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field]);
}
}
} else {
//If not, don't mind
iterator(i + 1);
}
}
}
} | javascript | function (i) {
if (i >= columns.length) {
insertIntoDB();
return;
}
var dbField = columns[i];
var field = dbField.Field;
//Check required fields
if (dbField.Null === 'NO' &&
dbField.Default === '' &&
dbField.Extra !== 'auto_increment' &&
dbField.Extra.search('on update')===-1) {
//Check if field not set
if (undefOrEmpty(req.body[field])) {
return sendError(res,"Field " + field + " is NOT NULL but not specified in this request");
} else {
//Check if the set values are roughly okay
value = checkIfSentvaluesAreSufficient(req,dbField);
console.log(value);
if(value !== false) {
//Value seems okay, go to the next field
insertJson[field] = value;
iterator(i + 1);
} else {
return sendError(res,'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field] );
}
}
} else {
//Check for not required fields
//Skip auto_incremented fields
if(dbField.Extra === 'auto_increment') {
iterator(i + 1);
} else {
//Check if the field was provided by the client
var defined = false;
if(dbField.Default == "FILE") {
if(req.files.hasOwnProperty(dbField.Field)) {
defined = true;
}
} else {
if(typeof req.body[field] !== "undefined") {
defined = true;
}
}
//If it was provided, check if the values are okay
if(defined) {
value = checkIfSentvaluesAreSufficient(req,dbField);
if(value !== false) {
insertJson[field] = value;
iterator(i + 1);
} else {
if(dbField.Default == "FILE") {
return sendError(res, 'Value for field ' + field + ' is not sufficient. Either the file is to large or an other error occured');
} else {
return sendError(res, 'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field]);
}
}
} else {
//If not, don't mind
iterator(i + 1);
}
}
}
} | [
"function",
"(",
"i",
")",
"{",
"if",
"(",
"i",
">=",
"columns",
".",
"length",
")",
"{",
"insertIntoDB",
"(",
")",
";",
"return",
";",
"}",
"var",
"dbField",
"=",
"columns",
"[",
"i",
"]",
";",
"var",
"field",
"=",
"dbField",
".",
"Field",
";",
"//Check required fields",
"if",
"(",
"dbField",
".",
"Null",
"===",
"'NO'",
"&&",
"dbField",
".",
"Default",
"===",
"''",
"&&",
"dbField",
".",
"Extra",
"!==",
"'auto_increment'",
"&&",
"dbField",
".",
"Extra",
".",
"search",
"(",
"'on update'",
")",
"===",
"-",
"1",
")",
"{",
"//Check if field not set",
"if",
"(",
"undefOrEmpty",
"(",
"req",
".",
"body",
"[",
"field",
"]",
")",
")",
"{",
"return",
"sendError",
"(",
"res",
",",
"\"Field \"",
"+",
"field",
"+",
"\" is NOT NULL but not specified in this request\"",
")",
";",
"}",
"else",
"{",
"//Check if the set values are roughly okay",
"value",
"=",
"checkIfSentvaluesAreSufficient",
"(",
"req",
",",
"dbField",
")",
";",
"console",
".",
"log",
"(",
"value",
")",
";",
"if",
"(",
"value",
"!==",
"false",
")",
"{",
"//Value seems okay, go to the next field",
"insertJson",
"[",
"field",
"]",
"=",
"value",
";",
"iterator",
"(",
"i",
"+",
"1",
")",
";",
"}",
"else",
"{",
"return",
"sendError",
"(",
"res",
",",
"'Value for field '",
"+",
"field",
"+",
"' is not sufficient. Expecting '",
"+",
"dbField",
".",
"Type",
"+",
"' but got '",
"+",
"typeof",
"req",
".",
"body",
"[",
"field",
"]",
")",
";",
"}",
"}",
"}",
"else",
"{",
"//Check for not required fields",
"//Skip auto_incremented fields",
"if",
"(",
"dbField",
".",
"Extra",
"===",
"'auto_increment'",
")",
"{",
"iterator",
"(",
"i",
"+",
"1",
")",
";",
"}",
"else",
"{",
"//Check if the field was provided by the client",
"var",
"defined",
"=",
"false",
";",
"if",
"(",
"dbField",
".",
"Default",
"==",
"\"FILE\"",
")",
"{",
"if",
"(",
"req",
".",
"files",
".",
"hasOwnProperty",
"(",
"dbField",
".",
"Field",
")",
")",
"{",
"defined",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"typeof",
"req",
".",
"body",
"[",
"field",
"]",
"!==",
"\"undefined\"",
")",
"{",
"defined",
"=",
"true",
";",
"}",
"}",
"//If it was provided, check if the values are okay",
"if",
"(",
"defined",
")",
"{",
"value",
"=",
"checkIfSentvaluesAreSufficient",
"(",
"req",
",",
"dbField",
")",
";",
"if",
"(",
"value",
"!==",
"false",
")",
"{",
"insertJson",
"[",
"field",
"]",
"=",
"value",
";",
"iterator",
"(",
"i",
"+",
"1",
")",
";",
"}",
"else",
"{",
"if",
"(",
"dbField",
".",
"Default",
"==",
"\"FILE\"",
")",
"{",
"return",
"sendError",
"(",
"res",
",",
"'Value for field '",
"+",
"field",
"+",
"' is not sufficient. Either the file is to large or an other error occured'",
")",
";",
"}",
"else",
"{",
"return",
"sendError",
"(",
"res",
",",
"'Value for field '",
"+",
"field",
"+",
"' is not sufficient. Expecting '",
"+",
"dbField",
".",
"Type",
"+",
"' but got '",
"+",
"typeof",
"req",
".",
"body",
"[",
"field",
"]",
")",
";",
"}",
"}",
"}",
"else",
"{",
"//If not, don't mind",
"iterator",
"(",
"i",
"+",
"1",
")",
";",
"}",
"}",
"}",
"}"
] | Forced sync iterator | [
"Forced",
"sync",
"iterator"
] | 2d41a8a0e6fad3bebd57b063109f4fc428822f30 | https://github.com/kenodressel/mysql-to-rest/blob/2d41a8a0e6fad3bebd57b063109f4fc428822f30/controllers/api.js#L222-L291 | train |
|
kenodressel/mysql-to-rest | controllers/api.js | insertIntoDB | function insertIntoDB() {
lastQry = connection.query('INSERT INTO ?? SET ?', [req.params.table , insertJson] , function (err, rows) {
if (err) {
console.error(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
} else {
sendSuccessAnswer(req.params.table , res, rows.insertId);
}
});
} | javascript | function insertIntoDB() {
lastQry = connection.query('INSERT INTO ?? SET ?', [req.params.table , insertJson] , function (err, rows) {
if (err) {
console.error(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
} else {
sendSuccessAnswer(req.params.table , res, rows.insertId);
}
});
} | [
"function",
"insertIntoDB",
"(",
")",
"{",
"lastQry",
"=",
"connection",
".",
"query",
"(",
"'INSERT INTO ?? SET ?'",
",",
"[",
"req",
".",
"params",
".",
"table",
",",
"insertJson",
"]",
",",
"function",
"(",
"err",
",",
"rows",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"res",
".",
"statusCode",
"=",
"500",
";",
"res",
".",
"send",
"(",
"{",
"result",
":",
"'error'",
",",
"err",
":",
"err",
".",
"code",
"}",
")",
";",
"}",
"else",
"{",
"sendSuccessAnswer",
"(",
"req",
".",
"params",
".",
"table",
",",
"res",
",",
"rows",
".",
"insertId",
")",
";",
"}",
"}",
")",
";",
"}"
] | start the async "for" loop
When the loop is finished write everything in the database | [
"start",
"the",
"async",
"for",
"loop",
"When",
"the",
"loop",
"is",
"finished",
"write",
"everything",
"in",
"the",
"database"
] | 2d41a8a0e6fad3bebd57b063109f4fc428822f30 | https://github.com/kenodressel/mysql-to-rest/blob/2d41a8a0e6fad3bebd57b063109f4fc428822f30/controllers/api.js#L298-L312 | train |
kenodressel/mysql-to-rest | controllers/api.js | updateIntoDB | function updateIntoDB() {
//Yaaay, alle Tests bestanden gogo, insert!
lastQry = connection.query('UPDATE ?? SET ? WHERE ?? = ?', [req.params.table , updateJson, updateSelector.field, updateSelector.value] , function (err) {
if (err) return sendError(res,err.code);
sendSuccessAnswer(req.params.table , res, req.params.id, updateSelector.field);
});
} | javascript | function updateIntoDB() {
//Yaaay, alle Tests bestanden gogo, insert!
lastQry = connection.query('UPDATE ?? SET ? WHERE ?? = ?', [req.params.table , updateJson, updateSelector.field, updateSelector.value] , function (err) {
if (err) return sendError(res,err.code);
sendSuccessAnswer(req.params.table , res, req.params.id, updateSelector.field);
});
} | [
"function",
"updateIntoDB",
"(",
")",
"{",
"//Yaaay, alle Tests bestanden gogo, insert!",
"lastQry",
"=",
"connection",
".",
"query",
"(",
"'UPDATE ?? SET ? WHERE ?? = ?'",
",",
"[",
"req",
".",
"params",
".",
"table",
",",
"updateJson",
",",
"updateSelector",
".",
"field",
",",
"updateSelector",
".",
"value",
"]",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"sendError",
"(",
"res",
",",
"err",
".",
"code",
")",
";",
"sendSuccessAnswer",
"(",
"req",
".",
"params",
".",
"table",
",",
"res",
",",
"req",
".",
"params",
".",
"id",
",",
"updateSelector",
".",
"field",
")",
";",
"}",
")",
";",
"}"
] | start the async "for" loop | [
"start",
"the",
"async",
"for",
"loop"
] | 2d41a8a0e6fad3bebd57b063109f4fc428822f30 | https://github.com/kenodressel/mysql-to-rest/blob/2d41a8a0e6fad3bebd57b063109f4fc428822f30/controllers/api.js#L407-L414 | train |
kenodressel/mysql-to-rest | controllers/api.js | sendSuccessAnswer | function sendSuccessAnswer(table, res, id, field) {
if(typeof field === "undefined") {
if(id === 0) {
//Just assume that everything went okay. It looks like a non numeric primary key.
res.send({
result: 'success',
table: table
});
return;
} else {
field = "id";
}
}
lastQry = connection.query('SELECT * FROM ?? WHERE ?? = ?', [table, field, id] , function (err, rows) {
if (err) {
sendError(res, err.code)
} else {
res.send({
result: 'success',
json: rows,
table: table
});
}
});
} | javascript | function sendSuccessAnswer(table, res, id, field) {
if(typeof field === "undefined") {
if(id === 0) {
//Just assume that everything went okay. It looks like a non numeric primary key.
res.send({
result: 'success',
table: table
});
return;
} else {
field = "id";
}
}
lastQry = connection.query('SELECT * FROM ?? WHERE ?? = ?', [table, field, id] , function (err, rows) {
if (err) {
sendError(res, err.code)
} else {
res.send({
result: 'success',
json: rows,
table: table
});
}
});
} | [
"function",
"sendSuccessAnswer",
"(",
"table",
",",
"res",
",",
"id",
",",
"field",
")",
"{",
"if",
"(",
"typeof",
"field",
"===",
"\"undefined\"",
")",
"{",
"if",
"(",
"id",
"===",
"0",
")",
"{",
"//Just assume that everything went okay. It looks like a non numeric primary key.",
"res",
".",
"send",
"(",
"{",
"result",
":",
"'success'",
",",
"table",
":",
"table",
"}",
")",
";",
"return",
";",
"}",
"else",
"{",
"field",
"=",
"\"id\"",
";",
"}",
"}",
"lastQry",
"=",
"connection",
".",
"query",
"(",
"'SELECT * FROM ?? WHERE ?? = ?'",
",",
"[",
"table",
",",
"field",
",",
"id",
"]",
",",
"function",
"(",
"err",
",",
"rows",
")",
"{",
"if",
"(",
"err",
")",
"{",
"sendError",
"(",
"res",
",",
"err",
".",
"code",
")",
"}",
"else",
"{",
"res",
".",
"send",
"(",
"{",
"result",
":",
"'success'",
",",
"json",
":",
"rows",
",",
"table",
":",
"table",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Send the edited element to the requester
@param table
@param res
@param id
@param field | [
"Send",
"the",
"edited",
"element",
"to",
"the",
"requester"
] | 2d41a8a0e6fad3bebd57b063109f4fc428822f30 | https://github.com/kenodressel/mysql-to-rest/blob/2d41a8a0e6fad3bebd57b063109f4fc428822f30/controllers/api.js#L457-L481 | train |
kenodressel/mysql-to-rest | controllers/api.js | checkIfSentvaluesAreSufficient | function checkIfSentvaluesAreSufficient(req,dbField) {
if(dbField.Default == 'FILE') {
//For 'File' fields just return the link ot the file
if(req.files.hasOwnProperty(dbField.Field)) {
var file = req.files[dbField.Field].hasOwnProperty('name') ? req.files[dbField.Field] : req.files[dbField.Field][0];
if(settings.maxFileSize !== -1 && file.size > settings.maxFileSize) {
return false;
}
return file.name;
} else {
return false;
}
} else {
if (req.body[dbField.Field] === null || typeof req.body[dbField.Field] == "undefined") {
return dbField.Null == "YES" ? null : false;
}
//Normle Werte
if((dbField.Type.indexOf("int") != -1 || dbField.Type.indexOf("float") != -1 || dbField.Type.indexOf("double") != -1 )) {
return !isNaN(req.body[dbField.Field]) ? req.body[dbField.Field] : false;
} else if(typeof req.body[dbField.Field] === 'string') {
return escape(req.body[dbField.Field]);
}
return false;
}
} | javascript | function checkIfSentvaluesAreSufficient(req,dbField) {
if(dbField.Default == 'FILE') {
//For 'File' fields just return the link ot the file
if(req.files.hasOwnProperty(dbField.Field)) {
var file = req.files[dbField.Field].hasOwnProperty('name') ? req.files[dbField.Field] : req.files[dbField.Field][0];
if(settings.maxFileSize !== -1 && file.size > settings.maxFileSize) {
return false;
}
return file.name;
} else {
return false;
}
} else {
if (req.body[dbField.Field] === null || typeof req.body[dbField.Field] == "undefined") {
return dbField.Null == "YES" ? null : false;
}
//Normle Werte
if((dbField.Type.indexOf("int") != -1 || dbField.Type.indexOf("float") != -1 || dbField.Type.indexOf("double") != -1 )) {
return !isNaN(req.body[dbField.Field]) ? req.body[dbField.Field] : false;
} else if(typeof req.body[dbField.Field] === 'string') {
return escape(req.body[dbField.Field]);
}
return false;
}
} | [
"function",
"checkIfSentvaluesAreSufficient",
"(",
"req",
",",
"dbField",
")",
"{",
"if",
"(",
"dbField",
".",
"Default",
"==",
"'FILE'",
")",
"{",
"//For 'File' fields just return the link ot the file",
"if",
"(",
"req",
".",
"files",
".",
"hasOwnProperty",
"(",
"dbField",
".",
"Field",
")",
")",
"{",
"var",
"file",
"=",
"req",
".",
"files",
"[",
"dbField",
".",
"Field",
"]",
".",
"hasOwnProperty",
"(",
"'name'",
")",
"?",
"req",
".",
"files",
"[",
"dbField",
".",
"Field",
"]",
":",
"req",
".",
"files",
"[",
"dbField",
".",
"Field",
"]",
"[",
"0",
"]",
";",
"if",
"(",
"settings",
".",
"maxFileSize",
"!==",
"-",
"1",
"&&",
"file",
".",
"size",
">",
"settings",
".",
"maxFileSize",
")",
"{",
"return",
"false",
";",
"}",
"return",
"file",
".",
"name",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"req",
".",
"body",
"[",
"dbField",
".",
"Field",
"]",
"===",
"null",
"||",
"typeof",
"req",
".",
"body",
"[",
"dbField",
".",
"Field",
"]",
"==",
"\"undefined\"",
")",
"{",
"return",
"dbField",
".",
"Null",
"==",
"\"YES\"",
"?",
"null",
":",
"false",
";",
"}",
"//Normle Werte",
"if",
"(",
"(",
"dbField",
".",
"Type",
".",
"indexOf",
"(",
"\"int\"",
")",
"!=",
"-",
"1",
"||",
"dbField",
".",
"Type",
".",
"indexOf",
"(",
"\"float\"",
")",
"!=",
"-",
"1",
"||",
"dbField",
".",
"Type",
".",
"indexOf",
"(",
"\"double\"",
")",
"!=",
"-",
"1",
")",
")",
"{",
"return",
"!",
"isNaN",
"(",
"req",
".",
"body",
"[",
"dbField",
".",
"Field",
"]",
")",
"?",
"req",
".",
"body",
"[",
"dbField",
".",
"Field",
"]",
":",
"false",
";",
"}",
"else",
"if",
"(",
"typeof",
"req",
".",
"body",
"[",
"dbField",
".",
"Field",
"]",
"===",
"'string'",
")",
"{",
"return",
"escape",
"(",
"req",
".",
"body",
"[",
"dbField",
".",
"Field",
"]",
")",
";",
"}",
"return",
"false",
";",
"}",
"}"
] | Check roughly if the provided value is sufficient for the database field
@param req
@param dbField
@returns {*} | [
"Check",
"roughly",
"if",
"the",
"provided",
"value",
"is",
"sufficient",
"for",
"the",
"database",
"field"
] | 2d41a8a0e6fad3bebd57b063109f4fc428822f30 | https://github.com/kenodressel/mysql-to-rest/blob/2d41a8a0e6fad3bebd57b063109f4fc428822f30/controllers/api.js#L500-L528 | train |
kenodressel/mysql-to-rest | controllers/api.js | sendError | function sendError(res,err) {
console.error(err);
// also log last executed query, for easier debugging
console.error(lastQry.sql);
res.statusCode = 500;
res.send({
result: 'error',
err: err
});
} | javascript | function sendError(res,err) {
console.error(err);
// also log last executed query, for easier debugging
console.error(lastQry.sql);
res.statusCode = 500;
res.send({
result: 'error',
err: err
});
} | [
"function",
"sendError",
"(",
"res",
",",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"// also log last executed query, for easier debugging",
"console",
".",
"error",
"(",
"lastQry",
".",
"sql",
")",
";",
"res",
".",
"statusCode",
"=",
"500",
";",
"res",
".",
"send",
"(",
"{",
"result",
":",
"'error'",
",",
"err",
":",
"err",
"}",
")",
";",
"}"
] | Send error messsage to the user
@param res
@param err | [
"Send",
"error",
"messsage",
"to",
"the",
"user"
] | 2d41a8a0e6fad3bebd57b063109f4fc428822f30 | https://github.com/kenodressel/mysql-to-rest/blob/2d41a8a0e6fad3bebd57b063109f4fc428822f30/controllers/api.js#L597-L606 | train |
kenodressel/mysql-to-rest | controllers/api.js | findPrim | function findPrim(columns,field) {
var primary_keys = columns.filter(function (r) {return r.Key === 'PRI';});
//for multiple primary keys, just take the first
if(primary_keys.length > 0) {
return primary_keys[0].Field;
}
//If the provided field is a string, we might have a chance
if(typeof field === "string") {
if(checkIfFieldsExist(field,columns)) {
return escape(field);
}
}
//FALLBACK
return "id";
} | javascript | function findPrim(columns,field) {
var primary_keys = columns.filter(function (r) {return r.Key === 'PRI';});
//for multiple primary keys, just take the first
if(primary_keys.length > 0) {
return primary_keys[0].Field;
}
//If the provided field is a string, we might have a chance
if(typeof field === "string") {
if(checkIfFieldsExist(field,columns)) {
return escape(field);
}
}
//FALLBACK
return "id";
} | [
"function",
"findPrim",
"(",
"columns",
",",
"field",
")",
"{",
"var",
"primary_keys",
"=",
"columns",
".",
"filter",
"(",
"function",
"(",
"r",
")",
"{",
"return",
"r",
".",
"Key",
"===",
"'PRI'",
";",
"}",
")",
";",
"//for multiple primary keys, just take the first",
"if",
"(",
"primary_keys",
".",
"length",
">",
"0",
")",
"{",
"return",
"primary_keys",
"[",
"0",
"]",
".",
"Field",
";",
"}",
"//If the provided field is a string, we might have a chance",
"if",
"(",
"typeof",
"field",
"===",
"\"string\"",
")",
"{",
"if",
"(",
"checkIfFieldsExist",
"(",
"field",
",",
"columns",
")",
")",
"{",
"return",
"escape",
"(",
"field",
")",
";",
"}",
"}",
"//FALLBACK",
"return",
"\"id\"",
";",
"}"
] | Get primary key, or if specified
@param columns
@param field
@returns {*} | [
"Get",
"primary",
"key",
"or",
"if",
"specified"
] | 2d41a8a0e6fad3bebd57b063109f4fc428822f30 | https://github.com/kenodressel/mysql-to-rest/blob/2d41a8a0e6fad3bebd57b063109f4fc428822f30/controllers/api.js#L615-L633 | train |
mandnyc/ssml-builder | index.js | checkRateRange | function checkRateRange(num) {
var numString = num.substring(0, num.length - 1);
var parseNum = parseInt(numString);
if (parseNum < 20) {
throw new Error("The minimum rate is twenty percentage. Received: " + parseNum);
}
} | javascript | function checkRateRange(num) {
var numString = num.substring(0, num.length - 1);
var parseNum = parseInt(numString);
if (parseNum < 20) {
throw new Error("The minimum rate is twenty percentage. Received: " + parseNum);
}
} | [
"function",
"checkRateRange",
"(",
"num",
")",
"{",
"var",
"numString",
"=",
"num",
".",
"substring",
"(",
"0",
",",
"num",
".",
"length",
"-",
"1",
")",
";",
"var",
"parseNum",
"=",
"parseInt",
"(",
"numString",
")",
";",
"if",
"(",
"parseNum",
"<",
"20",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"The minimum rate is twenty percentage. Received: \"",
"+",
"parseNum",
")",
";",
"}",
"}"
] | This method ensures that the value of the rate must be equal or great than 20%
@param num is the value of rate | [
"This",
"method",
"ensures",
"that",
"the",
"value",
"of",
"the",
"rate",
"must",
"be",
"equal",
"or",
"great",
"than",
"20%"
] | 6b8cbeb6ce2570d624363fa7dca365d6fbb7e510 | https://github.com/mandnyc/ssml-builder/blob/6b8cbeb6ce2570d624363fa7dca365d6fbb7e510/index.js#L414-L420 | train |
mandnyc/ssml-builder | index.js | isInList | function isInList(value, listOfValues, msg) {
value = value.toLowerCase().trim();
if (listOfValues.indexOf(value) === -1) {
throw new Error(msg);
}
} | javascript | function isInList(value, listOfValues, msg) {
value = value.toLowerCase().trim();
if (listOfValues.indexOf(value) === -1) {
throw new Error(msg);
}
} | [
"function",
"isInList",
"(",
"value",
",",
"listOfValues",
",",
"msg",
")",
"{",
"value",
"=",
"value",
".",
"toLowerCase",
"(",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"listOfValues",
".",
"indexOf",
"(",
"value",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"msg",
")",
";",
"}",
"}"
] | This method validates if the value exists in the list of values
@param value
@param listOfValues
@param msg is the error message that will be thrown when the value is not in the list | [
"This",
"method",
"validates",
"if",
"the",
"value",
"exists",
"in",
"the",
"list",
"of",
"values"
] | 6b8cbeb6ce2570d624363fa7dca365d6fbb7e510 | https://github.com/mandnyc/ssml-builder/blob/6b8cbeb6ce2570d624363fa7dca365d6fbb7e510/index.js#L467-L472 | train |
pebble/clay | src/scripts/vendor/minified.js | equals | function equals(x, y) {
var a = isFunction(x) ? x() : x;
var b = isFunction(y) ? y() : y;
var aKeys;
if (a == b)
return true;
else if (a == _null || b == _null)
return false;
else if (isValue(a) || isValue(b))
return isDate(a) && isDate(b) && +a==+b;
else if (isList(a)) {
return (a.length == b.length) &&
!find(a, function(val, index) {
if (!equals(val, b[index]))
return true;
});
}
else {
return !isList(b) &&
((aKeys = keys(a)).length == keyCount(b)) &&
!find(aKeys, function(key) {
if (!equals(a[key],b[key]))
return true;
});
}
} | javascript | function equals(x, y) {
var a = isFunction(x) ? x() : x;
var b = isFunction(y) ? y() : y;
var aKeys;
if (a == b)
return true;
else if (a == _null || b == _null)
return false;
else if (isValue(a) || isValue(b))
return isDate(a) && isDate(b) && +a==+b;
else if (isList(a)) {
return (a.length == b.length) &&
!find(a, function(val, index) {
if (!equals(val, b[index]))
return true;
});
}
else {
return !isList(b) &&
((aKeys = keys(a)).length == keyCount(b)) &&
!find(aKeys, function(key) {
if (!equals(a[key],b[key]))
return true;
});
}
} | [
"function",
"equals",
"(",
"x",
",",
"y",
")",
"{",
"var",
"a",
"=",
"isFunction",
"(",
"x",
")",
"?",
"x",
"(",
")",
":",
"x",
";",
"var",
"b",
"=",
"isFunction",
"(",
"y",
")",
"?",
"y",
"(",
")",
":",
"y",
";",
"var",
"aKeys",
";",
"if",
"(",
"a",
"==",
"b",
")",
"return",
"true",
";",
"else",
"if",
"(",
"a",
"==",
"_null",
"||",
"b",
"==",
"_null",
")",
"return",
"false",
";",
"else",
"if",
"(",
"isValue",
"(",
"a",
")",
"||",
"isValue",
"(",
"b",
")",
")",
"return",
"isDate",
"(",
"a",
")",
"&&",
"isDate",
"(",
"b",
")",
"&&",
"+",
"a",
"==",
"+",
"b",
";",
"else",
"if",
"(",
"isList",
"(",
"a",
")",
")",
"{",
"return",
"(",
"a",
".",
"length",
"==",
"b",
".",
"length",
")",
"&&",
"!",
"find",
"(",
"a",
",",
"function",
"(",
"val",
",",
"index",
")",
"{",
"if",
"(",
"!",
"equals",
"(",
"val",
",",
"b",
"[",
"index",
"]",
")",
")",
"return",
"true",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"!",
"isList",
"(",
"b",
")",
"&&",
"(",
"(",
"aKeys",
"=",
"keys",
"(",
"a",
")",
")",
".",
"length",
"==",
"keyCount",
"(",
"b",
")",
")",
"&&",
"!",
"find",
"(",
"aKeys",
",",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"!",
"equals",
"(",
"a",
"[",
"key",
"]",
",",
"b",
"[",
"key",
"]",
")",
")",
"return",
"true",
";",
"}",
")",
";",
"}",
"}"
] | equals if a and b have the same elements and all are equal. Supports getters. | [
"equals",
"if",
"a",
"and",
"b",
"have",
"the",
"same",
"elements",
"and",
"all",
"are",
"equal",
".",
"Supports",
"getters",
"."
] | 1bf6db08092ab464974d1762a953ea7cbd24efb8 | https://github.com/pebble/clay/blob/1bf6db08092ab464974d1762a953ea7cbd24efb8/src/scripts/vendor/minified.js#L449-L474 | train |
pebble/clay | src/scripts/vendor/minified.js | parseDate | function parseDate(fmt, date) {
var indexMap = {}; // contains reGroupPosition -> typeLetter or [typeLetter, value array]
var reIndex = 1;
var timezoneOffsetMatch;
var timezoneIndex;
var match;
var format = replace(fmt, /^\?/);
if (format!=fmt && !trim(date))
return _null;
if (match = /^\[([+-])(\d\d)(\d\d)\]\s*(.*)/.exec(format)) {
timezoneOffsetMatch = match;
format = match[4];
}
var parser = new RegExp(format.replace(/(.)(\1*)(?:\[([^\]]*)\])?/g, function(wholeMatch, placeholderChar, placeholderDigits, param) {
if (/[dmhkyhs]/i.test(placeholderChar)) {
indexMap[reIndex++] = placeholderChar;
var plen = placeholderDigits.length+1;
return "(\\d"+(plen<2?"+":("{1,"+plen+"}"))+")";
}
else if (placeholderChar == 'z') {
timezoneIndex = reIndex;
reIndex += 3;
return "([+-])(\\d\\d)(\\d\\d)";
}
else if (/[Nna]/.test(placeholderChar)) {
indexMap[reIndex++] = [placeholderChar, param && param.split(',')];
return "([a-zA-Z\\u0080-\\u1fff]+)";
}
else if (/w/i.test(placeholderChar))
return "[a-zA-Z\\u0080-\\u1fff]+";
else if (/\s/.test(placeholderChar))
return "\\s+";
else
return escapeRegExp(wholeMatch);
}));
if (!(match = parser.exec(date)))
return undef;
var ctorArgs = [0, 0, 0, 0, 0, 0, 0];
for (var i = 1; i < reIndex; i++) {
var matchVal = match[i];
var indexEntry = indexMap[i];
if (isList(indexEntry)) { // for a, n or N
var placeholderChar = indexEntry[0];
var mapEntry = PARSE_DATE_MAP[placeholderChar];
var ctorIndex = mapEntry[0];
var valList = indexEntry[1] || mapEntry[1];
var listValue = find(valList, function(v, index) { if (startsWith(matchVal.toLowerCase(), v.toLowerCase())) return index; });
if (listValue == _null)
return undef;
if (placeholderChar == 'a')
ctorArgs[ctorIndex] += listValue * 12;
else
ctorArgs[ctorIndex] = listValue;
}
else if (indexEntry) { // for numeric values (yHmMs)
var value = parseFloat(matchVal);
var mapEntry = PARSE_DATE_MAP[indexEntry];
if (isList(mapEntry))
ctorArgs[mapEntry[0]] += value - mapEntry[1];
else
ctorArgs[mapEntry] += value;
}
}
var d = new Date(ctorArgs[0], ctorArgs[1], ctorArgs[2], ctorArgs[3], ctorArgs[4], ctorArgs[5], ctorArgs[6]);
return dateAdd(d, 'minutes', -getTimezone(timezoneOffsetMatch, 1, d) - getTimezone(match, timezoneIndex, d));
} | javascript | function parseDate(fmt, date) {
var indexMap = {}; // contains reGroupPosition -> typeLetter or [typeLetter, value array]
var reIndex = 1;
var timezoneOffsetMatch;
var timezoneIndex;
var match;
var format = replace(fmt, /^\?/);
if (format!=fmt && !trim(date))
return _null;
if (match = /^\[([+-])(\d\d)(\d\d)\]\s*(.*)/.exec(format)) {
timezoneOffsetMatch = match;
format = match[4];
}
var parser = new RegExp(format.replace(/(.)(\1*)(?:\[([^\]]*)\])?/g, function(wholeMatch, placeholderChar, placeholderDigits, param) {
if (/[dmhkyhs]/i.test(placeholderChar)) {
indexMap[reIndex++] = placeholderChar;
var plen = placeholderDigits.length+1;
return "(\\d"+(plen<2?"+":("{1,"+plen+"}"))+")";
}
else if (placeholderChar == 'z') {
timezoneIndex = reIndex;
reIndex += 3;
return "([+-])(\\d\\d)(\\d\\d)";
}
else if (/[Nna]/.test(placeholderChar)) {
indexMap[reIndex++] = [placeholderChar, param && param.split(',')];
return "([a-zA-Z\\u0080-\\u1fff]+)";
}
else if (/w/i.test(placeholderChar))
return "[a-zA-Z\\u0080-\\u1fff]+";
else if (/\s/.test(placeholderChar))
return "\\s+";
else
return escapeRegExp(wholeMatch);
}));
if (!(match = parser.exec(date)))
return undef;
var ctorArgs = [0, 0, 0, 0, 0, 0, 0];
for (var i = 1; i < reIndex; i++) {
var matchVal = match[i];
var indexEntry = indexMap[i];
if (isList(indexEntry)) { // for a, n or N
var placeholderChar = indexEntry[0];
var mapEntry = PARSE_DATE_MAP[placeholderChar];
var ctorIndex = mapEntry[0];
var valList = indexEntry[1] || mapEntry[1];
var listValue = find(valList, function(v, index) { if (startsWith(matchVal.toLowerCase(), v.toLowerCase())) return index; });
if (listValue == _null)
return undef;
if (placeholderChar == 'a')
ctorArgs[ctorIndex] += listValue * 12;
else
ctorArgs[ctorIndex] = listValue;
}
else if (indexEntry) { // for numeric values (yHmMs)
var value = parseFloat(matchVal);
var mapEntry = PARSE_DATE_MAP[indexEntry];
if (isList(mapEntry))
ctorArgs[mapEntry[0]] += value - mapEntry[1];
else
ctorArgs[mapEntry] += value;
}
}
var d = new Date(ctorArgs[0], ctorArgs[1], ctorArgs[2], ctorArgs[3], ctorArgs[4], ctorArgs[5], ctorArgs[6]);
return dateAdd(d, 'minutes', -getTimezone(timezoneOffsetMatch, 1, d) - getTimezone(match, timezoneIndex, d));
} | [
"function",
"parseDate",
"(",
"fmt",
",",
"date",
")",
"{",
"var",
"indexMap",
"=",
"{",
"}",
";",
"// contains reGroupPosition -> typeLetter or [typeLetter, value array]",
"var",
"reIndex",
"=",
"1",
";",
"var",
"timezoneOffsetMatch",
";",
"var",
"timezoneIndex",
";",
"var",
"match",
";",
"var",
"format",
"=",
"replace",
"(",
"fmt",
",",
"/",
"^\\?",
"/",
")",
";",
"if",
"(",
"format",
"!=",
"fmt",
"&&",
"!",
"trim",
"(",
"date",
")",
")",
"return",
"_null",
";",
"if",
"(",
"match",
"=",
"/",
"^\\[([+-])(\\d\\d)(\\d\\d)\\]\\s*(.*)",
"/",
".",
"exec",
"(",
"format",
")",
")",
"{",
"timezoneOffsetMatch",
"=",
"match",
";",
"format",
"=",
"match",
"[",
"4",
"]",
";",
"}",
"var",
"parser",
"=",
"new",
"RegExp",
"(",
"format",
".",
"replace",
"(",
"/",
"(.)(\\1*)(?:\\[([^\\]]*)\\])?",
"/",
"g",
",",
"function",
"(",
"wholeMatch",
",",
"placeholderChar",
",",
"placeholderDigits",
",",
"param",
")",
"{",
"if",
"(",
"/",
"[dmhkyhs]",
"/",
"i",
".",
"test",
"(",
"placeholderChar",
")",
")",
"{",
"indexMap",
"[",
"reIndex",
"++",
"]",
"=",
"placeholderChar",
";",
"var",
"plen",
"=",
"placeholderDigits",
".",
"length",
"+",
"1",
";",
"return",
"\"(\\\\d\"",
"+",
"(",
"plen",
"<",
"2",
"?",
"\"+\"",
":",
"(",
"\"{1,\"",
"+",
"plen",
"+",
"\"}\"",
")",
")",
"+",
"\")\"",
";",
"}",
"else",
"if",
"(",
"placeholderChar",
"==",
"'z'",
")",
"{",
"timezoneIndex",
"=",
"reIndex",
";",
"reIndex",
"+=",
"3",
";",
"return",
"\"([+-])(\\\\d\\\\d)(\\\\d\\\\d)\"",
";",
"}",
"else",
"if",
"(",
"/",
"[Nna]",
"/",
".",
"test",
"(",
"placeholderChar",
")",
")",
"{",
"indexMap",
"[",
"reIndex",
"++",
"]",
"=",
"[",
"placeholderChar",
",",
"param",
"&&",
"param",
".",
"split",
"(",
"','",
")",
"]",
";",
"return",
"\"([a-zA-Z\\\\u0080-\\\\u1fff]+)\"",
";",
"}",
"else",
"if",
"(",
"/",
"w",
"/",
"i",
".",
"test",
"(",
"placeholderChar",
")",
")",
"return",
"\"[a-zA-Z\\\\u0080-\\\\u1fff]+\"",
";",
"else",
"if",
"(",
"/",
"\\s",
"/",
".",
"test",
"(",
"placeholderChar",
")",
")",
"return",
"\"\\\\s+\"",
";",
"else",
"return",
"escapeRegExp",
"(",
"wholeMatch",
")",
";",
"}",
")",
")",
";",
"if",
"(",
"!",
"(",
"match",
"=",
"parser",
".",
"exec",
"(",
"date",
")",
")",
")",
"return",
"undef",
";",
"var",
"ctorArgs",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"reIndex",
";",
"i",
"++",
")",
"{",
"var",
"matchVal",
"=",
"match",
"[",
"i",
"]",
";",
"var",
"indexEntry",
"=",
"indexMap",
"[",
"i",
"]",
";",
"if",
"(",
"isList",
"(",
"indexEntry",
")",
")",
"{",
"// for a, n or N",
"var",
"placeholderChar",
"=",
"indexEntry",
"[",
"0",
"]",
";",
"var",
"mapEntry",
"=",
"PARSE_DATE_MAP",
"[",
"placeholderChar",
"]",
";",
"var",
"ctorIndex",
"=",
"mapEntry",
"[",
"0",
"]",
";",
"var",
"valList",
"=",
"indexEntry",
"[",
"1",
"]",
"||",
"mapEntry",
"[",
"1",
"]",
";",
"var",
"listValue",
"=",
"find",
"(",
"valList",
",",
"function",
"(",
"v",
",",
"index",
")",
"{",
"if",
"(",
"startsWith",
"(",
"matchVal",
".",
"toLowerCase",
"(",
")",
",",
"v",
".",
"toLowerCase",
"(",
")",
")",
")",
"return",
"index",
";",
"}",
")",
";",
"if",
"(",
"listValue",
"==",
"_null",
")",
"return",
"undef",
";",
"if",
"(",
"placeholderChar",
"==",
"'a'",
")",
"ctorArgs",
"[",
"ctorIndex",
"]",
"+=",
"listValue",
"*",
"12",
";",
"else",
"ctorArgs",
"[",
"ctorIndex",
"]",
"=",
"listValue",
";",
"}",
"else",
"if",
"(",
"indexEntry",
")",
"{",
"// for numeric values (yHmMs)",
"var",
"value",
"=",
"parseFloat",
"(",
"matchVal",
")",
";",
"var",
"mapEntry",
"=",
"PARSE_DATE_MAP",
"[",
"indexEntry",
"]",
";",
"if",
"(",
"isList",
"(",
"mapEntry",
")",
")",
"ctorArgs",
"[",
"mapEntry",
"[",
"0",
"]",
"]",
"+=",
"value",
"-",
"mapEntry",
"[",
"1",
"]",
";",
"else",
"ctorArgs",
"[",
"mapEntry",
"]",
"+=",
"value",
";",
"}",
"}",
"var",
"d",
"=",
"new",
"Date",
"(",
"ctorArgs",
"[",
"0",
"]",
",",
"ctorArgs",
"[",
"1",
"]",
",",
"ctorArgs",
"[",
"2",
"]",
",",
"ctorArgs",
"[",
"3",
"]",
",",
"ctorArgs",
"[",
"4",
"]",
",",
"ctorArgs",
"[",
"5",
"]",
",",
"ctorArgs",
"[",
"6",
"]",
")",
";",
"return",
"dateAdd",
"(",
"d",
",",
"'minutes'",
",",
"-",
"getTimezone",
"(",
"timezoneOffsetMatch",
",",
"1",
",",
"d",
")",
"-",
"getTimezone",
"(",
"match",
",",
"timezoneIndex",
",",
"d",
")",
")",
";",
"}"
] | returns date; null if optional and not set; undefined if parsing failed | [
"returns",
"date",
";",
"null",
"if",
"optional",
"and",
"not",
"set",
";",
"undefined",
"if",
"parsing",
"failed"
] | 1bf6db08092ab464974d1762a953ea7cbd24efb8 | https://github.com/pebble/clay/blob/1bf6db08092ab464974d1762a953ea7cbd24efb8/src/scripts/vendor/minified.js#L599-L669 | train |
pebble/clay | src/scripts/vendor/minified.js | collectUniqNodes | function collectUniqNodes(list, func) {
var result = [];
var nodeIds = {};
var currentNodeId;
flexiEach(list, function(value) {
flexiEach(func(value), function(node) {
if (!nodeIds[currentNodeId = getNodeId(node)]) {
result.push(node);
nodeIds[currentNodeId] = true;
}
});
});
return result;
} | javascript | function collectUniqNodes(list, func) {
var result = [];
var nodeIds = {};
var currentNodeId;
flexiEach(list, function(value) {
flexiEach(func(value), function(node) {
if (!nodeIds[currentNodeId = getNodeId(node)]) {
result.push(node);
nodeIds[currentNodeId] = true;
}
});
});
return result;
} | [
"function",
"collectUniqNodes",
"(",
"list",
",",
"func",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"nodeIds",
"=",
"{",
"}",
";",
"var",
"currentNodeId",
";",
"flexiEach",
"(",
"list",
",",
"function",
"(",
"value",
")",
"{",
"flexiEach",
"(",
"func",
"(",
"value",
")",
",",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"nodeIds",
"[",
"currentNodeId",
"=",
"getNodeId",
"(",
"node",
")",
"]",
")",
"{",
"result",
".",
"push",
"(",
"node",
")",
";",
"nodeIds",
"[",
"currentNodeId",
"]",
"=",
"true",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | collect variant that filters out duplicate nodes from the given list, returns a new array | [
"collect",
"variant",
"that",
"filters",
"out",
"duplicate",
"nodes",
"from",
"the",
"given",
"list",
"returns",
"a",
"new",
"array"
] | 1bf6db08092ab464974d1762a953ea7cbd24efb8 | https://github.com/pebble/clay/blob/1bf6db08092ab464974d1762a953ea7cbd24efb8/src/scripts/vendor/minified.js#L845-L859 | train |
pebble/clay | src/scripts/vendor/minified.js | triggerHandler | function triggerHandler(eventName, event, target) {
var match = !bubbleSelector;
var el = bubbleSelector ? target : registeredOn;
if (bubbleSelector) {
var selectorFilter = getFilterFunc(bubbleSelector, registeredOn);
while (el && el != registeredOn && !(match = selectorFilter(el)))
el = el['parentNode'];
}
return (!match) || (name != eventName) || ((handler.apply($(el), args || [event, index]) && prefix=='?') || prefix == '|');
} | javascript | function triggerHandler(eventName, event, target) {
var match = !bubbleSelector;
var el = bubbleSelector ? target : registeredOn;
if (bubbleSelector) {
var selectorFilter = getFilterFunc(bubbleSelector, registeredOn);
while (el && el != registeredOn && !(match = selectorFilter(el)))
el = el['parentNode'];
}
return (!match) || (name != eventName) || ((handler.apply($(el), args || [event, index]) && prefix=='?') || prefix == '|');
} | [
"function",
"triggerHandler",
"(",
"eventName",
",",
"event",
",",
"target",
")",
"{",
"var",
"match",
"=",
"!",
"bubbleSelector",
";",
"var",
"el",
"=",
"bubbleSelector",
"?",
"target",
":",
"registeredOn",
";",
"if",
"(",
"bubbleSelector",
")",
"{",
"var",
"selectorFilter",
"=",
"getFilterFunc",
"(",
"bubbleSelector",
",",
"registeredOn",
")",
";",
"while",
"(",
"el",
"&&",
"el",
"!=",
"registeredOn",
"&&",
"!",
"(",
"match",
"=",
"selectorFilter",
"(",
"el",
")",
")",
")",
"el",
"=",
"el",
"[",
"'parentNode'",
"]",
";",
"}",
"return",
"(",
"!",
"match",
")",
"||",
"(",
"name",
"!=",
"eventName",
")",
"||",
"(",
"(",
"handler",
".",
"apply",
"(",
"$",
"(",
"el",
")",
",",
"args",
"||",
"[",
"event",
",",
"index",
"]",
")",
"&&",
"prefix",
"==",
"'?'",
")",
"||",
"prefix",
"==",
"'|'",
")",
";",
"}"
] | returns true if processing should be continued | [
"returns",
"true",
"if",
"processing",
"should",
"be",
"continued"
] | 1bf6db08092ab464974d1762a953ea7cbd24efb8 | https://github.com/pebble/clay/blob/1bf6db08092ab464974d1762a953ea7cbd24efb8/src/scripts/vendor/minified.js#L889-L898 | train |
Backendless/JS-Code-Runner | lib/server-code/model/service-descriptor.js | enrichMethodNode | function enrichMethodNode(methodNode, method) {
method.description && (methodNode.description = method.description)
if (method.tags.route) {
let httpPath = method.tags.route
let httpMethod = 'GET'
const sepPos = httpPath.indexOf(' ')
if (sepPos !== -1) {
httpMethod = httpPath.substr(0, sepPos).toUpperCase()
httpPath = httpPath.substr(sepPos + 1)
if (!isValidHttpMethod(httpMethod)) {
throw new Error(`Unsupported HTTP method [${httpMethod}] for ${method.name} method`)
}
}
methodNode.method = httpMethod
methodNode.path = httpPath
}
return methodNode
} | javascript | function enrichMethodNode(methodNode, method) {
method.description && (methodNode.description = method.description)
if (method.tags.route) {
let httpPath = method.tags.route
let httpMethod = 'GET'
const sepPos = httpPath.indexOf(' ')
if (sepPos !== -1) {
httpMethod = httpPath.substr(0, sepPos).toUpperCase()
httpPath = httpPath.substr(sepPos + 1)
if (!isValidHttpMethod(httpMethod)) {
throw new Error(`Unsupported HTTP method [${httpMethod}] for ${method.name} method`)
}
}
methodNode.method = httpMethod
methodNode.path = httpPath
}
return methodNode
} | [
"function",
"enrichMethodNode",
"(",
"methodNode",
",",
"method",
")",
"{",
"method",
".",
"description",
"&&",
"(",
"methodNode",
".",
"description",
"=",
"method",
".",
"description",
")",
"if",
"(",
"method",
".",
"tags",
".",
"route",
")",
"{",
"let",
"httpPath",
"=",
"method",
".",
"tags",
".",
"route",
"let",
"httpMethod",
"=",
"'GET'",
"const",
"sepPos",
"=",
"httpPath",
".",
"indexOf",
"(",
"' '",
")",
"if",
"(",
"sepPos",
"!==",
"-",
"1",
")",
"{",
"httpMethod",
"=",
"httpPath",
".",
"substr",
"(",
"0",
",",
"sepPos",
")",
".",
"toUpperCase",
"(",
")",
"httpPath",
"=",
"httpPath",
".",
"substr",
"(",
"sepPos",
"+",
"1",
")",
"if",
"(",
"!",
"isValidHttpMethod",
"(",
"httpMethod",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"httpMethod",
"}",
"${",
"method",
".",
"name",
"}",
"`",
")",
"}",
"}",
"methodNode",
".",
"method",
"=",
"httpMethod",
"methodNode",
".",
"path",
"=",
"httpPath",
"}",
"return",
"methodNode",
"}"
] | Enriches service method node by adding 'method', 'route' and 'description' attributes.
@param {Object} methodNode
@param {Object} method
@returns {Object} methodNode | [
"Enriches",
"service",
"method",
"node",
"by",
"adding",
"method",
"route",
"and",
"description",
"attributes",
"."
] | 14a181664a6263cbe0a9dace079d40ab83a3458b | https://github.com/Backendless/JS-Code-Runner/blob/14a181664a6263cbe0a9dace079d40ab83a3458b/lib/server-code/model/service-descriptor.js#L69-L91 | train |
refractproject/minim | lib/elements.js | refract | function refract(value) {
if (value instanceof Element) {
return value;
}
if (typeof value === 'string') {
return new StringElement(value);
}
if (typeof value === 'number') {
return new NumberElement(value);
}
if (typeof value === 'boolean') {
return new BooleanElement(value);
}
if (value === null) {
return new NullElement();
}
if (Array.isArray(value)) {
return new ArrayElement(value.map(refract));
}
if (typeof value === 'object') {
const element = new ObjectElement(value);
return element;
}
return value;
} | javascript | function refract(value) {
if (value instanceof Element) {
return value;
}
if (typeof value === 'string') {
return new StringElement(value);
}
if (typeof value === 'number') {
return new NumberElement(value);
}
if (typeof value === 'boolean') {
return new BooleanElement(value);
}
if (value === null) {
return new NullElement();
}
if (Array.isArray(value)) {
return new ArrayElement(value.map(refract));
}
if (typeof value === 'object') {
const element = new ObjectElement(value);
return element;
}
return value;
} | [
"function",
"refract",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"instanceof",
"Element",
")",
"{",
"return",
"value",
";",
"}",
"if",
"(",
"typeof",
"value",
"===",
"'string'",
")",
"{",
"return",
"new",
"StringElement",
"(",
"value",
")",
";",
"}",
"if",
"(",
"typeof",
"value",
"===",
"'number'",
")",
"{",
"return",
"new",
"NumberElement",
"(",
"value",
")",
";",
"}",
"if",
"(",
"typeof",
"value",
"===",
"'boolean'",
")",
"{",
"return",
"new",
"BooleanElement",
"(",
"value",
")",
";",
"}",
"if",
"(",
"value",
"===",
"null",
")",
"{",
"return",
"new",
"NullElement",
"(",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"return",
"new",
"ArrayElement",
"(",
"value",
".",
"map",
"(",
"refract",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"value",
"===",
"'object'",
")",
"{",
"const",
"element",
"=",
"new",
"ObjectElement",
"(",
"value",
")",
";",
"return",
"element",
";",
"}",
"return",
"value",
";",
"}"
] | Refracts a JSON type to minim elements
@param value
@returns {Element} | [
"Refracts",
"a",
"JSON",
"type",
"to",
"minim",
"elements"
] | 7945b8b5e27c5f35e2e5301930c8269edbc284c2 | https://github.com/refractproject/minim/blob/7945b8b5e27c5f35e2e5301930c8269edbc284c2/lib/elements.js#L22-L53 | train |
zurb/supercollider | lib/init.js | statusLog | function statusLog(file, data, time) {
var msg = '';
var diff = (process.hrtime(time)[1] / 1000000000).toFixed(2);
var adapters = Object.keys(data._adapterData).join(', ');
msg += format('Supercollider: processed %s in %s', chalk.cyan(file), chalk.magenta(diff + ' s'));
if (adapters.length) {
msg += format(' with %s', chalk.yellow(adapters));
}
log(msg);
} | javascript | function statusLog(file, data, time) {
var msg = '';
var diff = (process.hrtime(time)[1] / 1000000000).toFixed(2);
var adapters = Object.keys(data._adapterData).join(', ');
msg += format('Supercollider: processed %s in %s', chalk.cyan(file), chalk.magenta(diff + ' s'));
if (adapters.length) {
msg += format(' with %s', chalk.yellow(adapters));
}
log(msg);
} | [
"function",
"statusLog",
"(",
"file",
",",
"data",
",",
"time",
")",
"{",
"var",
"msg",
"=",
"''",
";",
"var",
"diff",
"=",
"(",
"process",
".",
"hrtime",
"(",
"time",
")",
"[",
"1",
"]",
"/",
"1000000000",
")",
".",
"toFixed",
"(",
"2",
")",
";",
"var",
"adapters",
"=",
"Object",
".",
"keys",
"(",
"data",
".",
"_adapterData",
")",
".",
"join",
"(",
"', '",
")",
";",
"msg",
"+=",
"format",
"(",
"'Supercollider: processed %s in %s'",
",",
"chalk",
".",
"cyan",
"(",
"file",
")",
",",
"chalk",
".",
"magenta",
"(",
"diff",
"+",
"' s'",
")",
")",
";",
"if",
"(",
"adapters",
".",
"length",
")",
"{",
"msg",
"+=",
"format",
"(",
"' with %s'",
",",
"chalk",
".",
"yellow",
"(",
"adapters",
")",
")",
";",
"}",
"log",
"(",
"msg",
")",
";",
"}"
] | Logs the completion of a page being processed to the console.
@param {string} file - Name of the file.
@param {object} data - Data object associated with the file. The list of adapters is pulled from this.
@param {integer} time - Time it took to process the file. | [
"Logs",
"the",
"completion",
"of",
"a",
"page",
"being",
"processed",
"to",
"the",
"console",
"."
] | 83cdb9a0e652b448895394d6c83c33b88f44fad2 | https://github.com/zurb/supercollider/blob/83cdb9a0e652b448895394d6c83c33b88f44fad2/lib/init.js#L68-L80 | train |
tmcw/stickshift | stickshift.js | CodeMirror | function CodeMirror(place, options) {
if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
this.options = options = options ? copyObj(options) : {};
// Determine effective options based on given values and defaults.
copyObj(defaults, options, false);
setGuttersForLineNumbers(options);
var doc = options.value;
if (typeof doc == "string") doc = new Doc(doc, options.mode);
this.doc = doc;
var display = this.display = new Display(place, doc);
display.wrapper.CodeMirror = this;
updateGutters(this);
themeChanged(this);
if (options.lineWrapping)
this.display.wrapper.className += " CodeMirror-wrap";
if (options.autofocus && !mobile) focusInput(this);
initScrollbars(this);
this.state = {
keyMaps: [], // stores maps added by addKeyMap
overlays: [], // highlighting overlays, as added by addOverlay
modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
overwrite: false, focused: false,
suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput
draggingText: false,
highlight: new Delayed(), // stores highlight worker timeout
keySeq: null // Unfinished key sequence
};
// Override magic textarea content restore that IE sometimes does
// on our hidden textarea on reload
if (ie && ie_version < 11) setTimeout(bind(resetInput, this, true), 20);
registerEventHandlers(this);
ensureGlobalHandlers();
startOperation(this);
this.curOp.forceUpdate = true;
attachDoc(this, doc);
if ((options.autofocus && !mobile) || activeElt() == display.input)
setTimeout(bind(onFocus, this), 20);
else
onBlur(this);
for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
optionHandlers[opt](this, options[opt], Init);
maybeUpdateLineNumberWidth(this);
if (options.finishInit) options.finishInit(this);
for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
endOperation(this);
// Suppress optimizelegibility in Webkit, since it breaks text
// measuring on line wrapping boundaries.
if (webkit && options.lineWrapping &&
getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
display.lineDiv.style.textRendering = "auto";
} | javascript | function CodeMirror(place, options) {
if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
this.options = options = options ? copyObj(options) : {};
// Determine effective options based on given values and defaults.
copyObj(defaults, options, false);
setGuttersForLineNumbers(options);
var doc = options.value;
if (typeof doc == "string") doc = new Doc(doc, options.mode);
this.doc = doc;
var display = this.display = new Display(place, doc);
display.wrapper.CodeMirror = this;
updateGutters(this);
themeChanged(this);
if (options.lineWrapping)
this.display.wrapper.className += " CodeMirror-wrap";
if (options.autofocus && !mobile) focusInput(this);
initScrollbars(this);
this.state = {
keyMaps: [], // stores maps added by addKeyMap
overlays: [], // highlighting overlays, as added by addOverlay
modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
overwrite: false, focused: false,
suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput
draggingText: false,
highlight: new Delayed(), // stores highlight worker timeout
keySeq: null // Unfinished key sequence
};
// Override magic textarea content restore that IE sometimes does
// on our hidden textarea on reload
if (ie && ie_version < 11) setTimeout(bind(resetInput, this, true), 20);
registerEventHandlers(this);
ensureGlobalHandlers();
startOperation(this);
this.curOp.forceUpdate = true;
attachDoc(this, doc);
if ((options.autofocus && !mobile) || activeElt() == display.input)
setTimeout(bind(onFocus, this), 20);
else
onBlur(this);
for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
optionHandlers[opt](this, options[opt], Init);
maybeUpdateLineNumberWidth(this);
if (options.finishInit) options.finishInit(this);
for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
endOperation(this);
// Suppress optimizelegibility in Webkit, since it breaks text
// measuring on line wrapping boundaries.
if (webkit && options.lineWrapping &&
getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
display.lineDiv.style.textRendering = "auto";
} | [
"function",
"CodeMirror",
"(",
"place",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"CodeMirror",
")",
")",
"return",
"new",
"CodeMirror",
"(",
"place",
",",
"options",
")",
";",
"this",
".",
"options",
"=",
"options",
"=",
"options",
"?",
"copyObj",
"(",
"options",
")",
":",
"{",
"}",
";",
"// Determine effective options based on given values and defaults.",
"copyObj",
"(",
"defaults",
",",
"options",
",",
"false",
")",
";",
"setGuttersForLineNumbers",
"(",
"options",
")",
";",
"var",
"doc",
"=",
"options",
".",
"value",
";",
"if",
"(",
"typeof",
"doc",
"==",
"\"string\"",
")",
"doc",
"=",
"new",
"Doc",
"(",
"doc",
",",
"options",
".",
"mode",
")",
";",
"this",
".",
"doc",
"=",
"doc",
";",
"var",
"display",
"=",
"this",
".",
"display",
"=",
"new",
"Display",
"(",
"place",
",",
"doc",
")",
";",
"display",
".",
"wrapper",
".",
"CodeMirror",
"=",
"this",
";",
"updateGutters",
"(",
"this",
")",
";",
"themeChanged",
"(",
"this",
")",
";",
"if",
"(",
"options",
".",
"lineWrapping",
")",
"this",
".",
"display",
".",
"wrapper",
".",
"className",
"+=",
"\" CodeMirror-wrap\"",
";",
"if",
"(",
"options",
".",
"autofocus",
"&&",
"!",
"mobile",
")",
"focusInput",
"(",
"this",
")",
";",
"initScrollbars",
"(",
"this",
")",
";",
"this",
".",
"state",
"=",
"{",
"keyMaps",
":",
"[",
"]",
",",
"// stores maps added by addKeyMap",
"overlays",
":",
"[",
"]",
",",
"// highlighting overlays, as added by addOverlay",
"modeGen",
":",
"0",
",",
"// bumped when mode/overlay changes, used to invalidate highlighting info",
"overwrite",
":",
"false",
",",
"focused",
":",
"false",
",",
"suppressEdits",
":",
"false",
",",
"// used to disable editing during key handlers when in readOnly mode",
"pasteIncoming",
":",
"false",
",",
"cutIncoming",
":",
"false",
",",
"// help recognize paste/cut edits in readInput",
"draggingText",
":",
"false",
",",
"highlight",
":",
"new",
"Delayed",
"(",
")",
",",
"// stores highlight worker timeout",
"keySeq",
":",
"null",
"// Unfinished key sequence",
"}",
";",
"// Override magic textarea content restore that IE sometimes does",
"// on our hidden textarea on reload",
"if",
"(",
"ie",
"&&",
"ie_version",
"<",
"11",
")",
"setTimeout",
"(",
"bind",
"(",
"resetInput",
",",
"this",
",",
"true",
")",
",",
"20",
")",
";",
"registerEventHandlers",
"(",
"this",
")",
";",
"ensureGlobalHandlers",
"(",
")",
";",
"startOperation",
"(",
"this",
")",
";",
"this",
".",
"curOp",
".",
"forceUpdate",
"=",
"true",
";",
"attachDoc",
"(",
"this",
",",
"doc",
")",
";",
"if",
"(",
"(",
"options",
".",
"autofocus",
"&&",
"!",
"mobile",
")",
"||",
"activeElt",
"(",
")",
"==",
"display",
".",
"input",
")",
"setTimeout",
"(",
"bind",
"(",
"onFocus",
",",
"this",
")",
",",
"20",
")",
";",
"else",
"onBlur",
"(",
"this",
")",
";",
"for",
"(",
"var",
"opt",
"in",
"optionHandlers",
")",
"if",
"(",
"optionHandlers",
".",
"hasOwnProperty",
"(",
"opt",
")",
")",
"optionHandlers",
"[",
"opt",
"]",
"(",
"this",
",",
"options",
"[",
"opt",
"]",
",",
"Init",
")",
";",
"maybeUpdateLineNumberWidth",
"(",
"this",
")",
";",
"if",
"(",
"options",
".",
"finishInit",
")",
"options",
".",
"finishInit",
"(",
"this",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"initHooks",
".",
"length",
";",
"++",
"i",
")",
"initHooks",
"[",
"i",
"]",
"(",
"this",
")",
";",
"endOperation",
"(",
"this",
")",
";",
"// Suppress optimizelegibility in Webkit, since it breaks text",
"// measuring on line wrapping boundaries.",
"if",
"(",
"webkit",
"&&",
"options",
".",
"lineWrapping",
"&&",
"getComputedStyle",
"(",
"display",
".",
"lineDiv",
")",
".",
"textRendering",
"==",
"\"optimizelegibility\"",
")",
"display",
".",
"lineDiv",
".",
"style",
".",
"textRendering",
"=",
"\"auto\"",
";",
"}"
] | A CodeMirror instance represents an editor. This is the object that user code is usually dealing with. | [
"A",
"CodeMirror",
"instance",
"represents",
"an",
"editor",
".",
"This",
"is",
"the",
"object",
"that",
"user",
"code",
"is",
"usually",
"dealing",
"with",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L1983-L2043 | train |
tmcw/stickshift | stickshift.js | updateWidgetHeight | function updateWidgetHeight(line) {
if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
line.widgets[i].height = line.widgets[i].node.offsetHeight;
} | javascript | function updateWidgetHeight(line) {
if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
line.widgets[i].height = line.widgets[i].node.offsetHeight;
} | [
"function",
"updateWidgetHeight",
"(",
"line",
")",
"{",
"if",
"(",
"line",
".",
"widgets",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"line",
".",
"widgets",
".",
"length",
";",
"++",
"i",
")",
"line",
".",
"widgets",
"[",
"i",
"]",
".",
"height",
"=",
"line",
".",
"widgets",
"[",
"i",
"]",
".",
"node",
".",
"offsetHeight",
";",
"}"
] | Read and store the height of line widgets associated with the given line. | [
"Read",
"and",
"store",
"the",
"height",
"of",
"line",
"widgets",
"associated",
"with",
"the",
"given",
"line",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L2753-L2756 | train |
tmcw/stickshift | stickshift.js | ensureLineWrapped | function ensureLineWrapped(lineView) {
if (lineView.node == lineView.text) {
lineView.node = elt("div", null, null, "position: relative");
if (lineView.text.parentNode)
lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
lineView.node.appendChild(lineView.text);
if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
}
return lineView.node;
} | javascript | function ensureLineWrapped(lineView) {
if (lineView.node == lineView.text) {
lineView.node = elt("div", null, null, "position: relative");
if (lineView.text.parentNode)
lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
lineView.node.appendChild(lineView.text);
if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
}
return lineView.node;
} | [
"function",
"ensureLineWrapped",
"(",
"lineView",
")",
"{",
"if",
"(",
"lineView",
".",
"node",
"==",
"lineView",
".",
"text",
")",
"{",
"lineView",
".",
"node",
"=",
"elt",
"(",
"\"div\"",
",",
"null",
",",
"null",
",",
"\"position: relative\"",
")",
";",
"if",
"(",
"lineView",
".",
"text",
".",
"parentNode",
")",
"lineView",
".",
"text",
".",
"parentNode",
".",
"replaceChild",
"(",
"lineView",
".",
"node",
",",
"lineView",
".",
"text",
")",
";",
"lineView",
".",
"node",
".",
"appendChild",
"(",
"lineView",
".",
"text",
")",
";",
"if",
"(",
"ie",
"&&",
"ie_version",
"<",
"8",
")",
"lineView",
".",
"node",
".",
"style",
".",
"zIndex",
"=",
"2",
";",
"}",
"return",
"lineView",
".",
"node",
";",
"}"
] | Lines with gutter elements, widgets or a background class need to be wrapped, and have the extra elements added to the wrapper div | [
"Lines",
"with",
"gutter",
"elements",
"widgets",
"or",
"a",
"background",
"class",
"need",
"to",
"be",
"wrapped",
"and",
"have",
"the",
"extra",
"elements",
"added",
"to",
"the",
"wrapper",
"div"
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L2836-L2845 | train |
tmcw/stickshift | stickshift.js | extendSelection | function extendSelection(doc, head, other, options) {
setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
} | javascript | function extendSelection(doc, head, other, options) {
setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
} | [
"function",
"extendSelection",
"(",
"doc",
",",
"head",
",",
"other",
",",
"options",
")",
"{",
"setSelection",
"(",
"doc",
",",
"new",
"Selection",
"(",
"[",
"extendRange",
"(",
"doc",
",",
"doc",
".",
"sel",
".",
"primary",
"(",
")",
",",
"head",
",",
"other",
")",
"]",
",",
"0",
")",
",",
"options",
")",
";",
"}"
] | Extend the primary selection range, discard the rest. | [
"Extend",
"the",
"primary",
"selection",
"range",
"discard",
"the",
"rest",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L3138-L3140 | train |
tmcw/stickshift | stickshift.js | skipAtomic | function skipAtomic(doc, pos, bias, mayClear) {
var flipped = false, curPos = pos;
var dir = bias || 1;
doc.cantEdit = false;
search: for (;;) {
var line = getLine(doc, curPos.line);
if (line.markedSpans) {
for (var i = 0; i < line.markedSpans.length; ++i) {
var sp = line.markedSpans[i], m = sp.marker;
if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
(sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
if (mayClear) {
signal(m, "beforeCursorEnter");
if (m.explicitlyCleared) {
if (!line.markedSpans) break;
else {--i; continue;}
}
}
if (!m.atomic) continue;
var newPos = m.find(dir < 0 ? -1 : 1);
if (cmp(newPos, curPos) == 0) {
newPos.ch += dir;
if (newPos.ch < 0) {
if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
else newPos = null;
} else if (newPos.ch > line.text.length) {
if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
else newPos = null;
}
if (!newPos) {
if (flipped) {
// Driven in a corner -- no valid cursor position found at all
// -- try again *with* clearing, if we didn't already
if (!mayClear) return skipAtomic(doc, pos, bias, true);
// Otherwise, turn off editing until further notice, and return the start of the doc
doc.cantEdit = true;
return Pos(doc.first, 0);
}
flipped = true; newPos = pos; dir = -dir;
}
}
curPos = newPos;
continue search;
}
}
}
return curPos;
}
} | javascript | function skipAtomic(doc, pos, bias, mayClear) {
var flipped = false, curPos = pos;
var dir = bias || 1;
doc.cantEdit = false;
search: for (;;) {
var line = getLine(doc, curPos.line);
if (line.markedSpans) {
for (var i = 0; i < line.markedSpans.length; ++i) {
var sp = line.markedSpans[i], m = sp.marker;
if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
(sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
if (mayClear) {
signal(m, "beforeCursorEnter");
if (m.explicitlyCleared) {
if (!line.markedSpans) break;
else {--i; continue;}
}
}
if (!m.atomic) continue;
var newPos = m.find(dir < 0 ? -1 : 1);
if (cmp(newPos, curPos) == 0) {
newPos.ch += dir;
if (newPos.ch < 0) {
if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
else newPos = null;
} else if (newPos.ch > line.text.length) {
if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
else newPos = null;
}
if (!newPos) {
if (flipped) {
// Driven in a corner -- no valid cursor position found at all
// -- try again *with* clearing, if we didn't already
if (!mayClear) return skipAtomic(doc, pos, bias, true);
// Otherwise, turn off editing until further notice, and return the start of the doc
doc.cantEdit = true;
return Pos(doc.first, 0);
}
flipped = true; newPos = pos; dir = -dir;
}
}
curPos = newPos;
continue search;
}
}
}
return curPos;
}
} | [
"function",
"skipAtomic",
"(",
"doc",
",",
"pos",
",",
"bias",
",",
"mayClear",
")",
"{",
"var",
"flipped",
"=",
"false",
",",
"curPos",
"=",
"pos",
";",
"var",
"dir",
"=",
"bias",
"||",
"1",
";",
"doc",
".",
"cantEdit",
"=",
"false",
";",
"search",
":",
"for",
"(",
";",
";",
")",
"{",
"var",
"line",
"=",
"getLine",
"(",
"doc",
",",
"curPos",
".",
"line",
")",
";",
"if",
"(",
"line",
".",
"markedSpans",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"line",
".",
"markedSpans",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"sp",
"=",
"line",
".",
"markedSpans",
"[",
"i",
"]",
",",
"m",
"=",
"sp",
".",
"marker",
";",
"if",
"(",
"(",
"sp",
".",
"from",
"==",
"null",
"||",
"(",
"m",
".",
"inclusiveLeft",
"?",
"sp",
".",
"from",
"<=",
"curPos",
".",
"ch",
":",
"sp",
".",
"from",
"<",
"curPos",
".",
"ch",
")",
")",
"&&",
"(",
"sp",
".",
"to",
"==",
"null",
"||",
"(",
"m",
".",
"inclusiveRight",
"?",
"sp",
".",
"to",
">=",
"curPos",
".",
"ch",
":",
"sp",
".",
"to",
">",
"curPos",
".",
"ch",
")",
")",
")",
"{",
"if",
"(",
"mayClear",
")",
"{",
"signal",
"(",
"m",
",",
"\"beforeCursorEnter\"",
")",
";",
"if",
"(",
"m",
".",
"explicitlyCleared",
")",
"{",
"if",
"(",
"!",
"line",
".",
"markedSpans",
")",
"break",
";",
"else",
"{",
"--",
"i",
";",
"continue",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"m",
".",
"atomic",
")",
"continue",
";",
"var",
"newPos",
"=",
"m",
".",
"find",
"(",
"dir",
"<",
"0",
"?",
"-",
"1",
":",
"1",
")",
";",
"if",
"(",
"cmp",
"(",
"newPos",
",",
"curPos",
")",
"==",
"0",
")",
"{",
"newPos",
".",
"ch",
"+=",
"dir",
";",
"if",
"(",
"newPos",
".",
"ch",
"<",
"0",
")",
"{",
"if",
"(",
"newPos",
".",
"line",
">",
"doc",
".",
"first",
")",
"newPos",
"=",
"clipPos",
"(",
"doc",
",",
"Pos",
"(",
"newPos",
".",
"line",
"-",
"1",
")",
")",
";",
"else",
"newPos",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"newPos",
".",
"ch",
">",
"line",
".",
"text",
".",
"length",
")",
"{",
"if",
"(",
"newPos",
".",
"line",
"<",
"doc",
".",
"first",
"+",
"doc",
".",
"size",
"-",
"1",
")",
"newPos",
"=",
"Pos",
"(",
"newPos",
".",
"line",
"+",
"1",
",",
"0",
")",
";",
"else",
"newPos",
"=",
"null",
";",
"}",
"if",
"(",
"!",
"newPos",
")",
"{",
"if",
"(",
"flipped",
")",
"{",
"// Driven in a corner -- no valid cursor position found at all",
"// -- try again *with* clearing, if we didn't already",
"if",
"(",
"!",
"mayClear",
")",
"return",
"skipAtomic",
"(",
"doc",
",",
"pos",
",",
"bias",
",",
"true",
")",
";",
"// Otherwise, turn off editing until further notice, and return the start of the doc",
"doc",
".",
"cantEdit",
"=",
"true",
";",
"return",
"Pos",
"(",
"doc",
".",
"first",
",",
"0",
")",
";",
"}",
"flipped",
"=",
"true",
";",
"newPos",
"=",
"pos",
";",
"dir",
"=",
"-",
"dir",
";",
"}",
"}",
"curPos",
"=",
"newPos",
";",
"continue",
"search",
";",
"}",
"}",
"}",
"return",
"curPos",
";",
"}",
"}"
] | Ensure a given position is not inside an atomic range. | [
"Ensure",
"a",
"given",
"position",
"is",
"not",
"inside",
"an",
"atomic",
"range",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L3244-L3292 | train |
tmcw/stickshift | stickshift.js | drawSelectionCursor | function drawSelectionCursor(cm, range, output) {
var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);
var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
cursor.style.left = pos.left + "px";
cursor.style.top = pos.top + "px";
cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
if (pos.other) {
// Secondary cursor, shown when on a 'jump' in bi-directional text
var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
otherCursor.style.display = "";
otherCursor.style.left = pos.other.left + "px";
otherCursor.style.top = pos.other.top + "px";
otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
}
} | javascript | function drawSelectionCursor(cm, range, output) {
var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);
var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
cursor.style.left = pos.left + "px";
cursor.style.top = pos.top + "px";
cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
if (pos.other) {
// Secondary cursor, shown when on a 'jump' in bi-directional text
var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
otherCursor.style.display = "";
otherCursor.style.left = pos.other.left + "px";
otherCursor.style.top = pos.other.top + "px";
otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
}
} | [
"function",
"drawSelectionCursor",
"(",
"cm",
",",
"range",
",",
"output",
")",
"{",
"var",
"pos",
"=",
"cursorCoords",
"(",
"cm",
",",
"range",
".",
"head",
",",
"\"div\"",
",",
"null",
",",
"null",
",",
"!",
"cm",
".",
"options",
".",
"singleCursorHeightPerLine",
")",
";",
"var",
"cursor",
"=",
"output",
".",
"appendChild",
"(",
"elt",
"(",
"\"div\"",
",",
"\"\\u00a0\"",
",",
"\"CodeMirror-cursor\"",
")",
")",
";",
"cursor",
".",
"style",
".",
"left",
"=",
"pos",
".",
"left",
"+",
"\"px\"",
";",
"cursor",
".",
"style",
".",
"top",
"=",
"pos",
".",
"top",
"+",
"\"px\"",
";",
"cursor",
".",
"style",
".",
"height",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"pos",
".",
"bottom",
"-",
"pos",
".",
"top",
")",
"*",
"cm",
".",
"options",
".",
"cursorHeight",
"+",
"\"px\"",
";",
"if",
"(",
"pos",
".",
"other",
")",
"{",
"// Secondary cursor, shown when on a 'jump' in bi-directional text",
"var",
"otherCursor",
"=",
"output",
".",
"appendChild",
"(",
"elt",
"(",
"\"div\"",
",",
"\"\\u00a0\"",
",",
"\"CodeMirror-cursor CodeMirror-secondarycursor\"",
")",
")",
";",
"otherCursor",
".",
"style",
".",
"display",
"=",
"\"\"",
";",
"otherCursor",
".",
"style",
".",
"left",
"=",
"pos",
".",
"other",
".",
"left",
"+",
"\"px\"",
";",
"otherCursor",
".",
"style",
".",
"top",
"=",
"pos",
".",
"other",
".",
"top",
"+",
"\"px\"",
";",
"otherCursor",
".",
"style",
".",
"height",
"=",
"(",
"pos",
".",
"other",
".",
"bottom",
"-",
"pos",
".",
"other",
".",
"top",
")",
"*",
".85",
"+",
"\"px\"",
";",
"}",
"}"
] | Draws a cursor for the given range | [
"Draws",
"a",
"cursor",
"for",
"the",
"given",
"range"
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L3338-L3354 | train |
tmcw/stickshift | stickshift.js | findViewForLine | function findViewForLine(cm, lineN) {
if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
return cm.display.view[findViewIndex(cm, lineN)];
var ext = cm.display.externalMeasured;
if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
return ext;
} | javascript | function findViewForLine(cm, lineN) {
if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
return cm.display.view[findViewIndex(cm, lineN)];
var ext = cm.display.externalMeasured;
if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
return ext;
} | [
"function",
"findViewForLine",
"(",
"cm",
",",
"lineN",
")",
"{",
"if",
"(",
"lineN",
">=",
"cm",
".",
"display",
".",
"viewFrom",
"&&",
"lineN",
"<",
"cm",
".",
"display",
".",
"viewTo",
")",
"return",
"cm",
".",
"display",
".",
"view",
"[",
"findViewIndex",
"(",
"cm",
",",
"lineN",
")",
"]",
";",
"var",
"ext",
"=",
"cm",
".",
"display",
".",
"externalMeasured",
";",
"if",
"(",
"ext",
"&&",
"lineN",
">=",
"ext",
".",
"lineN",
"&&",
"lineN",
"<",
"ext",
".",
"lineN",
"+",
"ext",
".",
"size",
")",
"return",
"ext",
";",
"}"
] | Find a line view that corresponds to the given line number. | [
"Find",
"a",
"line",
"view",
"that",
"corresponds",
"to",
"the",
"given",
"line",
"number",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L3604-L3610 | train |
tmcw/stickshift | stickshift.js | prepareMeasureForLine | function prepareMeasureForLine(cm, line) {
var lineN = lineNo(line);
var view = findViewForLine(cm, lineN);
if (view && !view.text)
view = null;
else if (view && view.changes)
updateLineForChanges(cm, view, lineN, getDimensions(cm));
if (!view)
view = updateExternalMeasurement(cm, line);
var info = mapFromLineView(view, line, lineN);
return {
line: line, view: view, rect: null,
map: info.map, cache: info.cache, before: info.before,
hasHeights: false
};
} | javascript | function prepareMeasureForLine(cm, line) {
var lineN = lineNo(line);
var view = findViewForLine(cm, lineN);
if (view && !view.text)
view = null;
else if (view && view.changes)
updateLineForChanges(cm, view, lineN, getDimensions(cm));
if (!view)
view = updateExternalMeasurement(cm, line);
var info = mapFromLineView(view, line, lineN);
return {
line: line, view: view, rect: null,
map: info.map, cache: info.cache, before: info.before,
hasHeights: false
};
} | [
"function",
"prepareMeasureForLine",
"(",
"cm",
",",
"line",
")",
"{",
"var",
"lineN",
"=",
"lineNo",
"(",
"line",
")",
";",
"var",
"view",
"=",
"findViewForLine",
"(",
"cm",
",",
"lineN",
")",
";",
"if",
"(",
"view",
"&&",
"!",
"view",
".",
"text",
")",
"view",
"=",
"null",
";",
"else",
"if",
"(",
"view",
"&&",
"view",
".",
"changes",
")",
"updateLineForChanges",
"(",
"cm",
",",
"view",
",",
"lineN",
",",
"getDimensions",
"(",
"cm",
")",
")",
";",
"if",
"(",
"!",
"view",
")",
"view",
"=",
"updateExternalMeasurement",
"(",
"cm",
",",
"line",
")",
";",
"var",
"info",
"=",
"mapFromLineView",
"(",
"view",
",",
"line",
",",
"lineN",
")",
";",
"return",
"{",
"line",
":",
"line",
",",
"view",
":",
"view",
",",
"rect",
":",
"null",
",",
"map",
":",
"info",
".",
"map",
",",
"cache",
":",
"info",
".",
"cache",
",",
"before",
":",
"info",
".",
"before",
",",
"hasHeights",
":",
"false",
"}",
";",
"}"
] | Measurement can be split in two steps, the set-up work that applies to the whole line, and the measurement of the actual character. Functions like coordsChar, that need to do a lot of measurements in a row, can thus ensure that the set-up work is only done once. | [
"Measurement",
"can",
"be",
"split",
"in",
"two",
"steps",
"the",
"set",
"-",
"up",
"work",
"that",
"applies",
"to",
"the",
"whole",
"line",
"and",
"the",
"measurement",
"of",
"the",
"actual",
"character",
".",
"Functions",
"like",
"coordsChar",
"that",
"need",
"to",
"do",
"a",
"lot",
"of",
"measurements",
"in",
"a",
"row",
"can",
"thus",
"ensure",
"that",
"the",
"set",
"-",
"up",
"work",
"is",
"only",
"done",
"once",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L3617-L3633 | train |
tmcw/stickshift | stickshift.js | charWidth | function charWidth(display) {
if (display.cachedCharWidth != null) return display.cachedCharWidth;
var anchor = elt("span", "xxxxxxxxxx");
var pre = elt("pre", [anchor]);
removeChildrenAndAdd(display.measure, pre);
var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
if (width > 2) display.cachedCharWidth = width;
return width || 10;
} | javascript | function charWidth(display) {
if (display.cachedCharWidth != null) return display.cachedCharWidth;
var anchor = elt("span", "xxxxxxxxxx");
var pre = elt("pre", [anchor]);
removeChildrenAndAdd(display.measure, pre);
var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
if (width > 2) display.cachedCharWidth = width;
return width || 10;
} | [
"function",
"charWidth",
"(",
"display",
")",
"{",
"if",
"(",
"display",
".",
"cachedCharWidth",
"!=",
"null",
")",
"return",
"display",
".",
"cachedCharWidth",
";",
"var",
"anchor",
"=",
"elt",
"(",
"\"span\"",
",",
"\"xxxxxxxxxx\"",
")",
";",
"var",
"pre",
"=",
"elt",
"(",
"\"pre\"",
",",
"[",
"anchor",
"]",
")",
";",
"removeChildrenAndAdd",
"(",
"display",
".",
"measure",
",",
"pre",
")",
";",
"var",
"rect",
"=",
"anchor",
".",
"getBoundingClientRect",
"(",
")",
",",
"width",
"=",
"(",
"rect",
".",
"right",
"-",
"rect",
".",
"left",
")",
"/",
"10",
";",
"if",
"(",
"width",
">",
"2",
")",
"display",
".",
"cachedCharWidth",
"=",
"width",
";",
"return",
"width",
"||",
"10",
";",
"}"
] | Compute the default character width. | [
"Compute",
"the",
"default",
"character",
"width",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L3976-L3984 | train |
tmcw/stickshift | stickshift.js | endOperation | function endOperation(cm) {
var op = cm.curOp, group = op.ownsGroup;
if (!group) return;
try { fireCallbacksForOps(group); }
finally {
operationGroup = null;
for (var i = 0; i < group.ops.length; i++)
group.ops[i].cm.curOp = null;
endOperations(group);
}
} | javascript | function endOperation(cm) {
var op = cm.curOp, group = op.ownsGroup;
if (!group) return;
try { fireCallbacksForOps(group); }
finally {
operationGroup = null;
for (var i = 0; i < group.ops.length; i++)
group.ops[i].cm.curOp = null;
endOperations(group);
}
} | [
"function",
"endOperation",
"(",
"cm",
")",
"{",
"var",
"op",
"=",
"cm",
".",
"curOp",
",",
"group",
"=",
"op",
".",
"ownsGroup",
";",
"if",
"(",
"!",
"group",
")",
"return",
";",
"try",
"{",
"fireCallbacksForOps",
"(",
"group",
")",
";",
"}",
"finally",
"{",
"operationGroup",
"=",
"null",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"group",
".",
"ops",
".",
"length",
";",
"i",
"++",
")",
"group",
".",
"ops",
"[",
"i",
"]",
".",
"cm",
".",
"curOp",
"=",
"null",
";",
"endOperations",
"(",
"group",
")",
";",
"}",
"}"
] | Finish an operation, updating the display and signalling delayed events | [
"Finish",
"an",
"operation",
"updating",
"the",
"display",
"and",
"signalling",
"delayed",
"events"
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L4042-L4053 | train |
tmcw/stickshift | stickshift.js | setScrollTop | function setScrollTop(cm, val) {
if (Math.abs(cm.doc.scrollTop - val) < 2) return;
cm.doc.scrollTop = val;
if (!gecko) updateDisplaySimple(cm, {top: val});
if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
cm.display.scrollbars.setScrollTop(val);
if (gecko) updateDisplaySimple(cm);
startWorker(cm, 100);
} | javascript | function setScrollTop(cm, val) {
if (Math.abs(cm.doc.scrollTop - val) < 2) return;
cm.doc.scrollTop = val;
if (!gecko) updateDisplaySimple(cm, {top: val});
if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
cm.display.scrollbars.setScrollTop(val);
if (gecko) updateDisplaySimple(cm);
startWorker(cm, 100);
} | [
"function",
"setScrollTop",
"(",
"cm",
",",
"val",
")",
"{",
"if",
"(",
"Math",
".",
"abs",
"(",
"cm",
".",
"doc",
".",
"scrollTop",
"-",
"val",
")",
"<",
"2",
")",
"return",
";",
"cm",
".",
"doc",
".",
"scrollTop",
"=",
"val",
";",
"if",
"(",
"!",
"gecko",
")",
"updateDisplaySimple",
"(",
"cm",
",",
"{",
"top",
":",
"val",
"}",
")",
";",
"if",
"(",
"cm",
".",
"display",
".",
"scroller",
".",
"scrollTop",
"!=",
"val",
")",
"cm",
".",
"display",
".",
"scroller",
".",
"scrollTop",
"=",
"val",
";",
"cm",
".",
"display",
".",
"scrollbars",
".",
"setScrollTop",
"(",
"val",
")",
";",
"if",
"(",
"gecko",
")",
"updateDisplaySimple",
"(",
"cm",
")",
";",
"startWorker",
"(",
"cm",
",",
"100",
")",
";",
"}"
] | Sync the scrollable area and scrollbars, ensure the viewport covers the visible area. | [
"Sync",
"the",
"scrollable",
"area",
"and",
"scrollbars",
"ensure",
"the",
"viewport",
"covers",
"the",
"visible",
"area",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L5077-L5085 | train |
tmcw/stickshift | stickshift.js | ensureCursorVisible | function ensureCursorVisible(cm) {
resolveScrollToPos(cm);
var cur = cm.getCursor(), from = cur, to = cur;
if (!cm.options.lineWrapping) {
from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
to = Pos(cur.line, cur.ch + 1);
}
cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
} | javascript | function ensureCursorVisible(cm) {
resolveScrollToPos(cm);
var cur = cm.getCursor(), from = cur, to = cur;
if (!cm.options.lineWrapping) {
from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
to = Pos(cur.line, cur.ch + 1);
}
cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
} | [
"function",
"ensureCursorVisible",
"(",
"cm",
")",
"{",
"resolveScrollToPos",
"(",
"cm",
")",
";",
"var",
"cur",
"=",
"cm",
".",
"getCursor",
"(",
")",
",",
"from",
"=",
"cur",
",",
"to",
"=",
"cur",
";",
"if",
"(",
"!",
"cm",
".",
"options",
".",
"lineWrapping",
")",
"{",
"from",
"=",
"cur",
".",
"ch",
"?",
"Pos",
"(",
"cur",
".",
"line",
",",
"cur",
".",
"ch",
"-",
"1",
")",
":",
"cur",
";",
"to",
"=",
"Pos",
"(",
"cur",
".",
"line",
",",
"cur",
".",
"ch",
"+",
"1",
")",
";",
"}",
"cm",
".",
"curOp",
".",
"scrollToPos",
"=",
"{",
"from",
":",
"from",
",",
"to",
":",
"to",
",",
"margin",
":",
"cm",
".",
"options",
".",
"cursorScrollMargin",
",",
"isCursor",
":",
"true",
"}",
";",
"}"
] | Make sure that at the end of the operation the current cursor is shown. | [
"Make",
"sure",
"that",
"at",
"the",
"end",
"of",
"the",
"operation",
"the",
"current",
"cursor",
"is",
"shown",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L5863-L5871 | train |
tmcw/stickshift | stickshift.js | takeToken | function takeToken(cm, pos, precise, asArray) {
function getObj(copy) {
return {start: stream.start, end: stream.pos,
string: stream.current(),
type: style || null,
state: copy ? copyState(doc.mode, state) : state};
}
var doc = cm.doc, mode = doc.mode, style;
pos = clipPos(doc, pos);
var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
var stream = new StringStream(line.text, cm.options.tabSize), tokens;
if (asArray) tokens = [];
while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
stream.start = stream.pos;
style = readToken(mode, stream, state);
if (asArray) tokens.push(getObj(true));
}
return asArray ? tokens : getObj();
} | javascript | function takeToken(cm, pos, precise, asArray) {
function getObj(copy) {
return {start: stream.start, end: stream.pos,
string: stream.current(),
type: style || null,
state: copy ? copyState(doc.mode, state) : state};
}
var doc = cm.doc, mode = doc.mode, style;
pos = clipPos(doc, pos);
var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
var stream = new StringStream(line.text, cm.options.tabSize), tokens;
if (asArray) tokens = [];
while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
stream.start = stream.pos;
style = readToken(mode, stream, state);
if (asArray) tokens.push(getObj(true));
}
return asArray ? tokens : getObj();
} | [
"function",
"takeToken",
"(",
"cm",
",",
"pos",
",",
"precise",
",",
"asArray",
")",
"{",
"function",
"getObj",
"(",
"copy",
")",
"{",
"return",
"{",
"start",
":",
"stream",
".",
"start",
",",
"end",
":",
"stream",
".",
"pos",
",",
"string",
":",
"stream",
".",
"current",
"(",
")",
",",
"type",
":",
"style",
"||",
"null",
",",
"state",
":",
"copy",
"?",
"copyState",
"(",
"doc",
".",
"mode",
",",
"state",
")",
":",
"state",
"}",
";",
"}",
"var",
"doc",
"=",
"cm",
".",
"doc",
",",
"mode",
"=",
"doc",
".",
"mode",
",",
"style",
";",
"pos",
"=",
"clipPos",
"(",
"doc",
",",
"pos",
")",
";",
"var",
"line",
"=",
"getLine",
"(",
"doc",
",",
"pos",
".",
"line",
")",
",",
"state",
"=",
"getStateBefore",
"(",
"cm",
",",
"pos",
".",
"line",
",",
"precise",
")",
";",
"var",
"stream",
"=",
"new",
"StringStream",
"(",
"line",
".",
"text",
",",
"cm",
".",
"options",
".",
"tabSize",
")",
",",
"tokens",
";",
"if",
"(",
"asArray",
")",
"tokens",
"=",
"[",
"]",
";",
"while",
"(",
"(",
"asArray",
"||",
"stream",
".",
"pos",
"<",
"pos",
".",
"ch",
")",
"&&",
"!",
"stream",
".",
"eol",
"(",
")",
")",
"{",
"stream",
".",
"start",
"=",
"stream",
".",
"pos",
";",
"style",
"=",
"readToken",
"(",
"mode",
",",
"stream",
",",
"state",
")",
";",
"if",
"(",
"asArray",
")",
"tokens",
".",
"push",
"(",
"getObj",
"(",
"true",
")",
")",
";",
"}",
"return",
"asArray",
"?",
"tokens",
":",
"getObj",
"(",
")",
";",
"}"
] | Utility for getTokenAt and getLineTokens | [
"Utility",
"for",
"getTokenAt",
"and",
"getLineTokens"
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L7924-L7943 | train |
tmcw/stickshift | stickshift.js | buildLineContent | function buildLineContent(cm, lineView) {
// The padding-right forces the element to have a 'border', which
// is needed on Webkit to be able to get line-level bounding
// rectangles for it (in measureChar).
var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
lineView.measure = {};
// Iterate over the logical lines that make up this visual line.
for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
var line = i ? lineView.rest[i - 1] : lineView.line, order;
builder.pos = 0;
builder.addToken = buildToken;
// Optionally wire in some hacks into the token-rendering
// algorithm, to deal with browser quirks.
if ((ie || webkit) && cm.getOption("lineWrapping"))
builder.addToken = buildTokenSplitSpaces(builder.addToken);
if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
builder.addToken = buildTokenBadBidi(builder.addToken, order);
builder.map = [];
var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
if (line.styleClasses) {
if (line.styleClasses.bgClass)
builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
if (line.styleClasses.textClass)
builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
}
// Ensure at least a single node is present, for measuring.
if (builder.map.length == 0)
builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
// Store the map and a cache object for the current logical line
if (i == 0) {
lineView.measure.map = builder.map;
lineView.measure.cache = {};
} else {
(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
(lineView.measure.caches || (lineView.measure.caches = [])).push({});
}
}
// See issue #2901
if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
builder.content.className = "cm-tab-wrap-hack";
signal(cm, "renderLine", cm, lineView.line, builder.pre);
if (builder.pre.className)
builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
return builder;
} | javascript | function buildLineContent(cm, lineView) {
// The padding-right forces the element to have a 'border', which
// is needed on Webkit to be able to get line-level bounding
// rectangles for it (in measureChar).
var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
lineView.measure = {};
// Iterate over the logical lines that make up this visual line.
for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
var line = i ? lineView.rest[i - 1] : lineView.line, order;
builder.pos = 0;
builder.addToken = buildToken;
// Optionally wire in some hacks into the token-rendering
// algorithm, to deal with browser quirks.
if ((ie || webkit) && cm.getOption("lineWrapping"))
builder.addToken = buildTokenSplitSpaces(builder.addToken);
if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
builder.addToken = buildTokenBadBidi(builder.addToken, order);
builder.map = [];
var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
if (line.styleClasses) {
if (line.styleClasses.bgClass)
builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
if (line.styleClasses.textClass)
builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
}
// Ensure at least a single node is present, for measuring.
if (builder.map.length == 0)
builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
// Store the map and a cache object for the current logical line
if (i == 0) {
lineView.measure.map = builder.map;
lineView.measure.cache = {};
} else {
(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
(lineView.measure.caches || (lineView.measure.caches = [])).push({});
}
}
// See issue #2901
if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
builder.content.className = "cm-tab-wrap-hack";
signal(cm, "renderLine", cm, lineView.line, builder.pre);
if (builder.pre.className)
builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
return builder;
} | [
"function",
"buildLineContent",
"(",
"cm",
",",
"lineView",
")",
"{",
"// The padding-right forces the element to have a 'border', which",
"// is needed on Webkit to be able to get line-level bounding",
"// rectangles for it (in measureChar).",
"var",
"content",
"=",
"elt",
"(",
"\"span\"",
",",
"null",
",",
"null",
",",
"webkit",
"?",
"\"padding-right: .1px\"",
":",
"null",
")",
";",
"var",
"builder",
"=",
"{",
"pre",
":",
"elt",
"(",
"\"pre\"",
",",
"[",
"content",
"]",
")",
",",
"content",
":",
"content",
",",
"col",
":",
"0",
",",
"pos",
":",
"0",
",",
"cm",
":",
"cm",
"}",
";",
"lineView",
".",
"measure",
"=",
"{",
"}",
";",
"// Iterate over the logical lines that make up this visual line.",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<=",
"(",
"lineView",
".",
"rest",
"?",
"lineView",
".",
"rest",
".",
"length",
":",
"0",
")",
";",
"i",
"++",
")",
"{",
"var",
"line",
"=",
"i",
"?",
"lineView",
".",
"rest",
"[",
"i",
"-",
"1",
"]",
":",
"lineView",
".",
"line",
",",
"order",
";",
"builder",
".",
"pos",
"=",
"0",
";",
"builder",
".",
"addToken",
"=",
"buildToken",
";",
"// Optionally wire in some hacks into the token-rendering",
"// algorithm, to deal with browser quirks.",
"if",
"(",
"(",
"ie",
"||",
"webkit",
")",
"&&",
"cm",
".",
"getOption",
"(",
"\"lineWrapping\"",
")",
")",
"builder",
".",
"addToken",
"=",
"buildTokenSplitSpaces",
"(",
"builder",
".",
"addToken",
")",
";",
"if",
"(",
"hasBadBidiRects",
"(",
"cm",
".",
"display",
".",
"measure",
")",
"&&",
"(",
"order",
"=",
"getOrder",
"(",
"line",
")",
")",
")",
"builder",
".",
"addToken",
"=",
"buildTokenBadBidi",
"(",
"builder",
".",
"addToken",
",",
"order",
")",
";",
"builder",
".",
"map",
"=",
"[",
"]",
";",
"var",
"allowFrontierUpdate",
"=",
"lineView",
"!=",
"cm",
".",
"display",
".",
"externalMeasured",
"&&",
"lineNo",
"(",
"line",
")",
";",
"insertLineContent",
"(",
"line",
",",
"builder",
",",
"getLineStyles",
"(",
"cm",
",",
"line",
",",
"allowFrontierUpdate",
")",
")",
";",
"if",
"(",
"line",
".",
"styleClasses",
")",
"{",
"if",
"(",
"line",
".",
"styleClasses",
".",
"bgClass",
")",
"builder",
".",
"bgClass",
"=",
"joinClasses",
"(",
"line",
".",
"styleClasses",
".",
"bgClass",
",",
"builder",
".",
"bgClass",
"||",
"\"\"",
")",
";",
"if",
"(",
"line",
".",
"styleClasses",
".",
"textClass",
")",
"builder",
".",
"textClass",
"=",
"joinClasses",
"(",
"line",
".",
"styleClasses",
".",
"textClass",
",",
"builder",
".",
"textClass",
"||",
"\"\"",
")",
";",
"}",
"// Ensure at least a single node is present, for measuring.",
"if",
"(",
"builder",
".",
"map",
".",
"length",
"==",
"0",
")",
"builder",
".",
"map",
".",
"push",
"(",
"0",
",",
"0",
",",
"builder",
".",
"content",
".",
"appendChild",
"(",
"zeroWidthElement",
"(",
"cm",
".",
"display",
".",
"measure",
")",
")",
")",
";",
"// Store the map and a cache object for the current logical line",
"if",
"(",
"i",
"==",
"0",
")",
"{",
"lineView",
".",
"measure",
".",
"map",
"=",
"builder",
".",
"map",
";",
"lineView",
".",
"measure",
".",
"cache",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"(",
"lineView",
".",
"measure",
".",
"maps",
"||",
"(",
"lineView",
".",
"measure",
".",
"maps",
"=",
"[",
"]",
")",
")",
".",
"push",
"(",
"builder",
".",
"map",
")",
";",
"(",
"lineView",
".",
"measure",
".",
"caches",
"||",
"(",
"lineView",
".",
"measure",
".",
"caches",
"=",
"[",
"]",
")",
")",
".",
"push",
"(",
"{",
"}",
")",
";",
"}",
"}",
"// See issue #2901",
"if",
"(",
"webkit",
"&&",
"/",
"\\bcm-tab\\b",
"/",
".",
"test",
"(",
"builder",
".",
"content",
".",
"lastChild",
".",
"className",
")",
")",
"builder",
".",
"content",
".",
"className",
"=",
"\"cm-tab-wrap-hack\"",
";",
"signal",
"(",
"cm",
",",
"\"renderLine\"",
",",
"cm",
",",
"lineView",
".",
"line",
",",
"builder",
".",
"pre",
")",
";",
"if",
"(",
"builder",
".",
"pre",
".",
"className",
")",
"builder",
".",
"textClass",
"=",
"joinClasses",
"(",
"builder",
".",
"pre",
".",
"className",
",",
"builder",
".",
"textClass",
"||",
"\"\"",
")",
";",
"return",
"builder",
";",
"}"
] | Render the DOM representation of the text of a line. Also builds up a 'line map', which points at the DOM nodes that represent specific stretches of text, and is used by the measuring code. The returned object contains the DOM node, this map, and information about line-wide styles that were set by the mode. | [
"Render",
"the",
"DOM",
"representation",
"of",
"the",
"text",
"of",
"a",
"line",
".",
"Also",
"builds",
"up",
"a",
"line",
"map",
"which",
"points",
"at",
"the",
"DOM",
"nodes",
"that",
"represent",
"specific",
"stretches",
"of",
"text",
"and",
"is",
"used",
"by",
"the",
"measuring",
"code",
".",
"The",
"returned",
"object",
"contains",
"the",
"DOM",
"node",
"this",
"map",
"and",
"information",
"about",
"line",
"-",
"wide",
"styles",
"that",
"were",
"set",
"by",
"the",
"mode",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L8066-L8118 | train |
tmcw/stickshift | stickshift.js | buildToken | function buildToken(builder, text, style, startStyle, endStyle, title, css) {
if (!text) return;
var special = builder.cm.options.specialChars, mustWrap = false;
if (!special.test(text)) {
builder.col += text.length;
var content = document.createTextNode(text);
builder.map.push(builder.pos, builder.pos + text.length, content);
if (ie && ie_version < 9) mustWrap = true;
builder.pos += text.length;
} else {
var content = document.createDocumentFragment(), pos = 0;
while (true) {
special.lastIndex = pos;
var m = special.exec(text);
var skipped = m ? m.index - pos : text.length - pos;
if (skipped) {
var txt = document.createTextNode(text.slice(pos, pos + skipped));
if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.map.push(builder.pos, builder.pos + skipped, txt);
builder.col += skipped;
builder.pos += skipped;
}
if (!m) break;
pos += skipped + 1;
if (m[0] == "\t") {
var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
txt.setAttribute("role", "presentation");
builder.col += tabWidth;
} else {
var txt = builder.cm.options.specialCharPlaceholder(m[0]);
if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.col += 1;
}
builder.map.push(builder.pos, builder.pos + 1, txt);
builder.pos++;
}
}
if (style || startStyle || endStyle || mustWrap || css) {
var fullStyle = style || "";
if (startStyle) fullStyle += startStyle;
if (endStyle) fullStyle += endStyle;
var token = elt("span", [content], fullStyle, css);
if (title) token.title = title;
return builder.content.appendChild(token);
}
builder.content.appendChild(content);
} | javascript | function buildToken(builder, text, style, startStyle, endStyle, title, css) {
if (!text) return;
var special = builder.cm.options.specialChars, mustWrap = false;
if (!special.test(text)) {
builder.col += text.length;
var content = document.createTextNode(text);
builder.map.push(builder.pos, builder.pos + text.length, content);
if (ie && ie_version < 9) mustWrap = true;
builder.pos += text.length;
} else {
var content = document.createDocumentFragment(), pos = 0;
while (true) {
special.lastIndex = pos;
var m = special.exec(text);
var skipped = m ? m.index - pos : text.length - pos;
if (skipped) {
var txt = document.createTextNode(text.slice(pos, pos + skipped));
if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.map.push(builder.pos, builder.pos + skipped, txt);
builder.col += skipped;
builder.pos += skipped;
}
if (!m) break;
pos += skipped + 1;
if (m[0] == "\t") {
var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
txt.setAttribute("role", "presentation");
builder.col += tabWidth;
} else {
var txt = builder.cm.options.specialCharPlaceholder(m[0]);
if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.col += 1;
}
builder.map.push(builder.pos, builder.pos + 1, txt);
builder.pos++;
}
}
if (style || startStyle || endStyle || mustWrap || css) {
var fullStyle = style || "";
if (startStyle) fullStyle += startStyle;
if (endStyle) fullStyle += endStyle;
var token = elt("span", [content], fullStyle, css);
if (title) token.title = title;
return builder.content.appendChild(token);
}
builder.content.appendChild(content);
} | [
"function",
"buildToken",
"(",
"builder",
",",
"text",
",",
"style",
",",
"startStyle",
",",
"endStyle",
",",
"title",
",",
"css",
")",
"{",
"if",
"(",
"!",
"text",
")",
"return",
";",
"var",
"special",
"=",
"builder",
".",
"cm",
".",
"options",
".",
"specialChars",
",",
"mustWrap",
"=",
"false",
";",
"if",
"(",
"!",
"special",
".",
"test",
"(",
"text",
")",
")",
"{",
"builder",
".",
"col",
"+=",
"text",
".",
"length",
";",
"var",
"content",
"=",
"document",
".",
"createTextNode",
"(",
"text",
")",
";",
"builder",
".",
"map",
".",
"push",
"(",
"builder",
".",
"pos",
",",
"builder",
".",
"pos",
"+",
"text",
".",
"length",
",",
"content",
")",
";",
"if",
"(",
"ie",
"&&",
"ie_version",
"<",
"9",
")",
"mustWrap",
"=",
"true",
";",
"builder",
".",
"pos",
"+=",
"text",
".",
"length",
";",
"}",
"else",
"{",
"var",
"content",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
",",
"pos",
"=",
"0",
";",
"while",
"(",
"true",
")",
"{",
"special",
".",
"lastIndex",
"=",
"pos",
";",
"var",
"m",
"=",
"special",
".",
"exec",
"(",
"text",
")",
";",
"var",
"skipped",
"=",
"m",
"?",
"m",
".",
"index",
"-",
"pos",
":",
"text",
".",
"length",
"-",
"pos",
";",
"if",
"(",
"skipped",
")",
"{",
"var",
"txt",
"=",
"document",
".",
"createTextNode",
"(",
"text",
".",
"slice",
"(",
"pos",
",",
"pos",
"+",
"skipped",
")",
")",
";",
"if",
"(",
"ie",
"&&",
"ie_version",
"<",
"9",
")",
"content",
".",
"appendChild",
"(",
"elt",
"(",
"\"span\"",
",",
"[",
"txt",
"]",
")",
")",
";",
"else",
"content",
".",
"appendChild",
"(",
"txt",
")",
";",
"builder",
".",
"map",
".",
"push",
"(",
"builder",
".",
"pos",
",",
"builder",
".",
"pos",
"+",
"skipped",
",",
"txt",
")",
";",
"builder",
".",
"col",
"+=",
"skipped",
";",
"builder",
".",
"pos",
"+=",
"skipped",
";",
"}",
"if",
"(",
"!",
"m",
")",
"break",
";",
"pos",
"+=",
"skipped",
"+",
"1",
";",
"if",
"(",
"m",
"[",
"0",
"]",
"==",
"\"\\t\"",
")",
"{",
"var",
"tabSize",
"=",
"builder",
".",
"cm",
".",
"options",
".",
"tabSize",
",",
"tabWidth",
"=",
"tabSize",
"-",
"builder",
".",
"col",
"%",
"tabSize",
";",
"var",
"txt",
"=",
"content",
".",
"appendChild",
"(",
"elt",
"(",
"\"span\"",
",",
"spaceStr",
"(",
"tabWidth",
")",
",",
"\"cm-tab\"",
")",
")",
";",
"txt",
".",
"setAttribute",
"(",
"\"role\"",
",",
"\"presentation\"",
")",
";",
"builder",
".",
"col",
"+=",
"tabWidth",
";",
"}",
"else",
"{",
"var",
"txt",
"=",
"builder",
".",
"cm",
".",
"options",
".",
"specialCharPlaceholder",
"(",
"m",
"[",
"0",
"]",
")",
";",
"if",
"(",
"ie",
"&&",
"ie_version",
"<",
"9",
")",
"content",
".",
"appendChild",
"(",
"elt",
"(",
"\"span\"",
",",
"[",
"txt",
"]",
")",
")",
";",
"else",
"content",
".",
"appendChild",
"(",
"txt",
")",
";",
"builder",
".",
"col",
"+=",
"1",
";",
"}",
"builder",
".",
"map",
".",
"push",
"(",
"builder",
".",
"pos",
",",
"builder",
".",
"pos",
"+",
"1",
",",
"txt",
")",
";",
"builder",
".",
"pos",
"++",
";",
"}",
"}",
"if",
"(",
"style",
"||",
"startStyle",
"||",
"endStyle",
"||",
"mustWrap",
"||",
"css",
")",
"{",
"var",
"fullStyle",
"=",
"style",
"||",
"\"\"",
";",
"if",
"(",
"startStyle",
")",
"fullStyle",
"+=",
"startStyle",
";",
"if",
"(",
"endStyle",
")",
"fullStyle",
"+=",
"endStyle",
";",
"var",
"token",
"=",
"elt",
"(",
"\"span\"",
",",
"[",
"content",
"]",
",",
"fullStyle",
",",
"css",
")",
";",
"if",
"(",
"title",
")",
"token",
".",
"title",
"=",
"title",
";",
"return",
"builder",
".",
"content",
".",
"appendChild",
"(",
"token",
")",
";",
"}",
"builder",
".",
"content",
".",
"appendChild",
"(",
"content",
")",
";",
"}"
] | Build up the DOM representation for a single token, and add it to the line map. Takes care to render special characters separately. | [
"Build",
"up",
"the",
"DOM",
"representation",
"for",
"a",
"single",
"token",
"and",
"add",
"it",
"to",
"the",
"line",
"map",
".",
"Takes",
"care",
"to",
"render",
"special",
"characters",
"separately",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L8129-L8178 | train |
tmcw/stickshift | stickshift.js | function(at, lines, height) {
this.height += height;
this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
} | javascript | function(at, lines, height) {
this.height += height;
this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
} | [
"function",
"(",
"at",
",",
"lines",
",",
"height",
")",
"{",
"this",
".",
"height",
"+=",
"height",
";",
"this",
".",
"lines",
"=",
"this",
".",
"lines",
".",
"slice",
"(",
"0",
",",
"at",
")",
".",
"concat",
"(",
"lines",
")",
".",
"concat",
"(",
"this",
".",
"lines",
".",
"slice",
"(",
"at",
")",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"lines",
".",
"length",
";",
"++",
"i",
")",
"lines",
"[",
"i",
"]",
".",
"parent",
"=",
"this",
";",
"}"
] | Insert the given array of lines at offset 'at', count them as having the given height. | [
"Insert",
"the",
"given",
"array",
"of",
"lines",
"at",
"offset",
"at",
"count",
"them",
"as",
"having",
"the",
"given",
"height",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L8386-L8390 | train |
|
tmcw/stickshift | stickshift.js | clearSelectionEvents | function clearSelectionEvents(array) {
while (array.length) {
var last = lst(array);
if (last.ranges) array.pop();
else break;
}
} | javascript | function clearSelectionEvents(array) {
while (array.length) {
var last = lst(array);
if (last.ranges) array.pop();
else break;
}
} | [
"function",
"clearSelectionEvents",
"(",
"array",
")",
"{",
"while",
"(",
"array",
".",
"length",
")",
"{",
"var",
"last",
"=",
"lst",
"(",
"array",
")",
";",
"if",
"(",
"last",
".",
"ranges",
")",
"array",
".",
"pop",
"(",
")",
";",
"else",
"break",
";",
"}",
"}"
] | Pop all selection events off the end of a history array. Stop at a change event. | [
"Pop",
"all",
"selection",
"events",
"off",
"the",
"end",
"of",
"a",
"history",
"array",
".",
"Stop",
"at",
"a",
"change",
"event",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L9013-L9019 | train |
tmcw/stickshift | stickshift.js | function() {
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (target_view) {
target_view.location.href = object_url;
} else {
var new_tab = view.open(object_url, "_blank");
if (new_tab == undefined && typeof safari !== "undefined") {
//Apple do not allow window.open, see http://bit.ly/1kZffRI
view.location.href = object_url
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
} | javascript | function() {
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (target_view) {
target_view.location.href = object_url;
} else {
var new_tab = view.open(object_url, "_blank");
if (new_tab == undefined && typeof safari !== "undefined") {
//Apple do not allow window.open, see http://bit.ly/1kZffRI
view.location.href = object_url
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
} | [
"function",
"(",
")",
"{",
"// don't create more object URLs than needed",
"if",
"(",
"blob_changed",
"||",
"!",
"object_url",
")",
"{",
"object_url",
"=",
"get_URL",
"(",
")",
".",
"createObjectURL",
"(",
"blob",
")",
";",
"}",
"if",
"(",
"target_view",
")",
"{",
"target_view",
".",
"location",
".",
"href",
"=",
"object_url",
";",
"}",
"else",
"{",
"var",
"new_tab",
"=",
"view",
".",
"open",
"(",
"object_url",
",",
"\"_blank\"",
")",
";",
"if",
"(",
"new_tab",
"==",
"undefined",
"&&",
"typeof",
"safari",
"!==",
"\"undefined\"",
")",
"{",
"//Apple do not allow window.open, see http://bit.ly/1kZffRI",
"view",
".",
"location",
".",
"href",
"=",
"object_url",
"}",
"}",
"filesaver",
".",
"readyState",
"=",
"filesaver",
".",
"DONE",
";",
"dispatch_all",
"(",
")",
";",
"revoke",
"(",
"object_url",
")",
";",
"}"
] | First try a.download, then web filesystem, then object URLs | [
"First",
"try",
"a",
".",
"download",
"then",
"web",
"filesystem",
"then",
"object",
"URLs"
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L10486-L10503 | train |
|
tmcw/stickshift | stickshift.js | DOMMouseMoveTracker | function DOMMouseMoveTracker(
onMove,
/*function*/ onMoveEnd,
/*DOMElement*/ domNode) {
this.$DOMMouseMoveTracker_isDragging = false;
this.$DOMMouseMoveTracker_animationFrameID = null;
this.$DOMMouseMoveTracker_domNode = domNode;
this.$DOMMouseMoveTracker_onMove = onMove;
this.$DOMMouseMoveTracker_onMoveEnd = onMoveEnd;
this.$DOMMouseMoveTracker_onMouseMove = this.$DOMMouseMoveTracker_onMouseMove.bind(this);
this.$DOMMouseMoveTracker_onMouseUp = this.$DOMMouseMoveTracker_onMouseUp.bind(this);
this.$DOMMouseMoveTracker_didMouseMove = this.$DOMMouseMoveTracker_didMouseMove.bind(this);
} | javascript | function DOMMouseMoveTracker(
onMove,
/*function*/ onMoveEnd,
/*DOMElement*/ domNode) {
this.$DOMMouseMoveTracker_isDragging = false;
this.$DOMMouseMoveTracker_animationFrameID = null;
this.$DOMMouseMoveTracker_domNode = domNode;
this.$DOMMouseMoveTracker_onMove = onMove;
this.$DOMMouseMoveTracker_onMoveEnd = onMoveEnd;
this.$DOMMouseMoveTracker_onMouseMove = this.$DOMMouseMoveTracker_onMouseMove.bind(this);
this.$DOMMouseMoveTracker_onMouseUp = this.$DOMMouseMoveTracker_onMouseUp.bind(this);
this.$DOMMouseMoveTracker_didMouseMove = this.$DOMMouseMoveTracker_didMouseMove.bind(this);
} | [
"function",
"DOMMouseMoveTracker",
"(",
"onMove",
",",
"/*function*/",
"onMoveEnd",
",",
"/*DOMElement*/",
"domNode",
")",
"{",
"this",
".",
"$DOMMouseMoveTracker_isDragging",
"=",
"false",
";",
"this",
".",
"$DOMMouseMoveTracker_animationFrameID",
"=",
"null",
";",
"this",
".",
"$DOMMouseMoveTracker_domNode",
"=",
"domNode",
";",
"this",
".",
"$DOMMouseMoveTracker_onMove",
"=",
"onMove",
";",
"this",
".",
"$DOMMouseMoveTracker_onMoveEnd",
"=",
"onMoveEnd",
";",
"this",
".",
"$DOMMouseMoveTracker_onMouseMove",
"=",
"this",
".",
"$DOMMouseMoveTracker_onMouseMove",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"$DOMMouseMoveTracker_onMouseUp",
"=",
"this",
".",
"$DOMMouseMoveTracker_onMouseUp",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"$DOMMouseMoveTracker_didMouseMove",
"=",
"this",
".",
"$DOMMouseMoveTracker_didMouseMove",
".",
"bind",
"(",
"this",
")",
";",
"}"
] | onMove is the callback that will be called on every mouse move.
onMoveEnd is called on mouse up when movement has ended. | [
"onMove",
"is",
"the",
"callback",
"that",
"will",
"be",
"called",
"on",
"every",
"mouse",
"move",
".",
"onMoveEnd",
"is",
"called",
"on",
"mouse",
"up",
"when",
"movement",
"has",
"ended",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L10708-L10720 | train |
tmcw/stickshift | stickshift.js | function(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function() {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function() {
target.detachEvent('on' + eventType, callback);
}
};
}
} | javascript | function(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function() {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function() {
target.detachEvent('on' + eventType, callback);
}
};
}
} | [
"function",
"(",
"target",
",",
"eventType",
",",
"callback",
")",
"{",
"if",
"(",
"target",
".",
"addEventListener",
")",
"{",
"target",
".",
"addEventListener",
"(",
"eventType",
",",
"callback",
",",
"false",
")",
";",
"return",
"{",
"remove",
":",
"function",
"(",
")",
"{",
"target",
".",
"removeEventListener",
"(",
"eventType",
",",
"callback",
",",
"false",
")",
";",
"}",
"}",
";",
"}",
"else",
"if",
"(",
"target",
".",
"attachEvent",
")",
"{",
"target",
".",
"attachEvent",
"(",
"'on'",
"+",
"eventType",
",",
"callback",
")",
";",
"return",
"{",
"remove",
":",
"function",
"(",
")",
"{",
"target",
".",
"detachEvent",
"(",
"'on'",
"+",
"eventType",
",",
"callback",
")",
";",
"}",
"}",
";",
"}",
"}"
] | Listen to DOM events during the bubble phase.
@param {DOMEventTarget} target DOM element to register listener on.
@param {string} eventType Event type, e.g. 'click' or 'mouseover'.
@param {function} callback Callback function.
@return {object} Object with a `remove` method. | [
"Listen",
"to",
"DOM",
"events",
"during",
"the",
"bubble",
"phase",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L10853-L10869 | train |
|
tmcw/stickshift | stickshift.js | function(
/*number*/ combinedWidth,
/*number*/ leftOffset,
/*number*/ cellWidth,
/*?number*/ cellMinWidth,
/*?number*/ cellMaxWidth,
/*number|string*/ columnKey,
/*object*/ event) {
if (Locale.isRTL()) {
leftOffset = -leftOffset;
}
this.setState({
isColumnResizing: true,
columnResizingData: {
left: leftOffset + combinedWidth - cellWidth,
width: cellWidth,
minWidth: cellMinWidth,
maxWidth: cellMaxWidth,
initialEvent: {
clientX: event.clientX,
clientY: event.clientY,
preventDefault: emptyFunction
},
key: columnKey
}
});
} | javascript | function(
/*number*/ combinedWidth,
/*number*/ leftOffset,
/*number*/ cellWidth,
/*?number*/ cellMinWidth,
/*?number*/ cellMaxWidth,
/*number|string*/ columnKey,
/*object*/ event) {
if (Locale.isRTL()) {
leftOffset = -leftOffset;
}
this.setState({
isColumnResizing: true,
columnResizingData: {
left: leftOffset + combinedWidth - cellWidth,
width: cellWidth,
minWidth: cellMinWidth,
maxWidth: cellMaxWidth,
initialEvent: {
clientX: event.clientX,
clientY: event.clientY,
preventDefault: emptyFunction
},
key: columnKey
}
});
} | [
"function",
"(",
"/*number*/",
"combinedWidth",
",",
"/*number*/",
"leftOffset",
",",
"/*number*/",
"cellWidth",
",",
"/*?number*/",
"cellMinWidth",
",",
"/*?number*/",
"cellMaxWidth",
",",
"/*number|string*/",
"columnKey",
",",
"/*object*/",
"event",
")",
"{",
"if",
"(",
"Locale",
".",
"isRTL",
"(",
")",
")",
"{",
"leftOffset",
"=",
"-",
"leftOffset",
";",
"}",
"this",
".",
"setState",
"(",
"{",
"isColumnResizing",
":",
"true",
",",
"columnResizingData",
":",
"{",
"left",
":",
"leftOffset",
"+",
"combinedWidth",
"-",
"cellWidth",
",",
"width",
":",
"cellWidth",
",",
"minWidth",
":",
"cellMinWidth",
",",
"maxWidth",
":",
"cellMaxWidth",
",",
"initialEvent",
":",
"{",
"clientX",
":",
"event",
".",
"clientX",
",",
"clientY",
":",
"event",
".",
"clientY",
",",
"preventDefault",
":",
"emptyFunction",
"}",
",",
"key",
":",
"columnKey",
"}",
"}",
")",
";",
"}"
] | This is called when a cell that is in the header of a column has its
resizer knob clicked on. It displays the resizer and puts in the correct
location on the table. | [
"This",
"is",
"called",
"when",
"a",
"cell",
"that",
"is",
"in",
"the",
"header",
"of",
"a",
"column",
"has",
"its",
"resizer",
"knob",
"clicked",
"on",
".",
"It",
"displays",
"the",
"resizer",
"and",
"puts",
"in",
"the",
"correct",
"location",
"on",
"the",
"table",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L11481-L11507 | train |
|
tmcw/stickshift | stickshift.js | forEachColumn | function forEachColumn(children, callback) {
React.Children.forEach(children, function(child) {
if (child.type === FixedDataTableColumnGroup.type) {
forEachColumn(child.props.children, callback);
} else if (child.type === FixedDataTableColumn.type) {
callback(child);
}
});
} | javascript | function forEachColumn(children, callback) {
React.Children.forEach(children, function(child) {
if (child.type === FixedDataTableColumnGroup.type) {
forEachColumn(child.props.children, callback);
} else if (child.type === FixedDataTableColumn.type) {
callback(child);
}
});
} | [
"function",
"forEachColumn",
"(",
"children",
",",
"callback",
")",
"{",
"React",
".",
"Children",
".",
"forEach",
"(",
"children",
",",
"function",
"(",
"child",
")",
"{",
"if",
"(",
"child",
".",
"type",
"===",
"FixedDataTableColumnGroup",
".",
"type",
")",
"{",
"forEachColumn",
"(",
"child",
".",
"props",
".",
"children",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"child",
".",
"type",
"===",
"FixedDataTableColumn",
".",
"type",
")",
"{",
"callback",
"(",
"child",
")",
";",
"}",
"}",
")",
";",
"}"
] | Helper method to execute a callback against all columns given the children
of a table.
@param {?object|array} children
Children of a table.
@param {function} callback
Function to excecute for each column. It is passed the column. | [
"Helper",
"method",
"to",
"execute",
"a",
"callback",
"against",
"all",
"columns",
"given",
"the",
"children",
"of",
"a",
"table",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L13013-L13021 | train |
tmcw/stickshift | stickshift.js | mapColumns | function mapColumns(children, callback) {
var newChildren = [];
React.Children.forEach(children, function(originalChild) {
var newChild = originalChild;
// The child is either a column group or a column. If it is a column group
// we need to iterate over its columns and then potentially generate a
// new column group
if (originalChild.type === FixedDataTableColumnGroup.type) {
var haveColumnsChanged = false;
var newColumns = [];
forEachColumn(originalChild.props.children, function(originalcolumn) {
var newColumn = callback(originalcolumn);
if (newColumn !== originalcolumn) {
haveColumnsChanged = true;
}
newColumns.push(newColumn);
});
// If the column groups columns have changed clone the group and supply
// new children
if (haveColumnsChanged) {
newChild = cloneWithProps(originalChild, {children: newColumns});
}
} else if (originalChild.type === FixedDataTableColumn.type) {
newChild = callback(originalChild);
}
newChildren.push(newChild);
});
return newChildren;
} | javascript | function mapColumns(children, callback) {
var newChildren = [];
React.Children.forEach(children, function(originalChild) {
var newChild = originalChild;
// The child is either a column group or a column. If it is a column group
// we need to iterate over its columns and then potentially generate a
// new column group
if (originalChild.type === FixedDataTableColumnGroup.type) {
var haveColumnsChanged = false;
var newColumns = [];
forEachColumn(originalChild.props.children, function(originalcolumn) {
var newColumn = callback(originalcolumn);
if (newColumn !== originalcolumn) {
haveColumnsChanged = true;
}
newColumns.push(newColumn);
});
// If the column groups columns have changed clone the group and supply
// new children
if (haveColumnsChanged) {
newChild = cloneWithProps(originalChild, {children: newColumns});
}
} else if (originalChild.type === FixedDataTableColumn.type) {
newChild = callback(originalChild);
}
newChildren.push(newChild);
});
return newChildren;
} | [
"function",
"mapColumns",
"(",
"children",
",",
"callback",
")",
"{",
"var",
"newChildren",
"=",
"[",
"]",
";",
"React",
".",
"Children",
".",
"forEach",
"(",
"children",
",",
"function",
"(",
"originalChild",
")",
"{",
"var",
"newChild",
"=",
"originalChild",
";",
"// The child is either a column group or a column. If it is a column group",
"// we need to iterate over its columns and then potentially generate a",
"// new column group",
"if",
"(",
"originalChild",
".",
"type",
"===",
"FixedDataTableColumnGroup",
".",
"type",
")",
"{",
"var",
"haveColumnsChanged",
"=",
"false",
";",
"var",
"newColumns",
"=",
"[",
"]",
";",
"forEachColumn",
"(",
"originalChild",
".",
"props",
".",
"children",
",",
"function",
"(",
"originalcolumn",
")",
"{",
"var",
"newColumn",
"=",
"callback",
"(",
"originalcolumn",
")",
";",
"if",
"(",
"newColumn",
"!==",
"originalcolumn",
")",
"{",
"haveColumnsChanged",
"=",
"true",
";",
"}",
"newColumns",
".",
"push",
"(",
"newColumn",
")",
";",
"}",
")",
";",
"// If the column groups columns have changed clone the group and supply",
"// new children",
"if",
"(",
"haveColumnsChanged",
")",
"{",
"newChild",
"=",
"cloneWithProps",
"(",
"originalChild",
",",
"{",
"children",
":",
"newColumns",
"}",
")",
";",
"}",
"}",
"else",
"if",
"(",
"originalChild",
".",
"type",
"===",
"FixedDataTableColumn",
".",
"type",
")",
"{",
"newChild",
"=",
"callback",
"(",
"originalChild",
")",
";",
"}",
"newChildren",
".",
"push",
"(",
"newChild",
")",
";",
"}",
")",
";",
"return",
"newChildren",
";",
"}"
] | Helper method to map columns to new columns. This takes into account column
groups and will generate a new column group if its columns change.
@param {?object|array} children
Children of a table.
@param {function} callback
Function to excecute for each column. It is passed the column and should
return a result column. | [
"Helper",
"method",
"to",
"map",
"columns",
"to",
"new",
"columns",
".",
"This",
"takes",
"into",
"account",
"column",
"groups",
"and",
"will",
"generate",
"a",
"new",
"column",
"group",
"if",
"its",
"columns",
"change",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L13032-L13065 | train |
tmcw/stickshift | stickshift.js | FixedDataTableRowBuffer | function FixedDataTableRowBuffer(
rowsCount,
/*number*/ defaultRowHeight,
/*number*/ viewportHeight,
/*?function*/ rowHeightGetter)
{
invariant(
defaultRowHeight !== 0,
"defaultRowHeight musn't be equal 0 in FixedDataTableRowBuffer"
);
this.$FixedDataTableRowBuffer_bufferSet = new IntegerBufferSet();
this.$FixedDataTableRowBuffer_defaultRowHeight = defaultRowHeight;
this.$FixedDataTableRowBuffer_viewportRowsBegin = 0;
this.$FixedDataTableRowBuffer_viewportRowsEnd = 0;
this.$FixedDataTableRowBuffer_maxVisibleRowCount = Math.ceil(viewportHeight / defaultRowHeight) + 1;
this.$FixedDataTableRowBuffer_bufferRowsCount = clamp(
MIN_BUFFER_ROWS,
Math.floor(this.$FixedDataTableRowBuffer_maxVisibleRowCount/2),
MAX_BUFFER_ROWS
);
this.$FixedDataTableRowBuffer_rowsCount = rowsCount;
this.$FixedDataTableRowBuffer_rowHeightGetter = rowHeightGetter;
this.$FixedDataTableRowBuffer_rows = [];
this.$FixedDataTableRowBuffer_viewportHeight = viewportHeight;
this.getRows = this.getRows.bind(this);
this.getRowsWithUpdatedBuffer = this.getRowsWithUpdatedBuffer.bind(this);
} | javascript | function FixedDataTableRowBuffer(
rowsCount,
/*number*/ defaultRowHeight,
/*number*/ viewportHeight,
/*?function*/ rowHeightGetter)
{
invariant(
defaultRowHeight !== 0,
"defaultRowHeight musn't be equal 0 in FixedDataTableRowBuffer"
);
this.$FixedDataTableRowBuffer_bufferSet = new IntegerBufferSet();
this.$FixedDataTableRowBuffer_defaultRowHeight = defaultRowHeight;
this.$FixedDataTableRowBuffer_viewportRowsBegin = 0;
this.$FixedDataTableRowBuffer_viewportRowsEnd = 0;
this.$FixedDataTableRowBuffer_maxVisibleRowCount = Math.ceil(viewportHeight / defaultRowHeight) + 1;
this.$FixedDataTableRowBuffer_bufferRowsCount = clamp(
MIN_BUFFER_ROWS,
Math.floor(this.$FixedDataTableRowBuffer_maxVisibleRowCount/2),
MAX_BUFFER_ROWS
);
this.$FixedDataTableRowBuffer_rowsCount = rowsCount;
this.$FixedDataTableRowBuffer_rowHeightGetter = rowHeightGetter;
this.$FixedDataTableRowBuffer_rows = [];
this.$FixedDataTableRowBuffer_viewportHeight = viewportHeight;
this.getRows = this.getRows.bind(this);
this.getRowsWithUpdatedBuffer = this.getRowsWithUpdatedBuffer.bind(this);
} | [
"function",
"FixedDataTableRowBuffer",
"(",
"rowsCount",
",",
"/*number*/",
"defaultRowHeight",
",",
"/*number*/",
"viewportHeight",
",",
"/*?function*/",
"rowHeightGetter",
")",
"{",
"invariant",
"(",
"defaultRowHeight",
"!==",
"0",
",",
"\"defaultRowHeight musn't be equal 0 in FixedDataTableRowBuffer\"",
")",
";",
"this",
".",
"$FixedDataTableRowBuffer_bufferSet",
"=",
"new",
"IntegerBufferSet",
"(",
")",
";",
"this",
".",
"$FixedDataTableRowBuffer_defaultRowHeight",
"=",
"defaultRowHeight",
";",
"this",
".",
"$FixedDataTableRowBuffer_viewportRowsBegin",
"=",
"0",
";",
"this",
".",
"$FixedDataTableRowBuffer_viewportRowsEnd",
"=",
"0",
";",
"this",
".",
"$FixedDataTableRowBuffer_maxVisibleRowCount",
"=",
"Math",
".",
"ceil",
"(",
"viewportHeight",
"/",
"defaultRowHeight",
")",
"+",
"1",
";",
"this",
".",
"$FixedDataTableRowBuffer_bufferRowsCount",
"=",
"clamp",
"(",
"MIN_BUFFER_ROWS",
",",
"Math",
".",
"floor",
"(",
"this",
".",
"$FixedDataTableRowBuffer_maxVisibleRowCount",
"/",
"2",
")",
",",
"MAX_BUFFER_ROWS",
")",
";",
"this",
".",
"$FixedDataTableRowBuffer_rowsCount",
"=",
"rowsCount",
";",
"this",
".",
"$FixedDataTableRowBuffer_rowHeightGetter",
"=",
"rowHeightGetter",
";",
"this",
".",
"$FixedDataTableRowBuffer_rows",
"=",
"[",
"]",
";",
"this",
".",
"$FixedDataTableRowBuffer_viewportHeight",
"=",
"viewportHeight",
";",
"this",
".",
"getRows",
"=",
"this",
".",
"getRows",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"getRowsWithUpdatedBuffer",
"=",
"this",
".",
"getRowsWithUpdatedBuffer",
".",
"bind",
"(",
"this",
")",
";",
"}"
] | FixedDataTableRowBuffer is a helper class that executes row buffering logic for FixedDataTable. It figures out which rows should be rendered and in which positions. | [
"FixedDataTableRowBuffer",
"is",
"a",
"helper",
"class",
"that",
"executes",
"row",
"buffering",
"logic",
"for",
"FixedDataTable",
".",
"It",
"figures",
"out",
"which",
"rows",
"should",
"be",
"rendered",
"and",
"in",
"which",
"positions",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L13387-L13415 | train |
tmcw/stickshift | stickshift.js | cx | function cx(classNames) {
var classNamesArray;
if (typeof classNames == 'object') {
classNamesArray = Object.keys(classNames).filter(function(className) {
return classNames[className];
});
} else {
classNamesArray = Array.prototype.slice.call(arguments);
}
return classNamesArray.map(getClassName).join(' ');
} | javascript | function cx(classNames) {
var classNamesArray;
if (typeof classNames == 'object') {
classNamesArray = Object.keys(classNames).filter(function(className) {
return classNames[className];
});
} else {
classNamesArray = Array.prototype.slice.call(arguments);
}
return classNamesArray.map(getClassName).join(' ');
} | [
"function",
"cx",
"(",
"classNames",
")",
"{",
"var",
"classNamesArray",
";",
"if",
"(",
"typeof",
"classNames",
"==",
"'object'",
")",
"{",
"classNamesArray",
"=",
"Object",
".",
"keys",
"(",
"classNames",
")",
".",
"filter",
"(",
"function",
"(",
"className",
")",
"{",
"return",
"classNames",
"[",
"className",
"]",
";",
"}",
")",
";",
"}",
"else",
"{",
"classNamesArray",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"}",
"return",
"classNamesArray",
".",
"map",
"(",
"getClassName",
")",
".",
"join",
"(",
"' '",
")",
";",
"}"
] | This function is used to mark string literals representing CSS class names
so that they can be transformed statically. This allows for modularization
and minification of CSS class names.
In static_upstream, this function is actually implemented, but it should
eventually be replaced with something more descriptive, and the transform
that is used in the main stack should be ported for use elsewhere.
@param string|object className to modularize, or an object of key/values.
In the object case, the values are conditions that
determine if the className keys should be included.
@param [string ...] Variable list of classNames in the string case.
@return string Renderable space-separated CSS className. | [
"This",
"function",
"is",
"used",
"to",
"mark",
"string",
"literals",
"representing",
"CSS",
"class",
"names",
"so",
"that",
"they",
"can",
"be",
"transformed",
"statically",
".",
"This",
"allows",
"for",
"modularization",
"and",
"minification",
"of",
"CSS",
"class",
"names",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L15873-L15884 | train |
tmcw/stickshift | stickshift.js | function(obj) {
var ret = {};
var key;
invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
);
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
} | javascript | function(obj) {
var ret = {};
var key;
invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
);
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
} | [
"function",
"(",
"obj",
")",
"{",
"var",
"ret",
"=",
"{",
"}",
";",
"var",
"key",
";",
"invariant",
"(",
"obj",
"instanceof",
"Object",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"obj",
")",
",",
"'keyMirror(...): Argument must be an object.'",
")",
";",
"for",
"(",
"key",
"in",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"continue",
";",
"}",
"ret",
"[",
"key",
"]",
"=",
"key",
";",
"}",
"return",
"ret",
";",
"}"
] | Constructs an enumeration with keys equal to their value.
For example:
var COLORS = keyMirror({blue: null, red: null});
var myColor = COLORS.blue;
var isColorValid = !!COLORS[myColor];
The last line could not be performed if the values of the generated enum were
not equal to their keys.
Input: {key1: val1, key2: val2}
Output: {key1: key1, key2: key2}
@param {object} obj
@return {object} | [
"Constructs",
"an",
"enumeration",
"with",
"keys",
"equal",
"to",
"their",
"value",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L16267-L16281 | train |
|
tmcw/stickshift | stickshift.js | shallowEqual | function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var key;
// Test for A's keys different from B.
for (key in objA) {
if (objA.hasOwnProperty(key) &&
(!objB.hasOwnProperty(key) || objA[key] !== objB[key])) {
return false;
}
}
// Test for B's keys missing from A.
for (key in objB) {
if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) {
return false;
}
}
return true;
} | javascript | function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var key;
// Test for A's keys different from B.
for (key in objA) {
if (objA.hasOwnProperty(key) &&
(!objB.hasOwnProperty(key) || objA[key] !== objB[key])) {
return false;
}
}
// Test for B's keys missing from A.
for (key in objB) {
if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) {
return false;
}
}
return true;
} | [
"function",
"shallowEqual",
"(",
"objA",
",",
"objB",
")",
"{",
"if",
"(",
"objA",
"===",
"objB",
")",
"{",
"return",
"true",
";",
"}",
"var",
"key",
";",
"// Test for A's keys different from B.",
"for",
"(",
"key",
"in",
"objA",
")",
"{",
"if",
"(",
"objA",
".",
"hasOwnProperty",
"(",
"key",
")",
"&&",
"(",
"!",
"objB",
".",
"hasOwnProperty",
"(",
"key",
")",
"||",
"objA",
"[",
"key",
"]",
"!==",
"objB",
"[",
"key",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"// Test for B's keys missing from A.",
"for",
"(",
"key",
"in",
"objB",
")",
"{",
"if",
"(",
"objB",
".",
"hasOwnProperty",
"(",
"key",
")",
"&&",
"!",
"objA",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Performs equality by iterating through keys on an object and returning
false when any key has values which are not strictly equal between
objA and objB. Returns true when the values of all keys are strictly equal.
@return {boolean} | [
"Performs",
"equality",
"by",
"iterating",
"through",
"keys",
"on",
"an",
"object",
"and",
"returning",
"false",
"when",
"any",
"key",
"has",
"values",
"which",
"are",
"not",
"strictly",
"equal",
"between",
"objA",
"and",
"objB",
".",
"Returns",
"true",
"when",
"the",
"values",
"of",
"all",
"keys",
"are",
"strictly",
"equal",
"."
] | 1be06709ca2e1c59d5e5d4b9a0c7b34a46349001 | https://github.com/tmcw/stickshift/blob/1be06709ca2e1c59d5e5d4b9a0c7b34a46349001/stickshift.js#L16729-L16748 | train |
darul75/ng-prettyjson | dist/ng-prettyjson.min.js | function(a){var b;
// the final two arguments are the length, and the entire string itself;
// we don't care about those.
if(arguments.length<7)throw new Error("markup() must be called from String.prototype.replace()");return b=e.apply(null,arguments),'<span class="'+d[b]+'">'+a+"</span>"} | javascript | function(a){var b;
// the final two arguments are the length, and the entire string itself;
// we don't care about those.
if(arguments.length<7)throw new Error("markup() must be called from String.prototype.replace()");return b=e.apply(null,arguments),'<span class="'+d[b]+'">'+a+"</span>"} | [
"function",
"(",
"a",
")",
"{",
"var",
"b",
";",
"// the final two arguments are the length, and the entire string itself;",
"// we don't care about those.",
"if",
"(",
"arguments",
".",
"length",
"<",
"7",
")",
"throw",
"new",
"Error",
"(",
"\"markup() must be called from String.prototype.replace()\"",
")",
";",
"return",
"b",
"=",
"e",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
",",
"'<span class=\"'",
"+",
"d",
"[",
"b",
"]",
"+",
"'\">'",
"+",
"a",
"+",
"\"</span>\"",
"}"
] | cache some regular expressions | [
"cache",
"some",
"regular",
"expressions"
] | 2af9bae4d4e9021b5d22e09ffff593b3f5b25f5a | https://github.com/darul75/ng-prettyjson/blob/2af9bae4d4e9021b5d22e09ffff593b3f5b25f5a/dist/ng-prettyjson.min.js#L19-L22 | train |
|
HuddleEng/PhantomXHR | phantomxhr.js | FakeEvent | function FakeEvent(type, bubbles, cancelable, target) {
this.initEvent(type, bubbles, cancelable, target);
} | javascript | function FakeEvent(type, bubbles, cancelable, target) {
this.initEvent(type, bubbles, cancelable, target);
} | [
"function",
"FakeEvent",
"(",
"type",
",",
"bubbles",
",",
"cancelable",
",",
"target",
")",
"{",
"this",
".",
"initEvent",
"(",
"type",
",",
"bubbles",
",",
"cancelable",
",",
"target",
")",
";",
"}"
] | A naive implementation for simulating upload events | [
"A",
"naive",
"implementation",
"for",
"simulating",
"upload",
"events"
] | 0584a060ca0b6370eae448eda416a66b4ffc6eb6 | https://github.com/HuddleEng/PhantomXHR/blob/0584a060ca0b6370eae448eda416a66b4ffc6eb6/phantomxhr.js#L29-L31 | train |
jonschlinkert/grunt-prettify | tasks/prettify.js | padcomments | function padcomments(str, num) {
var nl = _str.repeat('\n', (num || 1));
return str.replace(/(\s*)(<!--.+)\s*(===.+)?/g, nl + '$1$2$1$3');
} | javascript | function padcomments(str, num) {
var nl = _str.repeat('\n', (num || 1));
return str.replace(/(\s*)(<!--.+)\s*(===.+)?/g, nl + '$1$2$1$3');
} | [
"function",
"padcomments",
"(",
"str",
",",
"num",
")",
"{",
"var",
"nl",
"=",
"_str",
".",
"repeat",
"(",
"'\\n'",
",",
"(",
"num",
"||",
"1",
")",
")",
";",
"return",
"str",
".",
"replace",
"(",
"/",
"(\\s*)(<!--.+)\\s*(===.+)?",
"/",
"g",
",",
"nl",
"+",
"'$1$2$1$3'",
")",
";",
"}"
] | fix multiline, Bootstrap-style comments | [
"fix",
"multiline",
"Bootstrap",
"-",
"style",
"comments"
] | d4769c71a67a24a6e48316dfb1d657b9938b1836 | https://github.com/jonschlinkert/grunt-prettify/blob/d4769c71a67a24a6e48316dfb1d657b9938b1836/tasks/prettify.js#L113-L116 | train |
vecnatechnologies/backbone-torso | torso-bundle.js | function(obj, cache) {
cache[obj.cid] = obj;
this.listenToOnce(obj, 'before-dispose', function() {
delete cache[obj.cid];
});
} | javascript | function(obj, cache) {
cache[obj.cid] = obj;
this.listenToOnce(obj, 'before-dispose', function() {
delete cache[obj.cid];
});
} | [
"function",
"(",
"obj",
",",
"cache",
")",
"{",
"cache",
"[",
"obj",
".",
"cid",
"]",
"=",
"obj",
";",
"this",
".",
"listenToOnce",
"(",
"obj",
",",
"'before-dispose'",
",",
"function",
"(",
")",
"{",
"delete",
"cache",
"[",
"obj",
".",
"cid",
"]",
";",
"}",
")",
";",
"}"
] | Initialize the given object in the given cache.
@method __initialize
@param obj {Backbone.Events} any object that implements/extends backbone events.
@param obj.cid {String} the unique identifier for the object.
@param cache {Object} the cache to add the object to.
@private | [
"Initialize",
"the",
"given",
"object",
"in",
"the",
"given",
"cache",
"."
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L336-L341 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | hotswap | function hotswap(currentNode, newNode, ignoreElements) {
var newNodeType = newNode.nodeType,
currentNodeType = currentNode.nodeType,
swapMethod;
if(newNodeType !== currentNodeType) {
$(currentNode).replaceWith(newNode);
} else {
swapMethod = swapMethods[newNodeType] || swapMethods['default'];
swapMethod(currentNode, newNode, ignoreElements);
}
} | javascript | function hotswap(currentNode, newNode, ignoreElements) {
var newNodeType = newNode.nodeType,
currentNodeType = currentNode.nodeType,
swapMethod;
if(newNodeType !== currentNodeType) {
$(currentNode).replaceWith(newNode);
} else {
swapMethod = swapMethods[newNodeType] || swapMethods['default'];
swapMethod(currentNode, newNode, ignoreElements);
}
} | [
"function",
"hotswap",
"(",
"currentNode",
",",
"newNode",
",",
"ignoreElements",
")",
"{",
"var",
"newNodeType",
"=",
"newNode",
".",
"nodeType",
",",
"currentNodeType",
"=",
"currentNode",
".",
"nodeType",
",",
"swapMethod",
";",
"if",
"(",
"newNodeType",
"!==",
"currentNodeType",
")",
"{",
"$",
"(",
"currentNode",
")",
".",
"replaceWith",
"(",
"newNode",
")",
";",
"}",
"else",
"{",
"swapMethod",
"=",
"swapMethods",
"[",
"newNodeType",
"]",
"||",
"swapMethods",
"[",
"'default'",
"]",
";",
"swapMethod",
"(",
"currentNode",
",",
"newNode",
",",
"ignoreElements",
")",
";",
"}",
"}"
] | Changes DOM Nodes that are different, and leaves others untouched.
Algorithm:
Delegates to a particular swapMethod, depending on the Node type.
Recurses for nested Element Nodes only.
There is always room for optimizing this method.
@method hotswap
@param currentNode {Node} The DOM Node corresponding to the existing page content to update
@param newNode {Node} The detached DOM Node representing the desired DOM subtree
@param ignoreElements {Array} Array of jQuery selectors for DOM Elements to ignore during render. Can be an expensive check. | [
"Changes",
"DOM",
"Nodes",
"that",
"are",
"different",
"and",
"leaves",
"others",
"untouched",
"."
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L465-L476 | train |
vecnatechnologies/backbone-torso | torso-bundle.js | cleanupStickitData | function cleanupStickitData(node) {
var $node = $(node);
var stickitValue = $node.data('stickit-bind-val');
if (node.tagName === 'OPTION' && node.value !== undefined && stickitValue !== node.value) {
$node.removeData('stickit-bind-val');
}
} | javascript | function cleanupStickitData(node) {
var $node = $(node);
var stickitValue = $node.data('stickit-bind-val');
if (node.tagName === 'OPTION' && node.value !== undefined && stickitValue !== node.value) {
$node.removeData('stickit-bind-val');
}
} | [
"function",
"cleanupStickitData",
"(",
"node",
")",
"{",
"var",
"$node",
"=",
"$",
"(",
"node",
")",
";",
"var",
"stickitValue",
"=",
"$node",
".",
"data",
"(",
"'stickit-bind-val'",
")",
";",
"if",
"(",
"node",
".",
"tagName",
"===",
"'OPTION'",
"&&",
"node",
".",
"value",
"!==",
"undefined",
"&&",
"stickitValue",
"!==",
"node",
".",
"value",
")",
"{",
"$node",
".",
"removeData",
"(",
"'stickit-bind-val'",
")",
";",
"}",
"}"
] | Stickit will rely on the 'stickit-bind-val' jQuery data attribute to determine the value to use for a given option.
If the value DOM attribute is not the same as the stickit-bind-val, then this will clear the jquery data attribute
so that stickit will use the value DOM attribute of the option. This happens when templateRenderer merges
the attributes of the newNode into a current node of the same type when the current node has the stickit-bind-val
jQuery data attribute set.
If the node value is not set, then the stickit-bind-val might be how the view is communicating the value for stickit to use
(possibly in the case of non-string values). In this case trust the stickit-bind-val.
@param node {Node} the DoM element to test and fix the stickit data on. | [
"Stickit",
"will",
"rely",
"on",
"the",
"stickit",
"-",
"bind",
"-",
"val",
"jQuery",
"data",
"attribute",
"to",
"determine",
"the",
"value",
"to",
"use",
"for",
"a",
"given",
"option",
".",
"If",
"the",
"value",
"DOM",
"attribute",
"is",
"not",
"the",
"same",
"as",
"the",
"stickit",
"-",
"bind",
"-",
"val",
"then",
"this",
"will",
"clear",
"the",
"jquery",
"data",
"attribute",
"so",
"that",
"stickit",
"will",
"use",
"the",
"value",
"DOM",
"attribute",
"of",
"the",
"option",
".",
"This",
"happens",
"when",
"templateRenderer",
"merges",
"the",
"attributes",
"of",
"the",
"newNode",
"into",
"a",
"current",
"node",
"of",
"the",
"same",
"type",
"when",
"the",
"current",
"node",
"has",
"the",
"stickit",
"-",
"bind",
"-",
"val",
"jQuery",
"data",
"attribute",
"set",
"."
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L490-L496 | train |
vecnatechnologies/backbone-torso | torso-bundle.js | function($el, template, context, opts) {
var newDOM, newHTML,
el = $el.get(0);
opts = opts || {};
newHTML = opts.newHTML || template(context);
if (opts.force) {
$el.html(newHTML);
} else {
newDOM = this.copyTopElement(el);
$(newDOM).html(newHTML);
this.hotswapKeepCaret(el, newDOM, opts.ignoreElements);
}
} | javascript | function($el, template, context, opts) {
var newDOM, newHTML,
el = $el.get(0);
opts = opts || {};
newHTML = opts.newHTML || template(context);
if (opts.force) {
$el.html(newHTML);
} else {
newDOM = this.copyTopElement(el);
$(newDOM).html(newHTML);
this.hotswapKeepCaret(el, newDOM, opts.ignoreElements);
}
} | [
"function",
"(",
"$el",
",",
"template",
",",
"context",
",",
"opts",
")",
"{",
"var",
"newDOM",
",",
"newHTML",
",",
"el",
"=",
"$el",
".",
"get",
"(",
"0",
")",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"newHTML",
"=",
"opts",
".",
"newHTML",
"||",
"template",
"(",
"context",
")",
";",
"if",
"(",
"opts",
".",
"force",
")",
"{",
"$el",
".",
"html",
"(",
"newHTML",
")",
";",
"}",
"else",
"{",
"newDOM",
"=",
"this",
".",
"copyTopElement",
"(",
"el",
")",
";",
"$",
"(",
"newDOM",
")",
".",
"html",
"(",
"newHTML",
")",
";",
"this",
".",
"hotswapKeepCaret",
"(",
"el",
",",
"newDOM",
",",
"opts",
".",
"ignoreElements",
")",
";",
"}",
"}"
] | Performs efficient re-rendering of a template.
@method render
@param $el {jQueryObject} The Element to render into
@param template {Handlebars Template} The HBS template to apply
@param context {Object} The context object to pass to the template
@param [opts] {Object} Other options
@param [opts.force=false] {Boolean} Will forcefully do a fresh render and not a diff-render
@param [opts.newHTML] {String} If you pass in newHTML, it will not use the template or context, but use this instead.
@param [opts.ignoreElements] {Array} jQuery selectors of DOM elements to ignore during render. Can be an expensive check | [
"Performs",
"efficient",
"re",
"-",
"rendering",
"of",
"a",
"template",
"."
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L614-L627 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(currentNode, newNode, ignoreElements) {
var currentCaret, activeElement,
currentNodeContainsActiveElement = false;
try {
activeElement = document.activeElement;
} catch (error) {
activeElement = null;
}
if (activeElement && currentNode && $.contains(activeElement, currentNode)) {
currentNodeContainsActiveElement = true;
}
if (currentNodeContainsActiveElement && this.supportsSelection(activeElement)) {
currentCaret = this.getCaretPosition(activeElement);
}
this.hotswap(currentNode, newNode, ignoreElements);
if (currentNodeContainsActiveElement && this.supportsSelection(activeElement)) {
this.setCaretPosition(activeElement, currentCaret);
}
} | javascript | function(currentNode, newNode, ignoreElements) {
var currentCaret, activeElement,
currentNodeContainsActiveElement = false;
try {
activeElement = document.activeElement;
} catch (error) {
activeElement = null;
}
if (activeElement && currentNode && $.contains(activeElement, currentNode)) {
currentNodeContainsActiveElement = true;
}
if (currentNodeContainsActiveElement && this.supportsSelection(activeElement)) {
currentCaret = this.getCaretPosition(activeElement);
}
this.hotswap(currentNode, newNode, ignoreElements);
if (currentNodeContainsActiveElement && this.supportsSelection(activeElement)) {
this.setCaretPosition(activeElement, currentCaret);
}
} | [
"function",
"(",
"currentNode",
",",
"newNode",
",",
"ignoreElements",
")",
"{",
"var",
"currentCaret",
",",
"activeElement",
",",
"currentNodeContainsActiveElement",
"=",
"false",
";",
"try",
"{",
"activeElement",
"=",
"document",
".",
"activeElement",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"activeElement",
"=",
"null",
";",
"}",
"if",
"(",
"activeElement",
"&&",
"currentNode",
"&&",
"$",
".",
"contains",
"(",
"activeElement",
",",
"currentNode",
")",
")",
"{",
"currentNodeContainsActiveElement",
"=",
"true",
";",
"}",
"if",
"(",
"currentNodeContainsActiveElement",
"&&",
"this",
".",
"supportsSelection",
"(",
"activeElement",
")",
")",
"{",
"currentCaret",
"=",
"this",
".",
"getCaretPosition",
"(",
"activeElement",
")",
";",
"}",
"this",
".",
"hotswap",
"(",
"currentNode",
",",
"newNode",
",",
"ignoreElements",
")",
";",
"if",
"(",
"currentNodeContainsActiveElement",
"&&",
"this",
".",
"supportsSelection",
"(",
"activeElement",
")",
")",
"{",
"this",
".",
"setCaretPosition",
"(",
"activeElement",
",",
"currentCaret",
")",
";",
"}",
"}"
] | Call this.hotswap but also keeps the caret position the same
@param currentNode {Node} The DOM Node corresponding to the existing page content to update
@param newNode {Node} The detached DOM Node representing the desired DOM subtree
@param ignoreElements {Array} Array of jQuery selectors for DOM Elements to ignore during render. Can be an expensive check.
@method hotswapKeepCaret | [
"Call",
"this",
".",
"hotswap",
"but",
"also",
"keeps",
"the",
"caret",
"position",
"the",
"same"
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L637-L655 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(el) {
var newDOM = document.createElement(el.tagName);
_.each(el.attributes, function(attrib) {
newDOM.setAttribute(attrib.name, attrib.value);
});
return newDOM;
} | javascript | function(el) {
var newDOM = document.createElement(el.tagName);
_.each(el.attributes, function(attrib) {
newDOM.setAttribute(attrib.name, attrib.value);
});
return newDOM;
} | [
"function",
"(",
"el",
")",
"{",
"var",
"newDOM",
"=",
"document",
".",
"createElement",
"(",
"el",
".",
"tagName",
")",
";",
"_",
".",
"each",
"(",
"el",
".",
"attributes",
",",
"function",
"(",
"attrib",
")",
"{",
"newDOM",
".",
"setAttribute",
"(",
"attrib",
".",
"name",
",",
"attrib",
".",
"value",
")",
";",
"}",
")",
";",
"return",
"newDOM",
";",
"}"
] | Produces a copy of the element tag with attributes but with no contents
@param el {Element} the DOM element to be copied
@return {Element} a shallow copy of the element with no children but with attributes
@method copyTopElement | [
"Produces",
"a",
"copy",
"of",
"the",
"element",
"tag",
"with",
"attributes",
"but",
"with",
"no",
"contents"
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L666-L672 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(options) {
options = options || {};
options.idsToFetch = options.idsToFetch || this.trackedIds;
options.setOptions = options.setOptions || {remove: false};
return this.__loadWrapper(function() {
if (options.idsToFetch && options.idsToFetch.length) {
return parentInstance.fetchByIds(options);
} else {
return $.Deferred().resolve().promise();
}
});
} | javascript | function(options) {
options = options || {};
options.idsToFetch = options.idsToFetch || this.trackedIds;
options.setOptions = options.setOptions || {remove: false};
return this.__loadWrapper(function() {
if (options.idsToFetch && options.idsToFetch.length) {
return parentInstance.fetchByIds(options);
} else {
return $.Deferred().resolve().promise();
}
});
} | [
"function",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"idsToFetch",
"=",
"options",
".",
"idsToFetch",
"||",
"this",
".",
"trackedIds",
";",
"options",
".",
"setOptions",
"=",
"options",
".",
"setOptions",
"||",
"{",
"remove",
":",
"false",
"}",
";",
"return",
"this",
".",
"__loadWrapper",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"options",
".",
"idsToFetch",
"&&",
"options",
".",
"idsToFetch",
".",
"length",
")",
"{",
"return",
"parentInstance",
".",
"fetchByIds",
"(",
"options",
")",
";",
"}",
"else",
"{",
"return",
"$",
".",
"Deferred",
"(",
")",
".",
"resolve",
"(",
")",
".",
"promise",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Will force the cache to fetch just the registered ids of this collection
@method requesterMixin.fetch
@param [options] - argument options
@param [options.idsToFetch=collectionTrackedIds] {Array} - A list of request Ids, will default to current tracked ids
@param [options.setOptions] {Object} - if a set is made, then the setOptions will be passed into the set method
@return {Promise} promise that will resolve when the fetch is complete | [
"Will",
"force",
"the",
"cache",
"to",
"fetch",
"just",
"the",
"registered",
"ids",
"of",
"this",
"collection"
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L808-L819 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(ids, options) {
options = options || {};
options.idsToFetch = _.intersection(ids, this.getTrackedIds());
return this.fetch(options);
} | javascript | function(ids, options) {
options = options || {};
options.idsToFetch = _.intersection(ids, this.getTrackedIds());
return this.fetch(options);
} | [
"function",
"(",
"ids",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"idsToFetch",
"=",
"_",
".",
"intersection",
"(",
"ids",
",",
"this",
".",
"getTrackedIds",
"(",
")",
")",
";",
"return",
"this",
".",
"fetch",
"(",
"options",
")",
";",
"}"
] | Will force the cache to fetch a subset of this collection's tracked ids
@method requesterMixin.fetchByIds
@param ids {Array} array of model ids
@param [options] {Object} if given, will pass the options argument to this.fetch. Note, will not affect options.idsToFetch
@return {Promise} promise that will resolve when the fetch is complete | [
"Will",
"force",
"the",
"cache",
"to",
"fetch",
"a",
"subset",
"of",
"this",
"collection",
"s",
"tracked",
"ids"
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L828-L832 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(ids) {
this.remove(_.difference(this.trackedIds, ids));
parentInstance.registerIds(ids, ownerKey);
this.trackedIds = ids;
} | javascript | function(ids) {
this.remove(_.difference(this.trackedIds, ids));
parentInstance.registerIds(ids, ownerKey);
this.trackedIds = ids;
} | [
"function",
"(",
"ids",
")",
"{",
"this",
".",
"remove",
"(",
"_",
".",
"difference",
"(",
"this",
".",
"trackedIds",
",",
"ids",
")",
")",
";",
"parentInstance",
".",
"registerIds",
"(",
"ids",
",",
"ownerKey",
")",
";",
"this",
".",
"trackedIds",
"=",
"ids",
";",
"}"
] | Pass a list of ids to begin tracking. This will reset any previous list of ids being tracked.
Overrides the Id registration system to route via the parent collection
@method requesterMixin.trackIds
@param ids The list of ids that this collection wants to track | [
"Pass",
"a",
"list",
"of",
"ids",
"to",
"begin",
"tracking",
".",
"This",
"will",
"reset",
"any",
"previous",
"list",
"of",
"ids",
"being",
"tracked",
".",
"Overrides",
"the",
"Id",
"registration",
"system",
"to",
"route",
"via",
"the",
"parent",
"collection"
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L840-L844 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(options) {
options = options || {};
//find ids that we don't have in cache and aren't already in the process of being fetched.
var idsNotInCache = _.difference(this.getTrackedIds(), _.pluck(parentInstance.models, 'id'));
var idsWithPromises = _.pick(parentInstance.idPromises, idsNotInCache);
// Determine which ids are already being fetched and the associated promises for those ids.
options.idsToFetch = _.difference(idsNotInCache, _.uniq(_.flatten(_.keys(idsWithPromises))));
var thisFetchPromise = this.fetch(options);
// Return a promise that resolves when all ids are fetched (including pending ids).
var allPromisesToWaitFor = _.flatten(_.values(idsWithPromises));
allPromisesToWaitFor.push(thisFetchPromise);
var allUniquePromisesToWaitFor = _.uniq(allPromisesToWaitFor);
return $.when.apply($, allUniquePromisesToWaitFor)
// Make it look like the multiple promises was performed by a single request.
.then(function() {
// collects the parts of each ajax call into arrays: result = { [data1, data2, ...], [textStatus1, textStatus2, ...], [jqXHR1, jqXHR2, ...] };
var result = _.zip(arguments);
// Flatten the data so it looks like the result of a single request.
var resultData = result[0];
var flattenedResultData = _.flatten(resultData);
return flattenedResultData;
});
} | javascript | function(options) {
options = options || {};
//find ids that we don't have in cache and aren't already in the process of being fetched.
var idsNotInCache = _.difference(this.getTrackedIds(), _.pluck(parentInstance.models, 'id'));
var idsWithPromises = _.pick(parentInstance.idPromises, idsNotInCache);
// Determine which ids are already being fetched and the associated promises for those ids.
options.idsToFetch = _.difference(idsNotInCache, _.uniq(_.flatten(_.keys(idsWithPromises))));
var thisFetchPromise = this.fetch(options);
// Return a promise that resolves when all ids are fetched (including pending ids).
var allPromisesToWaitFor = _.flatten(_.values(idsWithPromises));
allPromisesToWaitFor.push(thisFetchPromise);
var allUniquePromisesToWaitFor = _.uniq(allPromisesToWaitFor);
return $.when.apply($, allUniquePromisesToWaitFor)
// Make it look like the multiple promises was performed by a single request.
.then(function() {
// collects the parts of each ajax call into arrays: result = { [data1, data2, ...], [textStatus1, textStatus2, ...], [jqXHR1, jqXHR2, ...] };
var result = _.zip(arguments);
// Flatten the data so it looks like the result of a single request.
var resultData = result[0];
var flattenedResultData = _.flatten(resultData);
return flattenedResultData;
});
} | [
"function",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"//find ids that we don't have in cache and aren't already in the process of being fetched.",
"var",
"idsNotInCache",
"=",
"_",
".",
"difference",
"(",
"this",
".",
"getTrackedIds",
"(",
")",
",",
"_",
".",
"pluck",
"(",
"parentInstance",
".",
"models",
",",
"'id'",
")",
")",
";",
"var",
"idsWithPromises",
"=",
"_",
".",
"pick",
"(",
"parentInstance",
".",
"idPromises",
",",
"idsNotInCache",
")",
";",
"// Determine which ids are already being fetched and the associated promises for those ids.",
"options",
".",
"idsToFetch",
"=",
"_",
".",
"difference",
"(",
"idsNotInCache",
",",
"_",
".",
"uniq",
"(",
"_",
".",
"flatten",
"(",
"_",
".",
"keys",
"(",
"idsWithPromises",
")",
")",
")",
")",
";",
"var",
"thisFetchPromise",
"=",
"this",
".",
"fetch",
"(",
"options",
")",
";",
"// Return a promise that resolves when all ids are fetched (including pending ids).",
"var",
"allPromisesToWaitFor",
"=",
"_",
".",
"flatten",
"(",
"_",
".",
"values",
"(",
"idsWithPromises",
")",
")",
";",
"allPromisesToWaitFor",
".",
"push",
"(",
"thisFetchPromise",
")",
";",
"var",
"allUniquePromisesToWaitFor",
"=",
"_",
".",
"uniq",
"(",
"allPromisesToWaitFor",
")",
";",
"return",
"$",
".",
"when",
".",
"apply",
"(",
"$",
",",
"allUniquePromisesToWaitFor",
")",
"// Make it look like the multiple promises was performed by a single request.",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// collects the parts of each ajax call into arrays: result = { [data1, data2, ...], [textStatus1, textStatus2, ...], [jqXHR1, jqXHR2, ...] };",
"var",
"result",
"=",
"_",
".",
"zip",
"(",
"arguments",
")",
";",
"// Flatten the data so it looks like the result of a single request.",
"var",
"resultData",
"=",
"result",
"[",
"0",
"]",
";",
"var",
"flattenedResultData",
"=",
"_",
".",
"flatten",
"(",
"resultData",
")",
";",
"return",
"flattenedResultData",
";",
"}",
")",
";",
"}"
] | Will force the cache to fetch any of this collection's tracked models that are not in the cache
while not fetching models that are already in the cache. Useful when you want the effeciency of
pulling models from the cache and don't need all the models to be up-to-date.
If the ids being fetched are already being fetched by the cache, then they will not be re-fetched.
The resulting promise is resolved when ALL items in the process of being fetched have completed.
The promise will resolve to a unified data property that is a combination of the completion of all of the fetches.
@method requesterMixin.pull
@param [options] {Object} if given, will pass the options argument to this.fetch. Note, will not affect options.idsToFetch
@return {Promise} promise that will resolve when the fetch is complete with all of the data that was fetched from the server.
Will only resolve once all ids have attempted to be fetched from the server. | [
"Will",
"force",
"the",
"cache",
"to",
"fetch",
"any",
"of",
"this",
"collection",
"s",
"tracked",
"models",
"that",
"are",
"not",
"in",
"the",
"cache",
"while",
"not",
"fetching",
"models",
"that",
"are",
"already",
"in",
"the",
"cache",
".",
"Useful",
"when",
"you",
"want",
"the",
"effeciency",
"of",
"pulling",
"models",
"from",
"the",
"cache",
"and",
"don",
"t",
"need",
"all",
"the",
"models",
"to",
"be",
"up",
"-",
"to",
"-",
"date",
"."
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L892-L917 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(modelIdentifier) {
var model = this.get(modelIdentifier);
parentClass.remove.apply(this, arguments);
if (model) {
var trackedIdsWithoutModel = this.getTrackedIds();
trackedIdsWithoutModel = _.without(trackedIdsWithoutModel, model.id);
this.trackIds(trackedIdsWithoutModel);
}
} | javascript | function(modelIdentifier) {
var model = this.get(modelIdentifier);
parentClass.remove.apply(this, arguments);
if (model) {
var trackedIdsWithoutModel = this.getTrackedIds();
trackedIdsWithoutModel = _.without(trackedIdsWithoutModel, model.id);
this.trackIds(trackedIdsWithoutModel);
}
} | [
"function",
"(",
"modelIdentifier",
")",
"{",
"var",
"model",
"=",
"this",
".",
"get",
"(",
"modelIdentifier",
")",
";",
"parentClass",
".",
"remove",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"if",
"(",
"model",
")",
"{",
"var",
"trackedIdsWithoutModel",
"=",
"this",
".",
"getTrackedIds",
"(",
")",
";",
"trackedIdsWithoutModel",
"=",
"_",
".",
"without",
"(",
"trackedIdsWithoutModel",
",",
"model",
".",
"id",
")",
";",
"this",
".",
"trackIds",
"(",
"trackedIdsWithoutModel",
")",
";",
"}",
"}"
] | In addition to removing the model from the collection also remove it from the list of tracked ids.
@param modelIdentifier {*} same duck-typing as Backbone.Collection.get():
by id, cid, model object with id or cid properties,
or an attributes object that is transformed through modelId | [
"In",
"addition",
"to",
"removing",
"the",
"model",
"from",
"the",
"collection",
"also",
"remove",
"it",
"from",
"the",
"list",
"of",
"tracked",
"ids",
"."
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L944-L952 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(args) {
base.call(this, args);
this.loadedOnceDeferred = new $.Deferred();
this.loadedOnce = false;
this.loadingCount = 0;
// Loading is a convenience flag that is the equivalent of loadingCount > 0
this.loading = false;
} | javascript | function(args) {
base.call(this, args);
this.loadedOnceDeferred = new $.Deferred();
this.loadedOnce = false;
this.loadingCount = 0;
// Loading is a convenience flag that is the equivalent of loadingCount > 0
this.loading = false;
} | [
"function",
"(",
"args",
")",
"{",
"base",
".",
"call",
"(",
"this",
",",
"args",
")",
";",
"this",
".",
"loadedOnceDeferred",
"=",
"new",
"$",
".",
"Deferred",
"(",
")",
";",
"this",
".",
"loadedOnce",
"=",
"false",
";",
"this",
".",
"loadingCount",
"=",
"0",
";",
"// Loading is a convenience flag that is the equivalent of loadingCount > 0",
"this",
".",
"loading",
"=",
"false",
";",
"}"
] | Adds the loading mixin
@method constructor
@param args {Object} the arguments to the base constructor method | [
"Adds",
"the",
"loading",
"mixin"
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L1359-L1366 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(fetchMethod, options) {
var object = this;
this.loadingCount++;
this.loading = true;
this.trigger('load-begin');
return $.when(fetchMethod.call(object, options)).always(function() {
if (!object.loadedOnce) {
object.loadedOnce = true;
object.loadedOnceDeferred.resolve();
}
object.loadingCount--;
if (object.loadingCount <= 0) {
object.loadingCount = 0; // prevent going negative.
object.loading = false;
}
}).done(function(data, textStatus, jqXHR) {
object.trigger('load-complete', {success: true, data: data, textStatus: textStatus, jqXHR: jqXHR});
}).fail(function(jqXHR, textStatus, errorThrown) {
object.trigger('load-complete', {success: false, jqXHR: jqXHR, textStatus: textStatus, errorThrown: errorThrown});
});
} | javascript | function(fetchMethod, options) {
var object = this;
this.loadingCount++;
this.loading = true;
this.trigger('load-begin');
return $.when(fetchMethod.call(object, options)).always(function() {
if (!object.loadedOnce) {
object.loadedOnce = true;
object.loadedOnceDeferred.resolve();
}
object.loadingCount--;
if (object.loadingCount <= 0) {
object.loadingCount = 0; // prevent going negative.
object.loading = false;
}
}).done(function(data, textStatus, jqXHR) {
object.trigger('load-complete', {success: true, data: data, textStatus: textStatus, jqXHR: jqXHR});
}).fail(function(jqXHR, textStatus, errorThrown) {
object.trigger('load-complete', {success: false, jqXHR: jqXHR, textStatus: textStatus, errorThrown: errorThrown});
});
} | [
"function",
"(",
"fetchMethod",
",",
"options",
")",
"{",
"var",
"object",
"=",
"this",
";",
"this",
".",
"loadingCount",
"++",
";",
"this",
".",
"loading",
"=",
"true",
";",
"this",
".",
"trigger",
"(",
"'load-begin'",
")",
";",
"return",
"$",
".",
"when",
"(",
"fetchMethod",
".",
"call",
"(",
"object",
",",
"options",
")",
")",
".",
"always",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"object",
".",
"loadedOnce",
")",
"{",
"object",
".",
"loadedOnce",
"=",
"true",
";",
"object",
".",
"loadedOnceDeferred",
".",
"resolve",
"(",
")",
";",
"}",
"object",
".",
"loadingCount",
"--",
";",
"if",
"(",
"object",
".",
"loadingCount",
"<=",
"0",
")",
"{",
"object",
".",
"loadingCount",
"=",
"0",
";",
"// prevent going negative.",
"object",
".",
"loading",
"=",
"false",
";",
"}",
"}",
")",
".",
"done",
"(",
"function",
"(",
"data",
",",
"textStatus",
",",
"jqXHR",
")",
"{",
"object",
".",
"trigger",
"(",
"'load-complete'",
",",
"{",
"success",
":",
"true",
",",
"data",
":",
"data",
",",
"textStatus",
":",
"textStatus",
",",
"jqXHR",
":",
"jqXHR",
"}",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"jqXHR",
",",
"textStatus",
",",
"errorThrown",
")",
"{",
"object",
".",
"trigger",
"(",
"'load-complete'",
",",
"{",
"success",
":",
"false",
",",
"jqXHR",
":",
"jqXHR",
",",
"textStatus",
":",
"textStatus",
",",
"errorThrown",
":",
"errorThrown",
"}",
")",
";",
"}",
")",
";",
"}"
] | Base load function that will trigger a "load-begin" and a "load-complete" as
the fetch happens. Use this method to wrap any method that returns a promise in loading events
@method __loadWrapper
@param fetchMethod {Function} - the method to invoke a fetch
@param options {Object} - the object to hold the options needed by the fetchMethod
@return {Promise} a promise when the fetch method has completed and the events have been triggered | [
"Base",
"load",
"function",
"that",
"will",
"trigger",
"a",
"load",
"-",
"begin",
"and",
"a",
"load",
"-",
"complete",
"as",
"the",
"fetch",
"happens",
".",
"Use",
"this",
"method",
"to",
"wrap",
"any",
"method",
"that",
"returns",
"a",
"promise",
"in",
"loading",
"events"
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L1410-L1430 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function(viewPrepare) {
var viewContext = viewPrepare() || {};
var behaviorContext = _.omit(this.toJSON(), 'view');
_.extend(behaviorContext, this.prepare());
viewContext[this.alias] = behaviorContext;
return viewContext;
} | javascript | function(viewPrepare) {
var viewContext = viewPrepare() || {};
var behaviorContext = _.omit(this.toJSON(), 'view');
_.extend(behaviorContext, this.prepare());
viewContext[this.alias] = behaviorContext;
return viewContext;
} | [
"function",
"(",
"viewPrepare",
")",
"{",
"var",
"viewContext",
"=",
"viewPrepare",
"(",
")",
"||",
"{",
"}",
";",
"var",
"behaviorContext",
"=",
"_",
".",
"omit",
"(",
"this",
".",
"toJSON",
"(",
")",
",",
"'view'",
")",
";",
"_",
".",
"extend",
"(",
"behaviorContext",
",",
"this",
".",
"prepare",
"(",
")",
")",
";",
"viewContext",
"[",
"this",
".",
"alias",
"]",
"=",
"behaviorContext",
";",
"return",
"viewContext",
";",
"}"
] | Wraps the view's prepare such that it returns the combination of the view and behavior's prepare results.
@method __viewPrepareWrapper
@private
@param viewPrepare {Function} the prepare method from the view.
@return {Object} the combined view and behavior prepare() results.
{
<behavior alias>: behavior.prepare(),
... // view prepare properties.
} | [
"Wraps",
"the",
"view",
"s",
"prepare",
"such",
"that",
"it",
"returns",
"the",
"combination",
"of",
"the",
"view",
"and",
"behavior",
"s",
"prepare",
"results",
"."
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L1904-L1910 | train |
|
vecnatechnologies/backbone-torso | torso-bundle.js | function() {
this.listenTo(this.view, 'initialize:complete', this.__augmentViewPrepare);
this.listenTo(this.view, 'before-dispose-callback', this.__dispose);
_.each(eventMap, function(callback, event) {
this.listenTo(this.view, event, this[callback]);
}, this);
} | javascript | function() {
this.listenTo(this.view, 'initialize:complete', this.__augmentViewPrepare);
this.listenTo(this.view, 'before-dispose-callback', this.__dispose);
_.each(eventMap, function(callback, event) {
this.listenTo(this.view, event, this[callback]);
}, this);
} | [
"function",
"(",
")",
"{",
"this",
".",
"listenTo",
"(",
"this",
".",
"view",
",",
"'initialize:complete'",
",",
"this",
".",
"__augmentViewPrepare",
")",
";",
"this",
".",
"listenTo",
"(",
"this",
".",
"view",
",",
"'before-dispose-callback'",
",",
"this",
".",
"__dispose",
")",
";",
"_",
".",
"each",
"(",
"eventMap",
",",
"function",
"(",
"callback",
",",
"event",
")",
"{",
"this",
".",
"listenTo",
"(",
"this",
".",
"view",
",",
"event",
",",
"this",
"[",
"callback",
"]",
")",
";",
"}",
",",
"this",
")",
";",
"}"
] | Registers defined lifecycle methods to be called at appropriate time in view's lifecycle
@method __bindLifecycleMethods
@private | [
"Registers",
"defined",
"lifecycle",
"methods",
"to",
"be",
"called",
"at",
"appropriate",
"time",
"in",
"view",
"s",
"lifecycle"
] | 5afd50da74bd46517dca75d23c10fea594730be2 | https://github.com/vecnatechnologies/backbone-torso/blob/5afd50da74bd46517dca75d23c10fea594730be2/torso-bundle.js#L1918-L1924 | train |