_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q46900
|
todoBlurred
|
train
|
function todoBlurred(todo, event) {
var trimmedText = event.target.value.trim();
if (!trimmedText) {
db.remove(todo);
} else {
todo.title = trimmedText;
db.put(todo);
}
}
|
javascript
|
{
"resource": ""
}
|
q46901
|
sync
|
train
|
function sync() {
syncDom.setAttribute('data-sync-state', 'syncing');
var opts = {continuous: true, complete: syncError};
db.replicate.to(remoteCouch, opts);
db.replicate.from(remoteCouch, opts);
}
|
javascript
|
{
"resource": ""
}
|
q46902
|
todoDblClicked
|
train
|
function todoDblClicked(todo) {
var div = document.getElementById('li_' + todo._id);
var inputEditTodo = document.getElementById('input_' + todo._id);
div.className = 'editing';
inputEditTodo.focus();
}
|
javascript
|
{
"resource": ""
}
|
q46903
|
createTodoListItem
|
train
|
function createTodoListItem(todo) {
var checkbox = document.createElement('input');
checkbox.className = 'toggle';
checkbox.type = 'checkbox';
checkbox.addEventListener('change', checkboxChanged.bind(this, todo));
var label = document.createElement('label');
label.appendChild( document.createTextNode(todo.title));
label.addEventListener('dblclick', todoDblClicked.bind(this, todo));
var deleteLink = document.createElement('button');
deleteLink.className = 'destroy';
deleteLink.addEventListener( 'click', deleteButtonPressed.bind(this, todo));
var divDisplay = document.createElement('div');
divDisplay.className = 'view';
divDisplay.appendChild(checkbox);
divDisplay.appendChild(label);
divDisplay.appendChild(deleteLink);
var inputEditTodo = document.createElement('input');
inputEditTodo.id = 'input_' + todo._id;
inputEditTodo.className = 'edit';
inputEditTodo.value = todo.title;
inputEditTodo.addEventListener('keypress', todoKeyPressed.bind(this, todo));
inputEditTodo.addEventListener('blur', todoBlurred.bind(this, todo));
var li = document.createElement('li');
li.id = 'li_' + todo._id;
li.appendChild(divDisplay);
li.appendChild(inputEditTodo);
if (todo.completed) {
li.className += 'complete';
checkbox.checked = true;
}
return li;
}
|
javascript
|
{
"resource": ""
}
|
q46904
|
getPublicExportedNames
|
train
|
function getPublicExportedNames(entryModule) {
const fn = function() {};
const isStaticOrProtoName = (x) => (
!(x in fn) &&
(x !== `default`) &&
(x !== `undefined`) &&
(x !== `__esModule`) &&
(x !== `constructor`)
);
return Object
.getOwnPropertyNames(entryModule)
.filter((name) => name !== 'default')
.filter((name) => (
typeof entryModule[name] === `object` ||
typeof entryModule[name] === `function`
))
.map((name) => [name, entryModule[name]])
.reduce((reserved, [name, value]) => {
const staticNames = value &&
typeof value === 'object' ? Object.getOwnPropertyNames(value).filter(isStaticOrProtoName) :
typeof value === 'function' ? Object.getOwnPropertyNames(value).filter(isStaticOrProtoName) : [];
const instanceNames = (typeof value === `function` && Object.getOwnPropertyNames(value.prototype || {}) || []).filter(isStaticOrProtoName);
return [...reserved, { exportName: name, staticNames, instanceNames }];
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q46905
|
freeze
|
train
|
function freeze(object) {
if (process.env.NODE_ENV === 'production') {
return object
}
if (process.env.UPDEEP_MODE === 'dangerously_never_freeze') {
return object
}
if (needsFreezing(object)) {
recur(object)
}
return object
}
|
javascript
|
{
"resource": ""
}
|
q46906
|
update
|
train
|
function update(updates, object, ...args) {
if (typeof updates === 'function') {
return updates(object, ...args)
}
if (!isPlainObject(updates)) {
return updates
}
const defaultedObject =
typeof object === 'undefined' || object === null ? {} : object
const resolvedUpdates = resolveUpdates(updates, defaultedObject)
if (isEmpty(resolvedUpdates)) {
return defaultedObject
}
if (Array.isArray(defaultedObject)) {
return updateArray(resolvedUpdates, defaultedObject).filter(
value => value !== innerOmitted
)
}
return _omitBy(
{ ...defaultedObject, ...resolvedUpdates },
value => value === innerOmitted
)
}
|
javascript
|
{
"resource": ""
}
|
q46907
|
train
|
function(k) {
if (typeof k !== "string"){ k = _.stringify(k); }
return this._ns ? this._ns + k : k;
}
|
javascript
|
{
"resource": ""
}
|
|
q46908
|
render_with_layout
|
train
|
function render_with_layout(template, locals, cb) {
render_file(locals, function(err, str) {
if (err) {
return cb(err);
}
locals.body = str;
var res = template(locals, handlebarsOpts);
self.async.done(function(values) {
Object.keys(values).forEach(function(id) {
res = res.replace(id, values[id]);
});
cb(null, res);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q46909
|
configureCodeCoverage
|
train
|
function configureCodeCoverage (config) {
if (process.argv.indexOf("--coverage") === -1) {
console.warn("Code-coverage is not enabled");
return;
}
config.reporters.push("coverage");
config.coverageReporter = {
reporters: [
{ type: "text-summary" },
{ type: "lcov" }
]
};
config.files = config.files.map(function (file) {
if (typeof file === "string") {
file = file.replace(/^dist\/(.*)\.min\.js$/, "dist/$1.coverage.js");
}
return file;
});
}
|
javascript
|
{
"resource": ""
}
|
q46910
|
form
|
train
|
function form () {
form.form = $("#swagger-parser-form");
form.allow = {
label: form.form.find("#allow-label"),
menu: form.form.find("#allow-menu"),
json: form.form.find("input[name=allow-json]"),
yaml: form.form.find("input[name=allow-yaml]"),
text: form.form.find("input[name=allow-text]"),
empty: form.form.find("input[name=allow-empty]"),
unknown: form.form.find("input[name=allow-unknown]")
};
form.refs = {
label: form.form.find("#refs-label"),
menu: form.form.find("#refs-menu"),
external: form.form.find("input[name=refs-external]"),
circular: form.form.find("input[name=refs-circular]")
};
form.validate = {
label: form.form.find("#validate-label"),
menu: form.form.find("#validate-menu"),
schema: form.form.find("input[name=validate-schema]"),
spec: form.form.find("input[name=validate-spec]")
};
form.tabs = {
url: form.form.find("#url-tab"),
text: form.form.find("#text-tab")
};
form.method = {
button: form.form.find("button[name=method]"),
menu: form.form.find("#method-menu")
};
form.samples = {
url: {
container: form.form.find("#url-sample"),
link: form.form.find("#url-sample-link"),
},
text: {
container: form.form.find("#text-sample"),
link: form.form.find("#text-sample-link"),
}
};
form.url = form.form.find("input[name=url]");
form.textBox = null; // This is set in editors.js
form.bookmark = form.form.find("#bookmark");
}
|
javascript
|
{
"resource": ""
}
|
q46911
|
samples
|
train
|
function samples () {
form.samples.url.link.on("click", function (event) {
event.preventDefault();
form.url.val(samples.url);
});
form.samples.text.link.on("click", function (event) {
event.preventDefault();
form.textBox.setValue(samples.text, -1);
form.samples.text.container.hide();
form.textBox.focus();
});
form.textBox.on("input", function () {
if (form.textBox.session.getValue().length === 0) {
form.samples.text.container.show();
}
else {
form.samples.text.container.hide();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46912
|
dropdowns
|
train
|
function dropdowns () {
// Set the initial method name (in case it was set by the querystring module)
setSelectedMethod(form.method.button.val());
// Update each dropdown's label when its value(s) change
onChange(form.allow.menu, setAllowLabel);
onChange(form.refs.menu, setRefsLabel);
onChange(form.validate.menu, setValidateLabel);
// Track option changes
trackCheckbox(form.allow.json);
trackCheckbox(form.allow.yaml);
trackCheckbox(form.allow.text);
trackCheckbox(form.allow.empty);
trackCheckbox(form.allow.unknown);
trackCheckbox(form.refs.external);
trackCheckbox(form.refs.circular);
trackCheckbox(form.validate.schema);
trackCheckbox(form.validate.spec);
// Change the button text whenever a new method is selected
form.method.menu.find("a").on("click", function (event) {
form.method.menu.dropdown("toggle");
event.stopPropagation();
var methodName = $(this).data("value");
setSelectedMethod(methodName);
trackButtonLabel(methodName);
});
}
|
javascript
|
{
"resource": ""
}
|
q46913
|
setAllowLabel
|
train
|
function setAllowLabel () {
var values = getCheckedAndUnchecked(
form.allow.json, form.allow.yaml, form.allow.text, form.allow.empty, form.allow.unknown);
switch (values.checked.length) {
case 0:
form.allow.label.text("No file types allowed");
break;
case 1:
form.allow.label.text("Only allow " + values.checked[0] + " files");
break;
case 2:
form.allow.label.text("Only allow " + values.checked[0] + " and " + values.checked[1]);
break;
case 3:
form.allow.label.text("Don't allow " + values.unchecked[0] + " or " + values.unchecked[1]);
break;
case 4:
form.allow.label.text("Don't allow " + values.unchecked[0] + " files");
break;
case 5:
form.allow.label.text("Allow all file types");
}
}
|
javascript
|
{
"resource": ""
}
|
q46914
|
setRefsLabel
|
train
|
function setRefsLabel () {
var values = getCheckedAndUnchecked(form.refs.external, form.refs.circular);
switch (values.checked.length) {
case 0:
form.refs.label.text("Only follow internal $refs");
break;
case 1:
form.refs.label.text("Don't follow " + values.unchecked[0] + " $refs");
break;
case 2:
form.refs.label.text("Follow all $refs");
}
}
|
javascript
|
{
"resource": ""
}
|
q46915
|
setValidateLabel
|
train
|
function setValidateLabel () {
var values = getCheckedAndUnchecked(form.validate.schema, form.validate.spec);
switch (values.checked.length) {
case 0:
form.validate.label.text("Don't validate anything");
break;
case 1:
form.validate.label.text("Don't validate Swagger " + values.unchecked[0]);
break;
case 2:
form.validate.label.text("Validate everything");
}
}
|
javascript
|
{
"resource": ""
}
|
q46916
|
setSelectedMethod
|
train
|
function setSelectedMethod (methodName) {
form.method.button.val(methodName.toLowerCase());
methodName = methodName[0].toUpperCase() + methodName.substr(1);
form.method.button.text(methodName + " it!");
form.tabs.url.text(methodName + " a URL");
form.tabs.text.text(methodName + " Text");
}
|
javascript
|
{
"resource": ""
}
|
q46917
|
trackCheckbox
|
train
|
function trackCheckbox (checkbox) {
checkbox.on("change", function () {
var value = checkbox.is(":checked") ? 1 : 0;
analytics.trackEvent("options", "changed", checkbox.attr("name"), value);
});
}
|
javascript
|
{
"resource": ""
}
|
q46918
|
getCheckedAndUnchecked
|
train
|
function getCheckedAndUnchecked (checkboxes) {
var checked = [], unchecked = [];
for (var i = 0; i < arguments.length; i++) {
var checkbox = arguments[i];
if (checkbox.is(":checked")) {
checked.push(checkbox.data("value"));
}
else {
unchecked.push(checkbox.data("value"));
}
}
return { checked: checked, unchecked: unchecked };
}
|
javascript
|
{
"resource": ""
}
|
q46919
|
setFormFields
|
train
|
function setFormFields () {
var query = qs.parse(window.location.search.substr(1));
setCheckbox(form.allow.json, query["allow-json"]);
setCheckbox(form.allow.yaml, query["allow-yaml"]);
setCheckbox(form.allow.text, query["allow-text"]);
setCheckbox(form.allow.empty, query["allow-empty"]);
setCheckbox(form.allow.unknown, query["allow-unknown"]);
setCheckbox(form.refs.external, query["refs-external"]);
setCheckbox(form.refs.circular, query["refs-circular"]);
setCheckbox(form.validate.schema, query["validate-schema"]);
setCheckbox(form.validate.spec, query["validate-spec"]);
// If a custom URL is specified, then show the "Your API" tab
if (query.url) {
form.url.val(query.url);
}
// If a method is specified, then change the "Validate!" button
if (query.method) {
query.method = query.method.toLowerCase();
if (["parse", "resolve", "bundle", "dereference", "validate"].indexOf(query.method) !== -1) {
form.method.button.val(query.method);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46920
|
setCheckbox
|
train
|
function setCheckbox (input, value) {
if (!value || value === "true" || value === "on") {
value = "yes";
}
input.val([value]);
}
|
javascript
|
{
"resource": ""
}
|
q46921
|
setBookmarkURL
|
train
|
function setBookmarkURL () {
var query = {};
var options = form.getOptions();
options.parse.json || (query["allow-json"] = "no");
options.parse.yaml || (query["allow-yaml"] = "no");
options.parse.text || (query["allow-text"] = "no");
options.parse.json.allowEmpty || (query["allow-empty"] = "no");
options.parse.binary || (query["allow-unknown"] = "no");
options.resolve.external || (query["refs-external"] = "no");
options.dereference.circular || (query["refs-circular"] = "no");
options.validate.schema || (query["validate-schema"] = "no");
options.validate.spec || (query["validate-spec"] = "no");
var method = form.method.button.val();
method === "validate" || (query.method = method);
var url = form.url.val();
url === "" || (query.url = url);
var bookmark = "?" + qs.stringify(query);
form.bookmark.attr("href", bookmark);
}
|
javascript
|
{
"resource": ""
}
|
q46922
|
editors
|
train
|
function editors () {
editors.textBox = form.textBox = ace.edit("text-box");
form.textBox.setTheme(ACE_THEME);
var session = form.textBox.getSession();
session.setMode("ace/mode/yaml");
session.setTabSize(2);
editors.results = $("#results");
editors.tabs = editors.results.find(".nav-tabs");
editors.panes = editors.results.find(".tab-content");
}
|
javascript
|
{
"resource": ""
}
|
q46923
|
getShortTitle
|
train
|
function getShortTitle (title) {
// Get just the file name
var lastSlash = title.lastIndexOf("/");
if (lastSlash !== -1) {
title = title.substr(lastSlash + 1);
}
if (title.length > 15) {
// It's still too long, so, just return the first 10 characters
title = title.substr(0, 10) + "...";
}
return title;
}
|
javascript
|
{
"resource": ""
}
|
q46924
|
showResults
|
train
|
function showResults () {
var results = editors.results;
setTimeout(function () {
results[0].scrollIntoView();
results.addClass("animated")
.one("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function () {
// Remove the "animated" class when the animation ends,
// so we can replay the animation again next time
results.removeClass("animated");
});
});
}
|
javascript
|
{
"resource": ""
}
|
q46925
|
toText
|
train
|
function toText (obj) {
if (obj instanceof Error) {
return {
isJSON: false,
text: obj.message + "\n\n" + obj.stack
};
}
else {
try {
return {
isJSON: true,
text: JSON.stringify(obj, null, 2)
};
}
catch (e) {
return {
isJSON: false,
text: "This API is valid, but it cannot be shown because it contains circular references\n\n" + e.stack
};
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46926
|
parser
|
train
|
function parser () {
// When the form is submitted, parse the Swagger API
form.form.on("submit", function (event) {
event.preventDefault();
parseSwagger();
});
// When the "x" button is clicked, discard the results
$("#clear").on("click", function () {
swaggerParser = null;
editors.clearResults();
analytics.trackEvent("results", "clear");
});
}
|
javascript
|
{
"resource": ""
}
|
q46927
|
parseSwagger
|
train
|
function parseSwagger () {
try {
// Clear any previous results
editors.clearResults();
// Get all the parameters
swaggerParser = swaggerParser || new SwaggerParser();
var options = form.getOptions();
var method = form.method.button.val();
var api = form.getAPI();
// Call Swagger Parser
swaggerParser[method](api, options)
.then(function () {
// Show the results
var results = swaggerParser.$refs.values();
Object.keys(results).forEach(function (key) {
editors.showResult(key, results[key]);
});
})
.catch(function (err) {
editors.showError(ono(err));
analytics.trackError(err);
});
// Track the operation
counters[method]++;
analytics.trackEvent("button", "click", method, counters[method]);
}
catch (err) {
editors.showError(ono(err));
analytics.trackError(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q46928
|
validateSpec
|
train
|
function validateSpec (api) {
if (api.openapi) {
// We don't (yet) support validating against the OpenAPI spec
return;
}
var paths = Object.keys(api.paths || {});
var operationIds = [];
paths.forEach(function (pathName) {
var path = api.paths[pathName];
var pathId = "/paths" + pathName;
if (path && pathName.indexOf("/") === 0) {
validatePath(api, path, pathId, operationIds);
}
});
var definitions = Object.keys(api.definitions || {});
definitions.forEach(function (definitionName) {
var definition = api.definitions[definitionName];
var definitionId = "/definitions/" + definitionName;
validateRequiredPropertiesExist(definition, definitionId);
});
}
|
javascript
|
{
"resource": ""
}
|
q46929
|
validatePath
|
train
|
function validatePath (api, path, pathId, operationIds) {
swaggerMethods.forEach(function (operationName) {
var operation = path[operationName];
var operationId = pathId + "/" + operationName;
if (operation) {
var declaredOperationId = operation.operationId;
if (declaredOperationId) {
if (operationIds.indexOf(declaredOperationId) === -1) {
operationIds.push(declaredOperationId);
}
else {
throw ono.syntax("Validation failed. Duplicate operation id '%s'", declaredOperationId);
}
}
validateParameters(api, path, pathId, operation, operationId);
var responses = Object.keys(operation.responses || {});
responses.forEach(function (responseName) {
var response = operation.responses[responseName];
var responseId = operationId + "/responses/" + responseName;
validateResponse(responseName, (response || {}), responseId);
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46930
|
validateParameters
|
train
|
function validateParameters (api, path, pathId, operation, operationId) {
var pathParams = path.parameters || [];
var operationParams = operation.parameters || [];
// Check for duplicate path parameters
try {
checkForDuplicates(pathParams);
}
catch (e) {
throw ono.syntax(e, "Validation failed. %s has duplicate parameters", pathId);
}
// Check for duplicate operation parameters
try {
checkForDuplicates(operationParams);
}
catch (e) {
throw ono.syntax(e, "Validation failed. %s has duplicate parameters", operationId);
}
// Combine the path and operation parameters,
// with the operation params taking precedence over the path params
var params = pathParams.reduce(function (combinedParams, value) {
var duplicate = combinedParams.some(function (param) {
return param.in === value.in && param.name === value.name;
});
if (!duplicate) {
combinedParams.push(value);
}
return combinedParams;
}, operationParams.slice());
validateBodyParameters(params, operationId);
validatePathParameters(params, pathId, operationId);
validateParameterTypes(params, api, operation, operationId);
}
|
javascript
|
{
"resource": ""
}
|
q46931
|
validateBodyParameters
|
train
|
function validateBodyParameters (params, operationId) {
var bodyParams = params.filter(function (param) { return param.in === "body"; });
var formParams = params.filter(function (param) { return param.in === "formData"; });
// There can only be one "body" parameter
if (bodyParams.length > 1) {
throw ono.syntax(
"Validation failed. %s has %d body parameters. Only one is allowed.",
operationId, bodyParams.length
);
}
else if (bodyParams.length > 0 && formParams.length > 0) {
// "body" params and "formData" params are mutually exclusive
throw ono.syntax(
"Validation failed. %s has body parameters and formData parameters. Only one or the other is allowed.",
operationId
);
}
}
|
javascript
|
{
"resource": ""
}
|
q46932
|
validatePathParameters
|
train
|
function validatePathParameters (params, pathId, operationId) {
// Find all {placeholders} in the path string
var placeholders = pathId.match(util.swaggerParamRegExp) || [];
// Check for duplicates
for (var i = 0; i < placeholders.length; i++) {
for (var j = i + 1; j < placeholders.length; j++) {
if (placeholders[i] === placeholders[j]) {
throw ono.syntax(
"Validation failed. %s has multiple path placeholders named %s", operationId, placeholders[i]);
}
}
}
params
.filter(function (param) { return param.in === "path"; })
.forEach(function (param) {
if (param.required !== true) {
throw ono.syntax(
'Validation failed. Path parameters cannot be optional. Set required=true for the "%s" parameter at %s',
param.name,
operationId
);
}
var match = placeholders.indexOf("{" + param.name + "}");
if (match === -1) {
throw ono.syntax(
'Validation failed. %s has a path parameter named "%s", ' +
"but there is no corresponding {%s} in the path string",
operationId,
param.name,
param.name
);
}
placeholders.splice(match, 1);
});
if (placeholders.length > 0) {
throw ono.syntax("Validation failed. %s is missing path parameter(s) for %s", operationId, placeholders);
}
}
|
javascript
|
{
"resource": ""
}
|
q46933
|
validateParameterTypes
|
train
|
function validateParameterTypes (params, api, operation, operationId) {
params.forEach(function (param) {
var parameterId = operationId + "/parameters/" + param.name;
var schema, validTypes;
switch (param.in) {
case "body":
schema = param.schema;
validTypes = schemaTypes;
break;
case "formData":
schema = param;
validTypes = primitiveTypes.concat("file");
break;
default:
schema = param;
validTypes = primitiveTypes;
}
validateSchema(schema, parameterId, validTypes);
validateRequiredPropertiesExist(schema, parameterId);
if (schema.type === "file") {
// "file" params must consume at least one of these MIME types
var formData = /multipart\/(.*\+)?form-data/;
var urlEncoded = /application\/(.*\+)?x-www-form-urlencoded/;
var consumes = operation.consumes || api.consumes || [];
var hasValidMimeType = consumes.some(function (consume) {
return formData.test(consume) || urlEncoded.test(consume);
});
if (!hasValidMimeType) {
throw ono.syntax(
"Validation failed. %s has a file parameter, so it must consume multipart/form-data " +
"or application/x-www-form-urlencoded",
operationId
);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46934
|
checkForDuplicates
|
train
|
function checkForDuplicates (params) {
for (var i = 0; i < params.length - 1; i++) {
var outer = params[i];
for (var j = i + 1; j < params.length; j++) {
var inner = params[j];
if (outer.name === inner.name && outer.in === inner.in) {
throw ono.syntax('Validation failed. Found multiple %s parameters named "%s"', outer.in, outer.name);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46935
|
validateResponse
|
train
|
function validateResponse (code, response, responseId) {
if (code !== "default" && (code < 100 || code > 599)) {
throw ono.syntax("Validation failed. %s has an invalid response code (%s)", responseId, code);
}
var headers = Object.keys(response.headers || {});
headers.forEach(function (headerName) {
var header = response.headers[headerName];
var headerId = responseId + "/headers/" + headerName;
validateSchema(header, headerId, primitiveTypes);
});
if (response.schema) {
var validTypes = schemaTypes.concat("file");
if (validTypes.indexOf(response.schema.type) === -1) {
throw ono.syntax(
"Validation failed. %s has an invalid response schema type (%s)", responseId, response.schema.type);
}
else {
validateSchema(response.schema, responseId + "/schema", validTypes);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q46936
|
validateSchema
|
train
|
function validateSchema (schema, schemaId, validTypes) {
if (validTypes.indexOf(schema.type) === -1) {
throw ono.syntax(
"Validation failed. %s has an invalid type (%s)", schemaId, schema.type);
}
if (schema.type === "array" && !schema.items) {
throw ono.syntax('Validation failed. %s is an array, so it must include an "items" schema', schemaId);
}
}
|
javascript
|
{
"resource": ""
}
|
q46937
|
validateRequiredPropertiesExist
|
train
|
function validateRequiredPropertiesExist (schema, schemaId) {
/**
* Recursively collects all properties of the schema and its ancestors. They are added to the props object.
*/
function collectProperties (schemaObj, props) {
if (schemaObj.properties) {
for (var property in schemaObj.properties) {
if (schemaObj.properties.hasOwnProperty(property)) {
props[property] = schemaObj.properties[property];
}
}
}
if (schemaObj.allOf) {
schemaObj.allOf.forEach(function (parent) {
collectProperties(parent, props);
});
}
}
if (schema.required && Array.isArray(schema.required)) {
var props = {};
collectProperties(schema, props);
schema.required.forEach(function (requiredProperty) {
if (!props[requiredProperty]) {
throw ono.syntax("Validation failed. Property '%s' listed as required but does not exist in '%s'",
requiredProperty, schemaId);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q46938
|
collectProperties
|
train
|
function collectProperties (schemaObj, props) {
if (schemaObj.properties) {
for (var property in schemaObj.properties) {
if (schemaObj.properties.hasOwnProperty(property)) {
props[property] = schemaObj.properties[property];
}
}
}
if (schemaObj.allOf) {
schemaObj.allOf.forEach(function (parent) {
collectProperties(parent, props);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q46939
|
validateSchema
|
train
|
function validateSchema (api) {
// Choose the appropriate schema (Swagger or OpenAPI)
var schema = api.swagger
? require("swagger-schema-official/schema.json")
: require("openapi-schema-validation/schema/openapi-3.0.json");
var isValid = ZSchema.validate(api, schema);
if (!isValid) {
var err = ZSchema.getLastError();
var message = "Swagger schema validation failed. \n" + formatZSchemaError(err.details);
throw ono.syntax(err, { details: err.details }, message);
}
}
|
javascript
|
{
"resource": ""
}
|
q46940
|
initializeZSchema
|
train
|
function initializeZSchema () {
ZSchema = new ZSchema({
breakOnFirstError: true,
noExtraKeywords: true,
ignoreUnknownFormats: false,
reportPathAsArray: true
});
}
|
javascript
|
{
"resource": ""
}
|
q46941
|
formatZSchemaError
|
train
|
function formatZSchemaError (errors, indent) {
indent = indent || " ";
var message = "";
errors.forEach(function (error, index) {
message += util.format("%s%s at #/%s\n", indent, error.message, error.path.join("/"));
if (error.inner) {
message += formatZSchemaError(error.inner, indent + " ");
}
});
return message;
}
|
javascript
|
{
"resource": ""
}
|
q46942
|
createFilterFunction
|
train
|
function createFilterFunction (resource) {
return resource.has instanceof Function
? id => resource.has(id)
: id => resource[id]
}
|
javascript
|
{
"resource": ""
}
|
q46943
|
genTicks
|
train
|
function genTicks(min, max, count) {
var assign;
if (max < min) {
(assign = [max, min], min = assign[0], max = assign[1]);
}
var step = tickStep(min, max, count);
var first = Math.floor(min / step) * step;
var ticks$$1 = [first];
var cur = first;
while (cur < max) {
cur += step;
ticks$$1.push(cur);
}
if (Math.abs(min - ticks$$1[1]) < step) {
ticks$$1.shift();
ticks$$1[0] = min;
}
if (Math.abs(max - ticks$$1[ticks$$1.length - 2]) < step) {
ticks$$1.pop();
ticks$$1[ticks$$1.length - 1] = max;
}
return ticks$$1
}
|
javascript
|
{
"resource": ""
}
|
q46944
|
train
|
function () {
var styles = document.head.getElementsByTagName("style");
CHTMLSTYLES = styles[styles.length-1].innerHTML;
this.pxPerInch = 96;
this.defaultEx = 6;
this.defaultEm = 6 / CHTML.TEX.x_height * 1000;
this.defaultWidth = 100;
}
|
javascript
|
{
"resource": ""
}
|
|
q46945
|
Insert
|
train
|
function Insert(dst,src) {
for (var id in src) {if (src.hasOwnProperty(id)) {
// allow for concatenation of arrays?
if (typeof src[id] === 'object' && !(src[id] instanceof Array) &&
(typeof dst[id] === 'object' || typeof dst[id] === 'function'))
{Insert(dst[id],src[id])} else {dst[id] = src[id]}
}}
return dst;
}
|
javascript
|
{
"resource": ""
}
|
q46946
|
StartMathJax
|
train
|
function StartMathJax() {
serverState = STATE.STARTED;
var script = document.createElement("script");
script.src = MathJaxPath;
script.onerror = function () {AddError("Can't load MathJax.js from "+MathJaxPath)};
document.head.appendChild(script);
}
|
javascript
|
{
"resource": ""
}
|
q46947
|
AddError
|
train
|
function AddError(message,nopush) {
if (displayErrors) console.error(message);
if (!nopush) errors.push(message);
}
|
javascript
|
{
"resource": ""
}
|
q46948
|
GetSpeech
|
train
|
function GetSpeech(result) {
if (!data.speakText) return;
result.speakText = "Equation";
if (data.format !== "MathML") result.speakText = data.math;
else {
var jax = MathJax.Hub.getAllJax()[0];
if (jax.root.alttext) result.speakText = jax.root.alttext;
}
}
|
javascript
|
{
"resource": ""
}
|
q46949
|
GetHTML
|
train
|
function GetHTML(result) {
if (data.css) result.css = CHTMLSTYLES;
if (!data.html && !data.htmlNode) return;
var jax = MathJax.Hub.getAllJax()[0]; if (!jax) return;
var script = jax.SourceElement(), html = script.previousSibling;
// add speech text if there isn't one
if (data.speakText){
var labelTarget = html.querySelector('.mjx-math');
for (child of labelTarget.childNodes) child.setAttribute("aria-hidden",true);
if (!labelTarget.getAttribute("aria-label")){
labelTarget.setAttribute("aria-label",result.speakText);
}
}
// remove automatically generated IDs
var ids = html.querySelectorAll('[id^="MJXc-Node-"]');
for (var i = 0; i < ids.length; i++){
ids[i].removeAttribute("id");
}
// remove extreneous frame element
var frame = html.querySelector('[id^="MathJax-Element-"]');
if (frame){
// in display-mode, the frame is inside the display-style wrapper
html.insertBefore(frame.firstChild, frame);
html.removeChild(frame);
}
else{
// otherwise (inline-mode) the frame is the root element
html.removeAttribute("id");
}
if (data.html) result.html = html.outerHTML;
if (data.htmlNode) result.htmlNode = html;
}
|
javascript
|
{
"resource": ""
}
|
q46950
|
GetSVG
|
train
|
function GetSVG(result) {
if (!data.svg && !data.svgNode) return;
var jax = MathJax.Hub.getAllJax()[0]; if (!jax) return;
var script = jax.SourceElement(),
svg = script.previousSibling.getElementsByTagName("svg")[0];
svg.setAttribute("xmlns","http://www.w3.org/2000/svg");
//
// Add the speech text and mark the SVG appropriately
//
if (data.speakText){
for (var i=0, m=svg.childNodes.length; i < m; i++)
svg.childNodes[i].setAttribute("aria-hidden",true);
// Note: if aria-label exists, getSpeech preserved it in speakText
// remove aria-label since labelled-by title is preferred
svg.removeAttribute("aria-label");
ID++; var id = "MathJax-SVG-"+ID+"-Title";
svg.setAttribute("aria-labelledby",id);
var node = MathJax.HTML.Element("title",{id:id},[result.speakText]);
svg.insertBefore(node,svg.firstChild);
}
if (data.svg){
//
// SVG data is modified to add linebreaks for readability,
// and to put back the xlink namespace that is removed in HTML5
//
var svgdata = svg.outerHTML.replace(/><([^/])/g,">\n<$1")
.replace(/(<\/[a-z]*>)(?=<\/)/g,"$1\n")
.replace(/(<(?:use|image) [^>]*)(href=)/g,' $1xlink:$2');
//
// Add the requested data to the results
//
result.svg = svgdata;
}
if (data.svgNode) result.svgNode = svg;
result.width = svg.getAttribute("width");
result.height = svg.getAttribute("height");
result.style = svg.style.cssText;
}
|
javascript
|
{
"resource": ""
}
|
q46951
|
StartQueue
|
train
|
function StartQueue() {
data = callback = originalData = null; // clear existing equation, if any
errors = sErrors; sErrors = []; // clear any errors
if (!queue.length) return; // return if nothing to do
serverState = STATE.BUSY;
var result = {}, $$ = window.Array;
//
// Get the math data and callback
// and set the content with the proper script type
//
var item = queue.shift();
data = item[0]; callback = item[1]; originalData = item[2];
content.innerHTML = "";
MathJax.HTML.addElement(content,"script",{type: "math/"+TYPES[data.format]},[data.math]);
html.setAttribute("xmlns:"+data.xmlns,"http://www.w3.org/1998/Math/MathML");
//
// Set the SVG and TeX parameters
// according to the requested data
//
var CHTML = MathJax.OutputJax.CommonHTML,
SVG = MathJax.OutputJax.SVG,
TEX = MathJax.InputJax.TeX,
HUB = MathJax.Hub;
SVG.defaultEx = CHTML.defaultEx = data.ex;
SVG.defaultWidth = CHTMLdefaultWidth = data.width * data.ex;
SVG.config.linebreaks.automatic = CHTML.config.linebreaks.automatic = data.linebreaks;
SVG.config.linebreaks.width = CHTML.config.linebreaks.width = data.width * data.ex;
SVG.config.useFontCache = data.useFontCache;
SVG.config.useGlobalCache = data.useGlobalCache;
TEX.config.equationNumbers.autoNumber = data.equationNumbers;
//
// Set the state from data.state or clear it
//
GetState(data.state);
//
// Get the renderer to use
//
var renderer = (
(data.html || data.htmlNode || data.css) ? "CommonHTML" :
(data.svg || data.svgNode) ? "SVG" : "None"
);
//
// Set up a timeout timer to restart MathJax if it runs too long,
// Then push the Typeset call, the MathML, speech, and SVG calls,
// and our TypesetDone routine
//
timer = setTimeout(RestartMathJax,data.timeout);
HUB.Queue(
$$(SetRenderer,renderer),
$$("Process",HUB),
$$(TypesetDone,result),
$$(GetSpeech,result),
$$(GetMML,result),
$$(GetHTML,result),
$$(RerenderSVG,result),
$$(GetSVG,result),
$$(ReturnResult,result)
);
}
|
javascript
|
{
"resource": ""
}
|
q46952
|
GetState
|
train
|
function GetState(state) {
var SVG = MathJax.OutputJax.SVG,
TEX = MathJax.InputJax.TeX,
MML = MathJax.ElementJax.mml,
AMS = MathJax.Extension["TeX/AMSmath"],
HUB = MathJax.Hub, HTML = MathJax.HTML,
GLYPH = (SVG.BBOX||{}).GLYPH;
if (state && state.AMS) {
AMS.startNumber = state.AMS.startNumber;
AMS.labels = state.AMS.labels;
AMS.IDs = state.AMS.IDs;
MML.SUPER.ID = state.mmlID;
GLYPH.glyphs = state.glyphs;
GLYPH.defs = state.defs;
GLYPH.n = state.n;
ID = state.ID;
} else {
if (state) {state.AMS = {}}
if (SVG.resetGlyphs) SVG.resetGlyphs(true);
if (data.useGlobalCache) {
state.glyphs = {};
state.defs = HTML.Element("defs");
state.n = 0;
}
if (TEX.resetEquationNumbers) TEX.resetEquationNumbers();
MML.SUPER.ID = ID = 0;
MathJax.OutputJax.CommonHTML.ID = 0;
}
}
|
javascript
|
{
"resource": ""
}
|
q46953
|
TypesetDone
|
train
|
function TypesetDone(result) {
if (timer) {clearTimeout(timer); timer = null}
html.removeAttribute("xmlns:"+data.xmlns);
}
|
javascript
|
{
"resource": ""
}
|
q46954
|
ReturnResult
|
train
|
function ReturnResult(result) {
if (errors.length) {
result.errors = errors;
}
var state = data.state;
if (state) {
var AMS = MathJax.Extension["TeX/AMSmath"];
var GLYPH = (MathJax.OutputJax.SVG||{}).BBOX.GLYPH;
state.AMS.startNumber = AMS.startNumber;
state.AMS.labels = AMS.labels;
state.AMS.IDs = AMS.IDs;
state.mmlID = MathJax.ElementJax.mml.SUPER.ID;
state.glyphs = GLYPH.glyphs;
state.defs = GLYPH.defs;
state.n = GLYPH.n;
state.ID = ID;
}
serverState = STATE.READY;
callback(result, originalData);
if (serverState === STATE.READY) StartQueue();
}
|
javascript
|
{
"resource": ""
}
|
q46955
|
train
|
function (data, callback) {
if (!callback || typeof(callback) !== "function") {
if (displayErrors) console.error("Missing callback");
return;
}
var options = {};
for (var id in defaults) {if (defaults.hasOwnProperty(id)) {
options[id] = (data.hasOwnProperty(id) ? data[id]: defaults[id]);
}}
if (data.state) {options.state = data.state}
if (!TYPES[options.format]) {ReportError("Unknown format: "+options.format,callback); return}
queue.push([options,callback,Object.assign({},data)]);
if (serverState == STATE.STOPPED) {RestartMathJax()}
if (serverState == STATE.READY) StartQueue();
}
|
javascript
|
{
"resource": ""
}
|
|
q46956
|
duration
|
train
|
function duration(value) {
if (!isFinite(value)) return String(value);
var sign = '';
if (value < 0) {
sign = '-';
value = Math.abs(value);
} else {
value = Number(value);
}
var sec = value % 60;
var parts = [Math.round(sec) === sec ? sec : sec.toFixed(3)];
if (value < 60) {
parts.unshift(0); // at least one : is required
} else {
value = Math.round((value - parts[0]) / 60);
parts.unshift(value % 60); // minutes
if (value >= 60) {
value = Math.round((value - parts[0]) / 60);
parts.unshift(value); // hours
}
}
var first = parts.shift();
return (
sign +
first +
':' +
parts
.map(function(n) {
return n < 10 ? '0' + String(n) : String(n);
})
.join(':')
);
}
|
javascript
|
{
"resource": ""
}
|
q46957
|
Bromise
|
train
|
function Bromise(object, method, args) {
this.object = object;
this.method = method;
this.args = args.length > 1 ? args.slice(1) : [];
}
|
javascript
|
{
"resource": ""
}
|
q46958
|
train
|
function(downloadUrl, manifestUrl, flavor) {
return getManifest(manifestUrl)
.then(function(manifest) {
return {
desiredVersion: manifest.stable.replace('v', ''),
downloadUrl: downloadUrl,
manifestUrl: manifestUrl,
flavor: flavor
}
})
.then(this.getVersion);
}
|
javascript
|
{
"resource": ""
}
|
|
q46959
|
$apply
|
train
|
function $apply(f, value) {
if (process.env.NODE_ENV !== 'production') {
assert(isFunction(f), 'Invalid argument f supplied to immutability helper { $apply: f } (expected a function)');
}
return f(value);
}
|
javascript
|
{
"resource": ""
}
|
q46960
|
List
|
train
|
function List(value, path) {
if (process.env.NODE_ENV === 'production') {
if (identity) {
return value; // just trust the input if elements must not be hydrated
}
}
if (process.env.NODE_ENV !== 'production') {
path = path || [displayName];
assert(isArray(value), function () { return 'Invalid value ' + assert.stringify(value) + ' supplied to ' + path.join('/') + ' (expected an array of ' + typeNameCache + ')'; });
}
var idempotent = true; // will remain true if I can reutilise the input
var ret = []; // make a temporary copy, will be discarded if idempotent remains true
for (var i = 0, len = value.length; i < len; i++ ) {
var actual = value[i];
var instance = create(type, actual, ( process.env.NODE_ENV !== 'production' ? path.concat(i + ': ' + typeNameCache) : null ));
idempotent = idempotent && ( actual === instance );
ret.push(instance);
}
if (idempotent) { // implements idempotency
ret = value;
}
if (process.env.NODE_ENV !== 'production') {
Object.freeze(ret);
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q46961
|
generateWebHook
|
train
|
function generateWebHook(cordovaContext, pluginPreferences) {
var projectRoot = cordovaContext.opts.projectRoot;
var configXmlHelper = new ConfigXmlHelper(cordovaContext);
var packageName = configXmlHelper.getPackageName('android');
var template = readTemplate(projectRoot);
// if template was not found - exit
if (template == null || template.length == 0) {
return;
}
// generate hook content
var linksToInsert = generateLinksSet(projectRoot, packageName, pluginPreferences);
var hookContent = template.replace(LINK_PLACEHOLDER, linksToInsert);
// save hook
saveWebHook(projectRoot, hookContent);
}
|
javascript
|
{
"resource": ""
}
|
q46962
|
readTemplate
|
train
|
function readTemplate(projectRoot) {
var filePath = path.join(projectRoot, WEB_HOOK_TPL_FILE_PATH);
var tplData = null;
try {
tplData = fs.readFileSync(filePath, 'utf8');
} catch (err) {
console.warn('Template file for android web hook is not found!');
console.warn(err);
}
return tplData;
}
|
javascript
|
{
"resource": ""
}
|
q46963
|
saveWebHook
|
train
|
function saveWebHook(projectRoot, hookContent) {
var filePath = path.join(projectRoot, WEB_HOOK_FILE_PATH);
var isSaved = true;
// ensure directory exists
createDirectoryIfNeeded(path.dirname(filePath));
// write data to file
try {
fs.writeFileSync(filePath, hookContent, 'utf8');
} catch (err) {
console.warn('Failed to create android web hook!');
console.warn(err);
isSaved = false;
}
return isSaved;
}
|
javascript
|
{
"resource": ""
}
|
q46964
|
generateEntitlements
|
train
|
function generateEntitlements(cordovaContext, pluginPreferences) {
context = cordovaContext;
var currentEntitlements = getEntitlementsFileContent();
var newEntitlements = injectPreferences(currentEntitlements, pluginPreferences);
saveContentToEntitlementsFile(newEntitlements);
}
|
javascript
|
{
"resource": ""
}
|
q46965
|
saveContentToEntitlementsFile
|
train
|
function saveContentToEntitlementsFile(content) {
var plistContent = plist.build(content);
var filePath = pathToEntitlementsFile();
// ensure that file exists
mkpath.sync(path.dirname(filePath));
// save it's content
fs.writeFileSync(filePath, plistContent, 'utf8');
}
|
javascript
|
{
"resource": ""
}
|
q46966
|
getEntitlementsFileContent
|
train
|
function getEntitlementsFileContent() {
var pathToFile = pathToEntitlementsFile();
var content;
try {
content = fs.readFileSync(pathToFile, 'utf8');
} catch (err) {
return defaultEntitlementsFile();
}
return plist.parse(content);
}
|
javascript
|
{
"resource": ""
}
|
q46967
|
injectPreferences
|
train
|
function injectPreferences(currentEntitlements, pluginPreferences) {
var newEntitlements = currentEntitlements;
var content = generateAssociatedDomainsContent(pluginPreferences);
newEntitlements[ASSOCIATED_DOMAINS] = content;
return newEntitlements;
}
|
javascript
|
{
"resource": ""
}
|
q46968
|
generateAssociatedDomainsContent
|
train
|
function generateAssociatedDomainsContent(pluginPreferences) {
var domainsList = [];
// generate list of host links
pluginPreferences.hosts.forEach(function(host) {
var link = domainsListEntryForHost(host);
if (domainsList.indexOf(link) == -1) {
domainsList.push(link);
}
});
return domainsList;
}
|
javascript
|
{
"resource": ""
}
|
q46969
|
pathToEntitlementsFile
|
train
|
function pathToEntitlementsFile() {
if (entitlementsFilePath === undefined) {
entitlementsFilePath = path.join(getProjectRoot(), 'platforms', 'ios', getProjectName(), 'Resources', getProjectName() + '.entitlements');
}
return entitlementsFilePath;
}
|
javascript
|
{
"resource": ""
}
|
q46970
|
getProjectName
|
train
|
function getProjectName() {
if (projectName === undefined) {
var configXmlHelper = new ConfigXmlHelper(context);
projectName = configXmlHelper.getProjectName();
}
return projectName;
}
|
javascript
|
{
"resource": ""
}
|
q46971
|
run
|
train
|
function run(ctx) {
var projectRoot = ctx.opts.projectRoot;
var iosProjectFilePath = path.join(projectRoot, 'platforms', 'ios');
var configXmlHelper = new ConfigXmlHelper(ctx);
var newProjectName = configXmlHelper.getProjectName();
var oldProjectName = getOldProjectName(iosProjectFilePath);
// if name has not changed - do nothing
if (oldProjectName.length && oldProjectName === newProjectName) {
return;
}
console.log('Project name has changed. Renaming .entitlements file.');
// if it does - rename it
var oldEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', oldProjectName + '.entitlements');
var newEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', newProjectName + '.entitlements');
try {
fs.renameSync(oldEntitlementsFilePath, newEntitlementsFilePath);
} catch (err) {
console.warn('Failed to rename .entitlements file.');
console.warn(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q46972
|
getOldProjectName
|
train
|
function getOldProjectName(projectDir) {
var files = [];
try {
files = fs.readdirSync(projectDir);
} catch (err) {
return '';
}
var projectFile = '';
files.forEach(function(fileName) {
if (path.extname(fileName) === '.xcodeproj') {
projectFile = path.basename(fileName, '.xcodeproj');
}
});
return projectFile;
}
|
javascript
|
{
"resource": ""
}
|
q46973
|
writePreferences
|
train
|
function writePreferences(cordovaContext, pluginPreferences) {
var pathToManifest = path.join(cordovaContext.opts.projectRoot, 'platforms', 'android', 'AndroidManifest.xml');
var manifestSource = xmlHelper.readXmlAsJson(pathToManifest);
var cleanManifest;
var updatedManifest;
// remove old intent-filters
cleanManifest = removeOldOptions(manifestSource);
// inject intent-filters based on plugin preferences
updatedManifest = injectOptions(cleanManifest, pluginPreferences);
// save new version of the AndroidManifest
xmlHelper.writeJsonAsXml(updatedManifest, pathToManifest);
}
|
javascript
|
{
"resource": ""
}
|
q46974
|
removeOldOptions
|
train
|
function removeOldOptions(manifestData) {
var cleanManifest = manifestData;
var activities = manifestData['manifest']['application'][0]['activity'];
activities.forEach(removeIntentFiltersFromActivity);
cleanManifest['manifest']['application'][0]['activity'] = activities;
return cleanManifest;
}
|
javascript
|
{
"resource": ""
}
|
q46975
|
removeIntentFiltersFromActivity
|
train
|
function removeIntentFiltersFromActivity(activity) {
var oldIntentFilters = activity['intent-filter'];
var newIntentFilters = [];
if (oldIntentFilters == null || oldIntentFilters.length == 0) {
return;
}
oldIntentFilters.forEach(function(intentFilter) {
if (!isIntentFilterForUniversalLinks(intentFilter)) {
newIntentFilters.push(intentFilter);
}
});
activity['intent-filter'] = newIntentFilters;
}
|
javascript
|
{
"resource": ""
}
|
q46976
|
isIntentFilterForUniversalLinks
|
train
|
function isIntentFilterForUniversalLinks(intentFilter) {
var actions = intentFilter['action'];
var categories = intentFilter['category'];
var data = intentFilter['data'];
return isActionForUniversalLinks(actions) &&
isCategoriesForUniversalLinks(categories) &&
isDataTagForUniversalLinks(data);
}
|
javascript
|
{
"resource": ""
}
|
q46977
|
isActionForUniversalLinks
|
train
|
function isActionForUniversalLinks(actions) {
// there can be only 1 action
if (actions == null || actions.length != 1) {
return false;
}
var action = actions[0]['$']['android:name'];
return ('android.intent.action.VIEW' === action);
}
|
javascript
|
{
"resource": ""
}
|
q46978
|
isCategoriesForUniversalLinks
|
train
|
function isCategoriesForUniversalLinks(categories) {
// there can be only 2 categories
if (categories == null || categories.length != 2) {
return false;
}
var isBrowsable = false;
var isDefault = false;
// check intent categories
categories.forEach(function(category) {
var categoryName = category['$']['android:name'];
if (!isBrowsable) {
isBrowsable = 'android.intent.category.BROWSABLE' === categoryName;
}
if (!isDefault) {
isDefault = 'android.intent.category.DEFAULT' === categoryName;
}
});
return isDefault && isBrowsable;
}
|
javascript
|
{
"resource": ""
}
|
q46979
|
isDataTagForUniversalLinks
|
train
|
function isDataTagForUniversalLinks(data) {
// can have only 1 data tag in the intent-filter
if (data == null || data.length != 1) {
return false;
}
var dataHost = data[0]['$']['android:host'];
var dataScheme = data[0]['$']['android:scheme'];
var hostIsSet = dataHost != null && dataHost.length > 0;
var schemeIsSet = dataScheme != null && dataScheme.length > 0;
return hostIsSet && schemeIsSet;
}
|
javascript
|
{
"resource": ""
}
|
q46980
|
injectOptions
|
train
|
function injectOptions(manifestData, pluginPreferences) {
var changedManifest = manifestData;
var activitiesList = changedManifest['manifest']['application'][0]['activity'];
var launchActivityIndex = getMainLaunchActivityIndex(activitiesList);
var ulIntentFilters = [];
var launchActivity;
if (launchActivityIndex < 0) {
console.warn('Could not find launch activity in the AndroidManifest file. Can\'t inject Universal Links preferences.');
return;
}
// get launch activity
launchActivity = activitiesList[launchActivityIndex];
// generate intent-filters
pluginPreferences.hosts.forEach(function(host) {
host.paths.forEach(function(hostPath) {
ulIntentFilters.push(createIntentFilter(host.name, host.scheme, hostPath));
});
});
// add Universal Links intent-filters to the launch activity
launchActivity['intent-filter'] = launchActivity['intent-filter'].concat(ulIntentFilters);
return changedManifest;
}
|
javascript
|
{
"resource": ""
}
|
q46981
|
getMainLaunchActivityIndex
|
train
|
function getMainLaunchActivityIndex(activities) {
var launchActivityIndex = -1;
activities.some(function(activity, index) {
if (isLaunchActivity(activity)) {
launchActivityIndex = index;
return true;
}
return false;
});
return launchActivityIndex;
}
|
javascript
|
{
"resource": ""
}
|
q46982
|
createIntentFilter
|
train
|
function createIntentFilter(host, scheme, pathName) {
var intentFilter = {
'$': {
'android:autoVerify': 'true'
},
'action': [{
'$': {
'android:name': 'android.intent.action.VIEW'
}
}],
'category': [{
'$': {
'android:name': 'android.intent.category.DEFAULT'
}
}, {
'$': {
'android:name': 'android.intent.category.BROWSABLE'
}
}],
'data': [{
'$': {
'android:host': host,
'android:scheme': scheme
}
}]
};
injectPathComponentIntoIntentFilter(intentFilter, pathName);
return intentFilter;
}
|
javascript
|
{
"resource": ""
}
|
q46983
|
injectPathComponentIntoIntentFilter
|
train
|
function injectPathComponentIntoIntentFilter(intentFilter, pathName) {
if (pathName == null || pathName === '*') {
return;
}
var attrKey = 'android:path';
if (pathName.indexOf('*') >= 0) {
attrKey = 'android:pathPattern';
pathName = pathName.replace(/\*/g, '.*');
}
if (pathName.indexOf('/') != 0) {
pathName = '/' + pathName;
}
intentFilter['data'][0]['$'][attrKey] = pathName;
}
|
javascript
|
{
"resource": ""
}
|
q46984
|
readPreferences
|
train
|
function readPreferences(cordovaContext) {
// read data from projects root config.xml file
var configXml = new ConfigXmlHelper(cordovaContext).read();
if (configXml == null) {
console.warn('config.xml not found! Please, check that it exist\'s in your project\'s root directory.');
return null;
}
// look for data from the <universal-links> tag
var ulXmlPreferences = configXml.widget['universal-links'];
if (ulXmlPreferences == null || ulXmlPreferences.length == 0) {
console.warn('<universal-links> tag is not set in the config.xml. Universal Links plugin is not going to work.');
return null;
}
var xmlPreferences = ulXmlPreferences[0];
// read hosts
var hosts = constructHostsList(xmlPreferences);
// read ios team ID
var iosTeamId = getTeamIdPreference(xmlPreferences);
return {
'hosts': hosts,
'iosTeamId': iosTeamId
};
}
|
javascript
|
{
"resource": ""
}
|
q46985
|
constructHostsList
|
train
|
function constructHostsList(xmlPreferences) {
var hostsList = [];
// look for defined hosts
var xmlHostList = xmlPreferences['host'];
if (xmlHostList == null || xmlHostList.length == 0) {
return [];
}
xmlHostList.forEach(function(xmlElement) {
var host = constructHostEntry(xmlElement);
if (host) {
hostsList.push(host);
}
});
return hostsList;
}
|
javascript
|
{
"resource": ""
}
|
q46986
|
constructHostEntry
|
train
|
function constructHostEntry(xmlElement) {
var host = {
scheme: DEFAULT_SCHEME,
name: '',
paths: []
};
var hostProperties = xmlElement['$'];
if (hostProperties == null || hostProperties.length == 0) {
return null;
}
// read host name
host.name = hostProperties.name;
// read scheme if defined
if (hostProperties['scheme'] != null) {
host.scheme = hostProperties.scheme;
}
// construct paths list, defined for the given host
host.paths = constructPaths(xmlElement);
return host;
}
|
javascript
|
{
"resource": ""
}
|
q46987
|
constructPaths
|
train
|
function constructPaths(xmlElement) {
if (xmlElement['path'] == null) {
return ['*'];
}
var paths = [];
xmlElement.path.some(function(pathElement) {
var url = pathElement['$']['url'];
// Ignore explicit paths if '*' is defined
if (url === '*') {
paths = ['*'];
return true;
}
paths.push(url);
});
return paths;
}
|
javascript
|
{
"resource": ""
}
|
q46988
|
createNewAssociationFiles
|
train
|
function createNewAssociationFiles(pluginPreferences) {
var teamId = pluginPreferences.iosTeamId;
if (!teamId) {
teamId = IOS_TEAM_ID;
}
pluginPreferences.hosts.forEach(function(host) {
var content = generateFileContentForHost(host, teamId);
saveContentToFile(host.name, content);
});
}
|
javascript
|
{
"resource": ""
}
|
q46989
|
generateFileContentForHost
|
train
|
function generateFileContentForHost(host, teamId) {
var appID = teamId + '.' + getBundleId();
var paths = host.paths.slice();
// if paths are '*' - we should add '/' to it to support root domains.
// https://github.com/nordnet/cordova-universal-links-plugin/issues/46
if (paths.length == 1 && paths[0] === '*') {
paths.push('/');
}
return {
"applinks": {
"apps": [],
"details": [{
"appID": appID,
"paths": paths
}]
}
};
}
|
javascript
|
{
"resource": ""
}
|
q46990
|
saveContentToFile
|
train
|
function saveContentToFile(filePrefix, content) {
var dirPath = getWebHookDirectory();
var filePath = path.join(dirPath, filePrefix + '#' + ASSOCIATION_FILE_NAME);
// create all directories from file path
createDirectoriesIfNeeded(dirPath);
// write content to the file
try {
fs.writeFileSync(filePath, JSON.stringify(content, null, 2), 'utf8');
} catch (err) {
console.log(err);
}
}
|
javascript
|
{
"resource": ""
}
|
q46991
|
getBundleId
|
train
|
function getBundleId() {
if (bundleId === undefined) {
var configXmlHelper = new ConfigXmlHelper(context);
bundleId = configXmlHelper.getPackageName('ios');
}
return bundleId;
}
|
javascript
|
{
"resource": ""
}
|
q46992
|
getCordovaConfigParser
|
train
|
function getCordovaConfigParser(configFilePath) {
var ConfigParser;
// If we are running Cordova 5.4 or abova - use parser from cordova-common.
// Otherwise - from cordova-lib.
try {
ConfigParser = context.requireCordovaModule('cordova-common/src/ConfigParser/ConfigParser');
} catch (e) {
ConfigParser = context.requireCordovaModule('cordova-lib/src/configparser/ConfigParser')
}
return new ConfigParser(configFilePath);
}
|
javascript
|
{
"resource": ""
}
|
q46993
|
run
|
train
|
function run(cordovaContext) {
var pluginPreferences = configParser.readPreferences(cordovaContext);
var platformsList = cordovaContext.opts.platforms;
// if no preferences are found - exit
if (pluginPreferences == null) {
return;
}
// if no host is defined - exit
if (pluginPreferences.hosts == null || pluginPreferences.hosts.length == 0) {
console.warn('No host is specified in the config.xml. Universal Links plugin is not going to work.');
return;
}
platformsList.forEach(function(platform) {
switch (platform) {
case ANDROID:
{
activateUniversalLinksInAndroid(cordovaContext, pluginPreferences);
break;
}
case IOS:
{
activateUniversalLinksInIos(cordovaContext, pluginPreferences);
break;
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q46994
|
activateUniversalLinksInAndroid
|
train
|
function activateUniversalLinksInAndroid(cordovaContext, pluginPreferences) {
// inject preferenes into AndroidManifest.xml
androidManifestWriter.writePreferences(cordovaContext, pluginPreferences);
// generate html file with the <link> tags that you should inject on the website.
androidWebHook.generate(cordovaContext, pluginPreferences);
}
|
javascript
|
{
"resource": ""
}
|
q46995
|
activateUniversalLinksInIos
|
train
|
function activateUniversalLinksInIos(cordovaContext, pluginPreferences) {
// modify xcode project preferences
iosProjectPreferences.enableAssociativeDomainsCapability(cordovaContext);
// generate entitlements file
iosProjectEntitlements.generateAssociatedDomainsEntitlements(cordovaContext, pluginPreferences);
// generate apple-site-association-file
iosAppSiteAssociationFile.generate(cordovaContext, pluginPreferences);
}
|
javascript
|
{
"resource": ""
}
|
q46996
|
enableAssociativeDomainsCapability
|
train
|
function enableAssociativeDomainsCapability(cordovaContext) {
context = cordovaContext;
var projectFile = loadProjectFile();
// adjust preferences
activateAssociativeDomains(projectFile.xcode);
// add entitlements file to pbxfilereference
addPbxReference(projectFile.xcode);
// save changes
projectFile.write();
}
|
javascript
|
{
"resource": ""
}
|
q46997
|
addPbxReference
|
train
|
function addPbxReference(xcodeProject) {
var fileReferenceSection = nonComments(xcodeProject.pbxFileReferenceSection());
var entitlementsFileName = path.basename(pathToEntitlementsFile());
if (isPbxReferenceAlreadySet(fileReferenceSection, entitlementsFileName)) {
console.log('Entitlements file is in reference section.');
return;
}
console.log('Entitlements file is not in references section, adding it');
xcodeProject.addResourceFile(entitlementsFileName);
}
|
javascript
|
{
"resource": ""
}
|
q46998
|
loadProjectFile
|
train
|
function loadProjectFile() {
var platform_ios;
var projectFile;
try {
// try pre-5.0 cordova structure
platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms')['ios'];
projectFile = platform_ios.parseProjectFile(iosPlatformPath());
} catch (e) {
// let's try cordova 5.0 structure
platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms/ios');
projectFile = platform_ios.parseProjectFile(iosPlatformPath());
}
return projectFile;
}
|
javascript
|
{
"resource": ""
}
|
q46999
|
refresh
|
train
|
function refresh (env) {
return safeWipe(env.dest, {
force: true,
parent: is.string(env.src) || is.array(env.src) ? g2b(env.src) : null,
silent: true,
})
.then(() => mkdir(env.dest))
.then(() => {
env.logger.log(`Folder \`${env.displayDest}\` successfully refreshed.`)
})
.catch(err => {
// Friendly error for already existing directory.
throw new errors.SassDocError(err.message)
})
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.