repo_name stringlengths 2 55 | dataset stringclasses 1 value | owner stringlengths 3 31 | lang stringclasses 10 values | func_name stringlengths 1 104 | code stringlengths 20 96.7k | docstring stringlengths 1 4.92k | url stringlengths 94 241 | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
langhaiblogs | github_2023 | Allenkuzma | javascript | defaultLoading | function defaultLoading(api, opts) {
opts = opts || {};
defaults(opts, {
text: 'loading',
textColor: '#000',
fontSize: 12,
fontWeight: 'normal',
fontStyle: 'normal',
fontFamily: 'sans-serif',
maskColor: 'rgba(255, 255, 255, 0.8)',
showSpinner: true,
color: '#5470c6',
spinnerRadius: 10,
lineWidth: 5,
zlevel: 0
});
var group = new Group();
var mask = new Rect({
style: {
fill: opts.maskColor
},
zlevel: opts.zlevel,
z: 10000
});
group.add(mask);
var textContent = new ZRText({
style: {
text: opts.text,
fill: opts.textColor,
fontSize: opts.fontSize,
fontWeight: opts.fontWeight,
fontStyle: opts.fontStyle,
fontFamily: opts.fontFamily
},
zlevel: opts.zlevel,
z: 10001
});
var labelRect = new Rect({
style: {
fill: 'none'
},
textContent: textContent,
textConfig: {
position: 'right',
distance: 10
},
zlevel: opts.zlevel,
z: 10001
});
group.add(labelRect);
var arc;
if (opts.showSpinner) {
arc = new Arc({
shape: {
startAngle: -PI$3 / 2,
endAngle: -PI$3 / 2 + 0.1,
r: opts.spinnerRadius
},
style: {
stroke: opts.color,
lineCap: 'round',
lineWidth: opts.lineWidth
},
zlevel: opts.zlevel,
z: 10001
});
arc.animateShape(true).when(1000, {
endAngle: PI$3 * 3 / 2
}).start('circularInOut');
arc.animateShape(true).when(1000, {
startAngle: PI$3 * 3 / 2
}).delay(300).start('circularInOut');
group.add(arc);
} // Inject resize
group.resize = function () {
var textWidth = textContent.getBoundingRect().width;
var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
// textDistance needs to be calculated when both animation and text exist
var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
+ (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
+ (textWidth ? 0 : r);
var cy = api.getHeight() / 2;
opts.showSpinner && arc.setShape({
cx: cx,
cy: cy
});
labelRect.setShape({
x: cx - r,
y: cy - r,
width: r * 2,
height: r * 2
});
mask.setShape({
x: 0,
y: 0,
width: api.getWidth(),
height: api.getHeight()
});
};
group.resize();
return group;
} | /**
* @param {module:echarts/ExtensionAPI} api
* @param {Object} [opts]
* @param {string} [opts.text]
* @param {string} [opts.color]
* @param {string} [opts.textColor]
* @return {module:zrender/Element}
*/ | https://github.com/Allenkuzma/langhaiblogs/blob/a77bd2103800a65f11812b04afb506aeea9c9eae/src/main/resources/static/echarts/echarts.js#L25325-L25431 | a77bd2103800a65f11812b04afb506aeea9c9eae |
langhaiblogs | github_2023 | Allenkuzma | javascript | radialCoordinate | function radialCoordinate(rad, r) {
rad -= Math.PI / 2;
return {
x: r * Math.cos(rad),
y: r * Math.sin(rad)
};
} | /**
* Transform the common coordinate to radial coordinate.
*/ | https://github.com/Allenkuzma/langhaiblogs/blob/a77bd2103800a65f11812b04afb506aeea9c9eae/src/main/resources/static/pear/component/pear/module/echarts.js#L54204-L54210 | a77bd2103800a65f11812b04afb506aeea9c9eae |
teddycloud | github_2023 | toniebox-reverse-engineering | javascript | shouldUseClickEvent | function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
var nodeName = elem.nodeName;
return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
} | /**
* SECTION: handle `click` event
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/contrib/data/www/library/react-dom.development.js#L9350-L9356 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
teddycloud | github_2023 | toniebox-reverse-engineering | javascript | Component | function Component(props, context, updater) {
this.props = props;
this.context = context; // If a component has string refs, we will assign a different object later.
this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
} | /**
* Base class helpers for the updating state of a component.
*/ | https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/contrib/data/www/library/react.development.js#L513-L521 | 83d3b29cbfc74e8f76f48f8782646c8e464055b2 |
praxis-ide | github_2023 | toblotron | javascript | Var | function Var( id ) {
this.id = id;
this.ground = false;
} | // PROLOG OBJECTS | https://github.com/toblotron/praxis-ide/blob/b4f732c28f0280ead015094bce893a378a28bec2/lib/tau-prolog.0.3.4.js#L1619-L1622 | b4f732c28f0280ead015094bce893a378a28bec2 |
praxis-ide | github_2023 | toblotron | javascript | buildTokenBadBidi | function buildTokenBadBidi(inner, order) {
return function (builder, text, style, startStyle, endStyle, title, css) {
style = style ? style + " cm-force-border" : "cm-force-border"
var start = builder.pos, end = start + text.length
for (;;) {
// Find the part that overlaps with the start of this text
var part = (void 0)
for (var i = 0; i < order.length; i++) {
part = order[i]
if (part.to > start && part.from <= start) { break }
}
if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
startStyle = null
text = text.slice(part.to - start)
start = part.to
}
}
} | // Work around nonsense dimensions being reported for stretches of | https://github.com/toblotron/praxis-ide/blob/b4f732c28f0280ead015094bce893a378a28bec2/lib/codemirror/lib/codemirror.js#L1949-L1967 | b4f732c28f0280ead015094bce893a378a28bec2 |
praxis-ide | github_2023 | toblotron | javascript | Fancytree | function Fancytree(widget) {
this.widget = widget;
this.$div = widget.element;
this.options = widget.options;
if (this.options) {
if (this.options.lazyload !== undefined) {
$.error(
"The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead."
);
}
if (this.options.loaderror !== undefined) {
$.error(
"The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead."
);
}
if (this.options.fx !== undefined) {
$.error(
"The 'fx' option was replaced by 'toggleEffect' since 2014-11-30."
);
}
if (this.options.removeNode !== undefined) {
$.error(
"The 'removeNode' event was replaced by 'modifyChild' since 2.20 (2016-09-10)."
);
}
}
this.ext = {}; // Active extension instances
this.types = {};
this.columns = {};
// allow to init tree.data.foo from <div data-foo=''>
this.data = _getElementDataAsDict(this.$div);
// TODO: use widget.uuid instead?
this._id = "" + (this.options.treeId || $.ui.fancytree._nextId++);
// TODO: use widget.eventNamespace instead?
this._ns = ".fancytree-" + this._id; // append for namespaced events
this.activeNode = null;
this.focusNode = null;
this._hasFocus = null;
this._tempCache = {};
this._lastMousedownNode = null;
this._enableUpdate = true;
this.lastSelectedNode = null;
this.systemFocusElement = null;
this.lastQuicksearchTerm = "";
this.lastQuicksearchTime = 0;
this.viewport = null; // ext-grid
this.statusClassPropName = "span";
this.ariaPropName = "li";
this.nodeContainerAttrName = "li";
// Remove previous markup if any
this.$div.find(">ul.fancytree-container").remove();
// Create a node without parent.
var fakeParent = { tree: this },
$ul;
this.rootNode = new FancytreeNode(fakeParent, {
title: "root",
key: "root_" + this._id,
children: null,
expanded: true,
});
this.rootNode.parent = null;
// Create root markup
$ul = $("<ul>", {
id: "ft-id-" + this._id,
class: "ui-fancytree fancytree-container fancytree-plain",
}).appendTo(this.$div);
this.$container = $ul;
this.rootNode.ul = $ul[0];
if (this.options.debugLevel == null) {
this.options.debugLevel = FT.debugLevel;
}
// // Add container to the TAB chain
// // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
// // #577: Allow to set tabindex to "0", "-1" and ""
// this.$container.attr("tabindex", this.options.tabindex);
// if( this.options.rtl ) {
// this.$container.attr("DIR", "RTL").addClass("fancytree-rtl");
// // }else{
// // this.$container.attr("DIR", null).removeClass("fancytree-rtl");
// }
// if(this.options.aria){
// this.$container.attr("role", "tree");
// if( this.options.selectMode !== 1 ) {
// this.$container.attr("aria-multiselectable", true);
// }
// }
} | /******************************************************************************
* Fancytree
*/ | https://github.com/toblotron/praxis-ide/blob/b4f732c28f0280ead015094bce893a378a28bec2/lib/fancytree_dist/jquery.fancytree-all.js#L2632-L2724 | b4f732c28f0280ead015094bce893a378a28bec2 |
KCloud-Platform-IoT | github_2023 | KouShenhai | javascript | stretchSpansOverChange | function stretchSpansOverChange(doc, change) {
if (change.full) { return null }
var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
if (!oldFirst && !oldLast) { return null }
var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
// Get the spans that 'stick out' on both sides
var first = markedSpansBefore(oldFirst, startCh, isInsert);
var last = markedSpansAfter(oldLast, endCh, isInsert);
// Next, merge those two ends
var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
if (first) {
// Fix up .to properties of first
for (var i = 0; i < first.length; ++i) {
var span = first[i];
if (span.to == null) {
var found = getMarkedSpanFor(last, span.marker);
if (!found) { span.to = startCh; }
else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
}
}
}
if (last) {
// Fix up .from in last (or move them into first in case of sameLine)
for (var i$1 = 0; i$1 < last.length; ++i$1) {
var span$1 = last[i$1];
if (span$1.to != null) { span$1.to += offset; }
if (span$1.from == null) {
var found$1 = getMarkedSpanFor(first, span$1.marker);
if (!found$1) {
span$1.from = offset;
if (sameLine) { (first || (first = [])).push(span$1); }
}
} else {
span$1.from += offset;
if (sameLine) { (first || (first = [])).push(span$1); }
}
}
}
// Make sure we didn't create any zero-length spans
if (first) { first = clearEmptySpans(first); }
if (last && last != first) { last = clearEmptySpans(last); }
var newMarkers = [first];
if (!sameLine) {
// Fill gap with whole-line-spans
var gap = change.text.length - 2, gapMarkers;
if (gap > 0 && first)
{ for (var i$2 = 0; i$2 < first.length; ++i$2)
{ if (first[i$2].to == null)
{ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
for (var i$3 = 0; i$3 < gap; ++i$3)
{ newMarkers.push(gapMarkers); }
newMarkers.push(last);
}
return newMarkers
} | // Given a change object, compute the new set of marker spans that | https://github.com/KouShenhai/KCloud-Platform-IoT/blob/d10ccb3e93bdec47d529e858ec31585d794700ab/laokou-cloud/laokou-nacos/src/main/resources/static/console-ui/public/js/codemirror.js#L607-L665 | d10ccb3e93bdec47d529e858ec31585d794700ab |
kurento | github_2023 | Kurento | javascript | onerror | function onerror(error) {
if (error)
QUnit.pushFailure(error.message || error, error.stack);
QUnit.start();
} | /**
* Set an assert error and re-start the test so it can fail
*/ | https://github.com/Kurento/kurento/blob/b04c741488b60a10692f08d01e87b8bb08ef0300/clients/javascript/client/test/_common.js | b04c741488b60a10692f08d01e87b8bb08ef0300 |
openvpn-ui | github_2023 | d3vilh | javascript | isIndex | function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
} | /**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/ | https://github.com/d3vilh/openvpn-ui/blob/690f84df426c13ad4742b61fd23e52fcdc489aa0/swagger/swagger-ui.js#L16318-L16322 | 690f84df426c13ad4742b61fd23e52fcdc489aa0 |
nix-installer-action | github_2023 | DeterminateSystems | javascript | pipeResponseToStream | function pipeResponseToStream(response, output) {
return __awaiter(this, void 0, void 0, function* () {
const pipeline = util.promisify(stream.pipeline);
yield pipeline(response.message, output);
});
} | /**
* Pipes the body of a HTTP response to a stream
*
* @param response the HTTP response
* @param output the writable stream
*/ | https://github.com/DeterminateSystems/nix-installer-action/blob/a48face58194521af687ce7df4c802b1b558e743/dist/index.js#L814-L819 | a48face58194521af687ce7df4c802b1b558e743 |
nix-installer-action | github_2023 | DeterminateSystems | javascript | getOptions | function getOptions(copy) {
const result = {
followSymbolicLinks: true,
implicitDescendants: true,
omitBrokenSymbolicLinks: true
};
if (copy) {
if (typeof copy.followSymbolicLinks === 'boolean') {
result.followSymbolicLinks = copy.followSymbolicLinks;
core.debug(`followSymbolicLinks '${result.followSymbolicLinks}'`);
}
if (typeof copy.implicitDescendants === 'boolean') {
result.implicitDescendants = copy.implicitDescendants;
core.debug(`implicitDescendants '${result.implicitDescendants}'`);
}
if (typeof copy.omitBrokenSymbolicLinks === 'boolean') {
result.omitBrokenSymbolicLinks = copy.omitBrokenSymbolicLinks;
core.debug(`omitBrokenSymbolicLinks '${result.omitBrokenSymbolicLinks}'`);
}
}
return result;
} | /**
* Returns a copy with defaults filled in.
*/ | https://github.com/DeterminateSystems/nix-installer-action/blob/a48face58194521af687ce7df4c802b1b558e743/dist/index.js#L3570-L3591 | a48face58194521af687ce7df4c802b1b558e743 |
nix-installer-action | github_2023 | DeterminateSystems | javascript | HttpHeadersImpl.delete | delete(name) {
this._headersMap.delete(normalizeName(name));
} | /**
* Remove the header with the provided headerName.
* @param name - The name of the header to remove.
*/ | https://github.com/DeterminateSystems/nix-installer-action/blob/a48face58194521af687ce7df4c802b1b558e743/dist/index.js#L69795-L69797 | a48face58194521af687ce7df4c802b1b558e743 |
nix-installer-action | github_2023 | DeterminateSystems | javascript | defaultRetryPolicy | function defaultRetryPolicy(options = {}) {
var _a;
return {
name: exports.defaultRetryPolicyName,
sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], {
maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
}).sendRequest,
};
} | /**
* A policy that retries according to three strategies:
* - When the server sends a 429 response with a Retry-After header.
* - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
* - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
*/ | https://github.com/DeterminateSystems/nix-installer-action/blob/a48face58194521af687ce7df4c802b1b558e743/dist/index.js#L70980-L70988 | a48face58194521af687ce7df4c802b1b558e743 |
nix-installer-action | github_2023 | DeterminateSystems | javascript | tlsPolicy | function tlsPolicy(tlsSettings) {
return {
name: exports.tlsPolicyName,
sendRequest: async (req, next) => {
// Users may define a request tlsSettings, honor those over the client level one
if (!req.tlsSettings) {
req.tlsSettings = tlsSettings;
}
return next(req);
},
};
} | /**
* Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
*/ | https://github.com/DeterminateSystems/nix-installer-action/blob/a48face58194521af687ce7df4c802b1b558e743/dist/index.js#L71836-L71847 | a48face58194521af687ce7df4c802b1b558e743 |
nix-installer-action | github_2023 | DeterminateSystems | javascript | assertBoundFunction | function assertBoundFunction(value, message) {
if (!isBoundFunction(value)) {
throw new TypeError(message ?? typeErrorMessage('Function', value));
}
} | // eslint-disable-next-line @typescript-eslint/ban-types | https://github.com/DeterminateSystems/nix-installer-action/blob/a48face58194521af687ce7df4c802b1b558e743/dist/index.js#L76668-L76672 | a48face58194521af687ce7df4c802b1b558e743 |
ComfyUI | github_2023 | comfyanonymous | javascript | ScopeClass.update | update(captureContext) {
if (!captureContext) {
return this;
}
const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext;
const [scopeInstance, requestSession] = scopeToMerge instanceof Scope ? (
// eslint-disable-next-line deprecation/deprecation
[scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()]
) : isPlainObject$5(scopeToMerge) ? [captureContext, captureContext.requestSession] : [];
const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};
this._tags = { ...this._tags, ...tags };
this._extra = { ...this._extra, ...extra };
this._contexts = { ...this._contexts, ...contexts };
if (user && Object.keys(user).length) {
this._user = user;
}
if (level) {
this._level = level;
}
if (fingerprint.length) {
this._fingerprint = fingerprint;
}
if (propagationContext) {
this._propagationContext = propagationContext;
}
if (requestSession) {
this._requestSession = requestSession;
}
return this;
} | /**
* @inheritDoc
*/ | https://github.com/comfyanonymous/ComfyUI/blob/af93c8d1ee4be91f30ffd395ea6919e6f83923aa/web/assets/index-DqqhYDnY.js#L7979-L8008 | af93c8d1ee4be91f30ffd395ea6919e6f83923aa |
Digital-IDE | github_2023 | Digital-EDA | javascript | renderWaveDrom | function renderWaveDrom(id, json, style) {
const skin = selectSkin(style);
const renderObj = renderAny(id, json, skin);
let svgString = onmlStringify(renderObj);
// TODO: more elegant ? 这里是为了解决黑色模式下部分 rect 仍然是白色背景
svgString = replaceRectsWithCustomString(svgString, style);
return svgString;
} | /**
*
* @param {number} id
* @param {any} json
* @param {'dark' | 'light'} style
* @returns {string}
*/ | https://github.com/Digital-EDA/Digital-IDE/blob/2f90a87a1c9df236ee621e586d8e56ac0e7aaa57/resources/wavedrom/index.js#L34-L43 | 2f90a87a1c9df236ee621e586d8e56ac0e7aaa57 |
beginner-series | github_2023 | dotnet | javascript | computeStyleTests | function computeStyleTests() {
// This is a singleton, we need to execute it only once
if ( !div ) {
return;
}
container.style.cssText = "position:absolute;left:-11111px;width:60px;" +
"margin-top:1px;padding:0;border:0";
div.style.cssText =
"position:relative;display:block;box-sizing:border-box;overflow:scroll;" +
"margin:auto;border:1px;padding:1px;" +
"width:60%;top:1%";
documentElement.appendChild( container ).appendChild( div );
var divStyle = window.getComputedStyle( div );
pixelPositionVal = divStyle.top !== "1%";
// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12;
// Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
// Some styles come back with percentage values, even though they shouldn't
div.style.right = "60%";
pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36;
// Support: IE 9 - 11 only
// Detect misreporting of content dimensions for box-sizing:border-box elements
boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36;
// Support: IE 9 only
// Detect overflow:scroll screwiness (gh-3699)
// Support: Chrome <=64
// Don't get tricked when zoom affects offsetWidth (gh-4029)
div.style.position = "absolute";
scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12;
documentElement.removeChild( container );
// Nullify the div so it wouldn't be stored in the memory and
// it will also be a sign that checks already performed
div = null;
} | // Executing both pixelPosition & boxSizingReliable tests require only one layout | https://github.com/dotnet/beginner-series/blob/7094e2e5eed96c5a26d7aeef240a95f35201c063/Visual Studio/sample-code/RazorPagesCupcakes/wwwroot/lib/jquery/dist/jquery.js#L6439-L6481 | 7094e2e5eed96c5a26d7aeef240a95f35201c063 |
t3d.js | github_2023 | uinosoft | javascript | DynamicFont.dispose | dispose() {
this._fontAtlas.clear();
this._font.chars.length = 0;
} | /**
* Dispose the font data and atlas.
*/ | https://github.com/uinosoft/t3d.js/blob/b746a7f5c17a58c6711fe8ce71788301ad474363/examples/jsm/DynamicFont.js#L91-L94 | b746a7f5c17a58c6711fe8ce71788301ad474363 |
t3d.js | github_2023 | uinosoft | javascript | GLTFExporter.parse | parse(input, onDone, onError, options) {
const writer = new GLTFWriter();
const plugins = this.extensions.map(_ext => new _ext(writer));
writer.setPlugins(plugins);
writer.dracoOptions = this.dracoOptions;
writer.setDRACOExporter(this._dracoExporter);
writer.writeAsync(input, onDone, options).catch(onError);
} | /**
* Parse input root object(s) and generate GLTF output
* @param {Object3D or [Object3D]} input root object(s)
* @param {Function} onDone Callback on completed
* @param {Function} onError Callback on errors
* @param {Object} options options
*/ | https://github.com/uinosoft/t3d.js/blob/b746a7f5c17a58c6711fe8ce71788301ad474363/examples/jsm/exporters/GLTFExporter.js#L60-L71 | b746a7f5c17a58c6711fe8ce71788301ad474363 |
t3d.js | github_2023 | uinosoft | javascript | RenderStates.updateCamera | updateCamera(camera) {
const sceneData = this.scene;
const cameraData = this.camera;
const projectionMatrix = camera.projectionMatrix;
let cameraNear = 0, cameraFar = 0;
if (_isPerspectiveMatrix(projectionMatrix)) {
cameraNear = projectionMatrix.elements[14] / (projectionMatrix.elements[10] - 1);
cameraFar = projectionMatrix.elements[14] / (projectionMatrix.elements[10] + 1);
} else {
cameraNear = (projectionMatrix.elements[14] + 1) / projectionMatrix.elements[10];
cameraFar = (projectionMatrix.elements[14] - 1) / projectionMatrix.elements[10];
}
cameraData.near = cameraNear;
cameraData.far = cameraFar;
if (sceneData.logarithmicDepthBuffer) {
cameraData.logDepthCameraNear = cameraNear;
cameraData.logDepthBufFC = 2.0 / (Math.log(cameraFar - cameraNear + 1.0) * Math.LOG2E);
} else {
cameraData.logDepthCameraNear = 0;
cameraData.logDepthBufFC = 0;
}
cameraData.position.setFromMatrixPosition(camera.worldMatrix);
if (sceneData.useAnchorMatrix) {
cameraData.position.applyMatrix4(sceneData.anchorMatrixInverse);
}
cameraData.viewMatrix.copy(camera.viewMatrix);
if (sceneData.useAnchorMatrix) {
cameraData.viewMatrix.multiply(sceneData.anchorMatrix);
}
cameraData.projectionMatrix.copy(projectionMatrix);
cameraData.projectionViewMatrix.copy(projectionMatrix).multiply(cameraData.viewMatrix);
cameraData.rect.copy(camera.rect);
cameraData.version++;
this.gammaFactor = camera.gammaFactor;
this.outputEncoding = camera.outputEncoding;
} | /**
* Update render states about camera.
* @param {t3d.Camera}
*/ | https://github.com/uinosoft/t3d.js/blob/b746a7f5c17a58c6711fe8ce71788301ad474363/src/render/RenderStates.js#L44-L88 | b746a7f5c17a58c6711fe8ce71788301ad474363 |
t3d.js | github_2023 | uinosoft | javascript | ThinRenderer.updateRenderTargetMipmap | updateRenderTargetMipmap(renderTarget) {} | /**
* Reads the pixel data from the current render target into the provided buffer.
* The Renderer.asyncReadPixel property determines whether this operation is synchronous or asynchronous.
* To maintain consistency, this method always returns a Promise object.
* @param {Number} x - The x coordinate of the rectangle to read from.
* @param {Number} y - The y coordinate of the rectangle to read from.
* @param {Number} width - The width of the rectangle to read from.
* @param {Number} height - The height of the rectangle to read from.
* @param {TypedArray} buffer Uint8Array is the only destination type supported in all cases, other types are renderTarget and platform dependent.
* @return {Promise<TypedArray>} A promise that resolves with the passed in buffer after it has been filled with the pixel data.
*/ | https://github.com/uinosoft/t3d.js/blob/b746a7f5c17a58c6711fe8ce71788301ad474363/src/render/ThinRenderer.js#L191-L191 | b746a7f5c17a58c6711fe8ce71788301ad474363 |
node-sandbox | github_2023 | bnmgh1 | javascript | random | function random(sd) {
var d, e, k, n,
i = 0,
r = new this(1),
rd = [];
if (sd === void 0) sd = this.precision;
else checkInt32(sd, 1, MAX_DIGITS);
k = Math.ceil(sd / LOG_BASE);
if (!this.crypto) {
for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
// Browsers supporting crypto.getRandomValues.
} else if (crypto.getRandomValues) {
d = crypto.getRandomValues(new Uint32Array(k));
for (; i < k;) {
n = d[i];
// 0 <= n < 4294967296
// Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
if (n >= 4.29e9) {
d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
} else {
// 0 <= n <= 4289999999
// 0 <= (n % 1e7) <= 9999999
rd[i++] = n % 1e7;
}
}
// Node.js supporting crypto.randomBytes.
} else if (crypto.randomBytes) {
// buffer
d = crypto.randomBytes(k *= 4);
for (; i < k;) {
// 0 <= n < 2147483648
n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
// Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
if (n >= 2.14e9) {
crypto.randomBytes(4).copy(d, i);
} else {
// 0 <= n <= 2139999999
// 0 <= (n % 1e7) <= 9999999
rd.push(n % 1e7);
i += 4;
}
}
i = k / 4;
} else {
throw Error(cryptoUnavailable);
}
k = rd[--i];
sd %= LOG_BASE;
// Convert trailing digits to zeros according to sd.
if (k && sd) {
n = mathpow(10, LOG_BASE - sd);
rd[i] = (k / n | 0) * n;
}
// Remove trailing words which are zero.
for (; rd[i] === 0; i--) rd.pop();
// Zero?
if (i < 0) {
e = 0;
rd = [0];
} else {
e = -1;
// Remove leading words which are zero and adjust exponent accordingly.
for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
// Count the digits of the first word of rd to determine leading zeros.
for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
// Adjust the exponent for leading zeros of the first word of rd.
if (k < LOG_BASE) e -= LOG_BASE - k;
}
r.e = e;
r.d = rd;
return r;
} | /*
* Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
* `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
* are produced).
*
* [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
*
*/ | https://github.com/bnmgh1/node-sandbox/blob/e39d2a8e5ca530039e03055f94199f22c3248b0a/node_modules/decimal.js/decimal.js#L4659-L4753 | e39d2a8e5ca530039e03055f94199f22c3248b0a |
node-sandbox | github_2023 | bnmgh1 | javascript | SelectionImpl.anchorNode | get anchorNode() {
const anchor = this._anchor;
return anchor ? anchor.node : null;
} | // https://w3c.github.io/selection-api/#dom-selection-anchornode | https://github.com/bnmgh1/node-sandbox/blob/e39d2a8e5ca530039e03055f94199f22c3248b0a/node_modules/jsdom/lib/jsdom/living/selection/Selection-impl.js#L32-L35 | e39d2a8e5ca530039e03055f94199f22c3248b0a |
node-sandbox | github_2023 | bnmgh1 | javascript | _unmask | function _unmask(buffer, mask) {
for (let i = 0; i < buffer.length; i++) {
buffer[i] ^= mask[i & 3];
}
} | /**
* Unmasks a buffer using the given mask.
*
* @param {Buffer} buffer The buffer to unmask
* @param {Buffer} mask The mask to use
* @public
*/ | https://github.com/bnmgh1/node-sandbox/blob/e39d2a8e5ca530039e03055f94199f22c3248b0a/node_modules/ws/lib/buffer-util.js#L58-L62 | e39d2a8e5ca530039e03055f94199f22c3248b0a |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | createStrictSyntaxError | function createStrictSyntaxError (str, char) {
var index = str.indexOf(char)
var partial = index !== -1
? str.substring(0, index) + '#'
: ''
try {
JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
} catch (e) {
return normalizeJsonSyntaxError(e, {
message: e.message.replace('#', char),
stack: e.stack
})
}
} | /**
* Create strict violation syntax error matching native error.
*
* @param {string} str
* @param {string} char
* @return {Error}
* @private
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/6.EXPRESS-JS/File-Uploads2/1.Images-Upload/node_modules/body-parser/lib/types/json.js#L153-L167 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | mapCacheHas | function mapCacheHas(key) {
return getMapData(this, key).has(key);
} | /**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/6.EXPRESS-JS/File-Uploads2/1.Images-Upload/node_modules/cloudinary-core/cloudinary-core-shrinkwrap.js#L3540-L3542 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | sourcetag_typeof | function sourcetag_typeof(obj) { "@babel/helpers - typeof"; return sourcetag_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, sourcetag_typeof(obj); } | // CONCATENATED MODULE: ./src/tags/sourcetag.js | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/6.EXPRESS-JS/File-Uploads2/1.Images-Upload/node_modules/cloudinary-core/cloudinary-core-shrinkwrap.js#L11348-L11348 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | lazyClone | function lazyClone() {
var result = new LazyWrapper(this.__wrapped__);
result.__actions__ = copyArray(this.__actions__);
result.__dir__ = this.__dir__;
result.__filtered__ = this.__filtered__;
result.__iteratees__ = copyArray(this.__iteratees__);
result.__takeCount__ = this.__takeCount__;
result.__views__ = copyArray(this.__views__);
return result;
} | /**
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/6.EXPRESS-JS/File-Uploads2/1.Images-Upload/node_modules/lodash/_lazyClone.js#L12-L21 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | baseLt | function baseLt(value, other) {
return value < other;
} | /**
* The base implementation of `_.lt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/6.EXPRESS-JS/File-Uploads2/1.Images-Upload/node_modules/lodash/lodash.js#L3568-L3570 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | status | function status (code) {
if (typeof code === 'number') {
return getStatusMessage(code)
}
if (typeof code !== 'string') {
throw new TypeError('code must be a number or string')
}
// '403'
var n = parseInt(code, 10)
if (!isNaN(n)) {
return getStatusMessage(n)
}
return getStatusCode(code)
} | /**
* Get the status code.
*
* Given a number, this will throw if it is not a known status
* code, otherwise the code will be returned. Given a string,
* the string will be parsed for a number and return the code
* if valid, otherwise will lookup the code assuming this is
* the status message.
*
* @param {string|number} code
* @returns {number}
* @public
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/6.EXPRESS-JS/File-Uploads2/1.Images-Upload/node_modules/statuses/index.js#L130-L146 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | useColors | function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
} | /**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/PROJECTS/AI-PROJECTS/DALLE-3-IMAGE-GENERATOR/backend/node_modules/debug/src/browser.js#L39-L57 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | baseXor | function baseXor(arrays, iteratee, comparator) {
var length = arrays.length;
if (length < 2) {
return length ? baseUniq(arrays[0]) : [];
}
var index = -1,
result = Array(length);
while (++index < length) {
var array = arrays[index],
othIndex = -1;
while (++othIndex < length) {
if (othIndex != index) {
result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
}
}
}
return baseUniq(baseFlatten(result, 1), iteratee, comparator);
} | /**
* The base implementation of methods like `_.xor`, without support for
* iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of values.
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/PROJECTS/AI-PROJECTS/DALLE-3-IMAGE-GENERATOR/backend/node_modules/lodash/_baseXor.js#L15-L34 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | createCurry | function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
} | /**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/PROJECTS/AI-PROJECTS/DALLE-3-IMAGE-GENERATOR/backend/node_modules/lodash/_createCurry.js#L18-L44 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | Collection.namespace | get namespace() {
return this.fullNamespace.toString();
} | /**
* The namespace of this collection, in the format `${this.dbName}.${this.collectionName}`
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/PROJECTS/AI-PROJECTS/DALLE-3-IMAGE-GENERATOR/backend/node_modules/mongodb/lib/collection.js#L95-L97 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | ServerSession.hasTimedOut | hasTimedOut(sessionTimeoutMinutes) {
// Take the difference of the lastUse timestamp and now, which will result in a value in
// milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes`
const idleTimeMinutes = Math.round((((0, utils_1.calculateDurationInMs)(this.lastUse) % 86400000) % 3600000) / 60000);
return idleTimeMinutes > sessionTimeoutMinutes - 1;
} | /**
* Determines if the server session has timed out.
*
* @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes"
*/ | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/PROJECTS/AI-PROJECTS/DALLE-3-IMAGE-GENERATOR/backend/node_modules/mongodb/lib/sessions.js#L555-L560 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
Full-Stack-Web-Development-Bootcamp-Course | github_2023 | tweneboah | javascript | checkCharacter | function checkCharacter(inputChar, targetChar) {
if (inputChar !== targetChar) {
errors++;
//play error sound
new Audio("/error.mp3").play();
return false;
} else {
return true;
}
} | //Function to check typed character | https://github.com/tweneboah/Full-Stack-Web-Development-Bootcamp-Course/blob/6880262d9aa3d9e22e2a7910d7b7e727de75f590/PROJECTS/Typing-test-project-final/script.js#L46-L55 | 6880262d9aa3d9e22e2a7910d7b7e727de75f590 |
mox | github_2023 | mjl- | javascript | Client.DNSBLStatus | async DNSBLStatus() {
const fn = "DNSBLStatus";
const paramTypes = [];
const returnTypes = [["{}", "{}", "string"], ["[]", "Domain"], ["[]", "Domain"]];
const params = [];
return await _sherpaCall(this.baseURL, this.authState, { ...this.options }, paramTypes, returnTypes, fn, params);
} | // TLSRPTSummaries returns a summary of received TLS reports overlapping with | https://github.com/mjl-/mox/blob/93b627ceab9b90cb3669d0adc5d6dc208181fc7a/webadmin/admin.js#L714-L720 | 93b627ceab9b90cb3669d0adc5d6dc208181fc7a |
JS-Tap | github_2023 | hoodoer | javascript | innerMode | function innerMode(mode, state) {
var info;
while (mode.innerMode) {
info = mode.innerMode(state);
if (!info || info.mode == mode) { break }
state = info.state;
mode = info.mode;
}
return info || {mode: mode, state: state}
} | // Given a mode and a state (for that mode), find the inner mode and | https://github.com/hoodoer/JS-Tap/blob/13e455a3c5c101cac6a573677bf173b6eacc0fa4/static/node_modules/codemirror/addon/runmode/runmode-standalone.js#L208-L217 | 13e455a3c5c101cac6a573677bf173b6eacc0fa4 |
JS-Tap | github_2023 | hoodoer | javascript | drawSelectionCursor | function drawSelectionCursor(cm, head, output) {
var pos = cursorCoords(cm, 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 (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
var charPos = charCoords(cm, head, "div", null, null);
var width = charPos.right - charPos.left;
cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "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 | https://github.com/hoodoer/JS-Tap/blob/13e455a3c5c101cac6a573677bf173b6eacc0fa4/static/node_modules/codemirror/lib/codemirror.js#L3192-L3214 | 13e455a3c5c101cac6a573677bf173b6eacc0fa4 |
JS-Tap | github_2023 | hoodoer | javascript | Command.requiredOption | requiredOption(flags, description, fn, defaultValue) {
return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
} | /**
* Add a required option which must have a value after parsing. This usually means
* the option must be specified on the command line. (Otherwise the same as .option().)
*
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
*
* @param {string} flags
* @param {string} [description]
* @param {Function|*} [fn] - custom option processing function or default value
* @param {*} [defaultValue]
* @return {Command} `this` command for chaining
*/ | https://github.com/hoodoer/JS-Tap/blob/13e455a3c5c101cac6a573677bf173b6eacc0fa4/static/node_modules/commander/lib/command.js#L674-L676 | 13e455a3c5c101cac6a573677bf173b6eacc0fa4 |
webgpu-devtools | github_2023 | takahirox | javascript | paddingTop | function paddingTop(display) {return display.lineSpace.offsetTop} | // POSITION MEASUREMENT | https://github.com/takahirox/webgpu-devtools/blob/cd7b11a54ee23df592347153d523da885e9bc975/extensions/panel.js#L2320-L2320 | cd7b11a54ee23df592347153d523da885e9bc975 |
android-qinglong | github_2023 | FuShengPing | javascript | visualLineContinued | function visualLineContinued(line) {
var merged, lines;
while (merged = collapsedSpanAtEnd(line)) {
line = merged.find(1, true).line
;(lines || (lines = [])).push(line);
}
return lines
} | // Returns an array of logical lines that continue the visual line | https://github.com/FuShengPing/android-qinglong/blob/f1e50c9279ed7081f6dcd882accdbb525e5ed5fc/app/src/main/assets/web/editor/codemirror.js#L1572-L1579 | f1e50c9279ed7081f6dcd882accdbb525e5ed5fc |
CreArts-Obsidian-Vault | github_2023 | CreArts-Community | javascript | Duration.reconfigure | reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) {
const loc = this.loc.clone({ locale, numberingSystem });
const opts = { loc, matrix, conversionAccuracy };
return clone$1(this, opts);
} | /**
* "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration.
* @example dur.reconfigure({ locale: 'en-GB' })
* @return {Duration}
*/ | https://github.com/CreArts-Community/CreArts-Obsidian-Vault/blob/5092f39680b1a13289962114f9d38622fe652551/.obsidian/plugins/dataview/main.js#L3195-L3199 | 5092f39680b1a13289962114f9d38622fe652551 |
CreArts-Obsidian-Vault | github_2023 | CreArts-Community | javascript | Duration.shiftToAll | shiftToAll() {
if (!this.isValid) return this;
return this.shiftTo(
"years",
"months",
"weeks",
"days",
"hours",
"minutes",
"seconds",
"milliseconds"
);
} | /**
* Shift this Duration to all available units.
* Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds")
* @return {Duration}
*/ | https://github.com/CreArts-Community/CreArts-Obsidian-Vault/blob/5092f39680b1a13289962114f9d38622fe652551/.obsidian/plugins/dataview/main.js#L3306-L3318 | 5092f39680b1a13289962114f9d38622fe652551 |
CreArts-Obsidian-Vault | github_2023 | CreArts-Community | javascript | DateTime.second | get second() {
return this.isValid ? this.c.second : NaN;
} | /**
* Get the hour of the day (0-23).
* @example DateTime.local(2017, 5, 25, 9).hour //=> 9
* @type {number}
*/ | https://github.com/CreArts-Community/CreArts-Obsidian-Vault/blob/5092f39680b1a13289962114f9d38622fe652551/.obsidian/plugins/dataview/main.js#L6023-L6025 | 5092f39680b1a13289962114f9d38622fe652551 |
CreArts-Obsidian-Vault | github_2023 | CreArts-Community | javascript | DateTime.until | until(otherDateTime) {
return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
} | /**
* Returns a JavaScript object with this DateTime's year, month, day, and so on.
* @param opts - options for generating the object
* @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
* @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
* @return {Object}
*/ | https://github.com/CreArts-Community/CreArts-Obsidian-Vault/blob/5092f39680b1a13289962114f9d38622fe652551/.obsidian/plugins/dataview/main.js#L6839-L6841 | 5092f39680b1a13289962114f9d38622fe652551 |
CreArts-Obsidian-Vault | github_2023 | CreArts-Community | javascript | InlineWidget.toDOM | toDOM(view) {
this.el.addClasses(this.cssClasses);
return this.el;
} | // to prevent redraws when the editor updates. | https://github.com/CreArts-Community/CreArts-Obsidian-Vault/blob/5092f39680b1a13289962114f9d38622fe652551/.obsidian/plugins/dataview/main.js#L19172-L19175 | 5092f39680b1a13289962114f9d38622fe652551 |
CreArts-Obsidian-Vault | github_2023 | CreArts-Community | javascript | compileGeneralSelector | function compileGeneralSelector(next, selector, options, context, compileToken) {
var adapter = options.adapter, equals = options.equals;
switch (selector.type) {
case css_what_1.SelectorType.PseudoElement: {
throw new Error("Pseudo-elements are not supported by css-select");
}
case css_what_1.SelectorType.ColumnCombinator: {
throw new Error("Column combinators are not yet supported by css-select");
}
case css_what_1.SelectorType.Attribute: {
if (selector.namespace != null) {
throw new Error("Namespaced attributes are not yet supported by css-select");
}
if (!options.xmlMode || options.lowerCaseAttributeNames) {
selector.name = selector.name.toLowerCase();
}
return attributes.attributeRules[selector.action](next, selector, options);
}
case css_what_1.SelectorType.Pseudo: {
return (0, pseudoSelectors.compilePseudoSelector)(next, selector, options, context, compileToken);
}
// Tags
case css_what_1.SelectorType.Tag: {
if (selector.namespace != null) {
throw new Error("Namespaced tag names are not yet supported by css-select");
}
var name_1 = selector.name;
if (!options.xmlMode || options.lowerCaseTags) {
name_1 = name_1.toLowerCase();
}
return function tag(elem) {
return adapter.getName(elem) === name_1 && next(elem);
};
}
// Traversal
case css_what_1.SelectorType.Descendant: {
if (options.cacheResults === false ||
typeof WeakSet === "undefined") {
return function descendant(elem) {
var current = elem;
while ((current = getElementParent(current, adapter))) {
if (next(current)) {
return true;
}
}
return false;
};
}
// @ts-expect-error `ElementNode` is not extending object
var isFalseCache_1 = new WeakSet();
return function cachedDescendant(elem) {
var current = elem;
while ((current = getElementParent(current, adapter))) {
if (!isFalseCache_1.has(current)) {
if (adapter.isTag(current) && next(current)) {
return true;
}
isFalseCache_1.add(current);
}
}
return false;
};
}
case "_flexibleDescendant": {
// Include element itself, only used while querying an array
return function flexibleDescendant(elem) {
var current = elem;
do {
if (next(current))
return true;
} while ((current = getElementParent(current, adapter)));
return false;
};
}
case css_what_1.SelectorType.Parent: {
return function parent(elem) {
return adapter
.getChildren(elem)
.some(function (elem) { return adapter.isTag(elem) && next(elem); });
};
}
case css_what_1.SelectorType.Child: {
return function child(elem) {
var parent = adapter.getParent(elem);
return parent != null && adapter.isTag(parent) && next(parent);
};
}
case css_what_1.SelectorType.Sibling: {
return function sibling(elem) {
var siblings = adapter.getSiblings(elem);
for (var i = 0; i < siblings.length; i++) {
var currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling) && next(currentSibling)) {
return true;
}
}
return false;
};
}
case css_what_1.SelectorType.Adjacent: {
if (adapter.prevElementSibling) {
return function adjacent(elem) {
var previous = adapter.prevElementSibling(elem);
return previous != null && next(previous);
};
}
return function adjacent(elem) {
var siblings = adapter.getSiblings(elem);
var lastElement;
for (var i = 0; i < siblings.length; i++) {
var currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling)) {
lastElement = currentSibling;
}
}
return !!lastElement && next(lastElement);
};
}
case css_what_1.SelectorType.Universal: {
if (selector.namespace != null && selector.namespace !== "*") {
throw new Error("Namespaced universal selectors are not yet supported by css-select");
}
return next;
}
}
} | /*
* All available rules
*/ | https://github.com/CreArts-Community/CreArts-Obsidian-Vault/blob/5092f39680b1a13289962114f9d38622fe652551/.obsidian/plugins/simple-embeds/main.js#L6158-L6287 | 5092f39680b1a13289962114f9d38622fe652551 |
setup-micromamba | github_2023 | mamba-org | javascript | isBlob | function isBlob(x) {
return typeof x.stream === "function";
} | // node_modules/.pnpm/@azure+core-rest-pipeline@1.18.1/node_modules/@azure/core-rest-pipeline/dist/esm/util/typeGuards.js | https://github.com/mamba-org/setup-micromamba/blob/59bcdbae779c639f869cc8e3b223f36692af05c2/dist/post.js#L25942-L25944 | 59bcdbae779c639f869cc8e3b223f36692af05c2 |
embyExternalUrl | github_2023 | bpking1 | javascript | getDisableDocs | function getDisableDocs(r) {
const value = nginxConfig.disableDocs
&& !ngx.shared["tmpDict"].get("opendocs");
// r.log(`getDisableDocs: ${value}`);
return value;
} | // for js_set | https://github.com/bpking1/embyExternalUrl/blob/da18efe0009453c5ae198fc3cf44b84c6ee965f5/emby2Alist/nginx/conf.d/config/constant-nginx.js#L11-L16 | da18efe0009453c5ae198fc3cf44b84c6ee965f5 |
chartello | github_2023 | chartello | javascript | checkOffset | function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
} | /*
* Need to make sure that buffer isn't trying to write out of bounds.
*/ | https://github.com/chartello/chartello/blob/755b5ecf6094619da88ebe2e3e35a852de528036/public/js/app.js#L23686-L23689 | 755b5ecf6094619da88ebe2e3e35a852de528036 |
iMES-Factory | github_2023 | zmrid | javascript | toType | function toType(obj) {
return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase();
} | // Shoutout AngusCroll (https://goo.gl/pxwQGp) | https://github.com/zmrid/iMES-Factory/blob/d301552bd0e953882ea0b2162c0e17b36dd3a2a9/iMES.Net/iMES.WebApi/wwwroot/lib/bootstrap/dist/js/bootstrap.bundle.js#L86-L88 | d301552bd0e953882ea0b2162c0e17b36dd3a2a9 |
iMES-Factory | github_2023 | zmrid | javascript | get | function get (url, param, loading, config) {
showLoading(loading);
axios.defaults.headers[_Authorization] = getToken();
return new Promise((resolve, reject) => {
axios.get(url, config)
.then(response => {
resolve(response.data)
}, err => {
reject(err)
})
.catch((error) => {
reject(error)
})
})
} | //=true异步请求时会显示遮罩层,=字符串,异步请求时遮罩层显示当前字符串 | https://github.com/zmrid/iMES-Factory/blob/d301552bd0e953882ea0b2162c0e17b36dd3a2a9/iMES.Vue3/src/api/http.js#L138-L152 | d301552bd0e953882ea0b2162c0e17b36dd3a2a9 |
3x-ui | github_2023 | MHSanaei | javascript | includes | function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
} | /**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/ | https://github.com/MHSanaei/3x-ui/blob/49bfff9fa5a6acb50c8f51710a3e4005daf0ca32/web/assets/codemirror/jshint.js#L10885-L10896 | 49bfff9fa5a6acb50c8f51710a3e4005daf0ca32 |
3x-ui | github_2023 | MHSanaei | javascript | isValidArrayIndex | function isValidArrayIndex(val) {
const n = parseFloat(String(val));
return n >= 0 && Math.floor(n) === n && isFinite(val);
} | /**
* Check if val is a valid array index.
*/ | https://github.com/MHSanaei/3x-ui/blob/49bfff9fa5a6acb50c8f51710a3e4005daf0ca32/web/assets/vue/vue.common.dev.js#L65-L68 | 49bfff9fa5a6acb50c8f51710a3e4005daf0ca32 |
3x-ui | github_2023 | MHSanaei | javascript | defineReactive | function defineReactive(obj, key, val, customSetter, shallow, mock, observeEvenIfShallow = false) {
const dep = new Dep();
const property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return;
}
// cater for pre-defined getter/setters
const getter = property && property.get;
const setter = property && property.set;
if ((!getter || setter) &&
(val === NO_INITIAL_VALUE || arguments.length === 2)) {
val = obj[key];
}
let childOb = shallow ? val && val.__ob__ : observe(val, false, mock);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter() {
const value = getter ? getter.call(obj) : val;
if (Dep.target) {
{
dep.depend({
target: obj,
type: "get" /* TrackOpTypes.GET */,
key
});
}
if (childOb) {
childOb.dep.depend();
if (isArray(value)) {
dependArray(value);
}
}
}
return isRef(value) && !shallow ? value.value : value;
},
set: function reactiveSetter(newVal) {
const value = getter ? getter.call(obj) : val;
if (!hasChanged(value, newVal)) {
return;
}
if (customSetter) {
customSetter();
}
if (setter) {
setter.call(obj, newVal);
}
else if (getter) {
// #7981: for accessor properties without setter
return;
}
else if (!shallow && isRef(value) && !isRef(newVal)) {
value.value = newVal;
return;
}
else {
val = newVal;
}
childOb = shallow ? newVal && newVal.__ob__ : observe(newVal, false, mock);
{
dep.notify({
type: "set" /* TriggerOpTypes.SET */,
target: obj,
key,
newValue: newVal,
oldValue: value
});
}
}
});
return dep;
} | /**
* Define a reactive property on an Object.
*/ | https://github.com/MHSanaei/3x-ui/blob/49bfff9fa5a6acb50c8f51710a3e4005daf0ca32/web/assets/vue/vue.common.dev.js#L940-L1011 | 49bfff9fa5a6acb50c8f51710a3e4005daf0ca32 |
3x-ui | github_2023 | MHSanaei | javascript | processSlotOutlet | function processSlotOutlet(el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if (el.key) {
warn("`key` does not work on <slot> because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead.", getRawBindingAttr(el, 'key'));
}
}
} | // handle <slot/> outlets | https://github.com/MHSanaei/3x-ui/blob/49bfff9fa5a6acb50c8f51710a3e4005daf0ca32/web/assets/vue/vue.js#L10389-L10398 | 49bfff9fa5a6acb50c8f51710a3e4005daf0ca32 |
an-codeAI | github_2023 | sparrow-js | javascript | fileFlagLocal2Remote | function fileFlagLocal2Remote(flag) {
return {
type: SpecialArgType.FILEFLAG,
flagStr: flag.getFlagString()
};
} | /**
* @hidden
*/ | https://github.com/sparrow-js/an-codeAI/blob/a6184f39fb36ad9cda9857f45a1226acc3cdd0b9/public/static/browserfs11/browserfs.js#L10937-L10942 | a6184f39fb36ad9cda9857f45a1226acc3cdd0b9 |
an-codeAI | github_2023 | sparrow-js | javascript | conditionalGroup | function conditionalGroup(states, opts) {
return group(states[0], Object.assign({}, opts, {
expandedStates: states
}));
} | /**
* @param {Doc[]} states
* @param {object} [opts] - TBD ???
* @returns Doc
*/ | https://github.com/sparrow-js/an-codeAI/blob/a6184f39fb36ad9cda9857f45a1226acc3cdd0b9/public/static/js/prettier/2.0.5/standalone.js#L14038-L14042 | a6184f39fb36ad9cda9857f45a1226acc3cdd0b9 |
projectshut | github_2023 | priyankarpal | javascript | RegExpRoute.constructor | constructor(regExp, handler, method) {
{
finalAssertExports.isInstance(regExp, RegExp, {
moduleName: 'workbox-routing',
className: 'RegExpRoute',
funcName: 'constructor',
paramName: 'pattern'
});
}
const match = ({
url
}) => {
const result = regExp.exec(url.href);
// Return immediately if there's no match.
if (!result) {
return;
}
// Require that the match start at the first character in the URL string
// if it's a cross-origin request.
// See https://github.com/GoogleChrome/workbox/issues/281 for the context
// behind this behavior.
if (url.origin !== location.origin && result.index !== 0) {
{
logger.debug(`The regular expression '${regExp.toString()}' only partially matched ` + `against the cross-origin URL '${url.toString()}'. RegExpRoute's will only ` + `handle cross-origin requests if they match the entire URL.`);
}
return;
}
// If the route matches, but there aren't any capture groups defined, then
// this will return [], which is truthy and therefore sufficient to
// indicate a match.
// If there are capture groups, then it will return their values.
return result.slice(1);
};
super(match, handler, method);
} | /**
* If the regular expression contains
* [capture groups]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references},
* the captured values will be passed to the
* {@link workbox-routing~handlerCallback} `params`
* argument.
*
* @param {RegExp} regExp The regular expression to match against URLs.
* @param {workbox-routing~handlerCallback} handler A callback
* function that returns a Promise resulting in a Response.
* @param {string} [method='GET'] The HTTP method to match the Route
* against.
*/ | https://github.com/priyankarpal/projectshut/blob/3b38850653a70809ee8b13bd452208454daa9d79/public/workbox-8817a5e5.js#L616-L650 | 3b38850653a70809ee8b13bd452208454daa9d79 |
LibreChat | github_2023 | danny-avila | javascript | AnthropicClient.getStreamUsage | getStreamUsage() {
const inputUsage = this.message_start?.message?.usage ?? {};
const outputUsage = this.message_delta?.usage ?? {};
return Object.assign({}, inputUsage, outputUsage);
} | /**
* Get stream usage as returned by this client's API response.
* @returns {AnthropicStreamUsage} The stream usage object.
*/ | https://github.com/danny-avila/LibreChat/blob/52a6de2aa756564ffe12114ebfce0e7f93ea125c/api/app/clients/AnthropicClient.js#L195-L199 | 52a6de2aa756564ffe12114ebfce0e7f93ea125c |
transformers.js | github_2023 | huggingface | javascript | PyAnnoteFeatureExtractor.samples_to_frames | samples_to_frames(samples) {
return ((samples - this.config.offset) / this.config.step);
} | /**
* NOTE: Can return fractional values. `Math.ceil` will ensure correct value.
* @param {number} samples The number of frames in the audio.
* @returns {number} The number of frames in the audio.
*/ | https://github.com/huggingface/transformers.js/blob/829ace02044ba19ff9fa0293b4b975f1046cb6de/src/models/pyannote/feature_extraction_pyannote.js#L34-L36 | 829ace02044ba19ff9fa0293b4b975f1046cb6de |
ChatGPT-CodeReview | github_2023 | anc95 | javascript | getNodeRequestOptions$2 | function getNodeRequestOptions$2(request) {
const parsedURL = request[INTERNALS$2$2].parsedURL;
const headers = new Headers$2(request[INTERNALS$2$2].headers);
// fetch step 1.3
if (!headers.has('Accept')) {
headers.set('Accept', '*/*');
}
// Basic fetch
if (!parsedURL.protocol || !parsedURL.hostname) {
throw new TypeError('Only absolute URLs are supported');
}
if (!/^https?:$/.test(parsedURL.protocol)) {
throw new TypeError('Only HTTP(S) protocols are supported');
}
if (request.signal && request.body instanceof Stream$2.Readable && !streamDestructionSupported$1) {
throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
}
// HTTP-network-or-cache fetch steps 2.4-2.7
let contentLengthValue = null;
if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
contentLengthValue = '0';
}
if (request.body != null) {
const totalBytes = getTotalBytes$2(request);
if (typeof totalBytes === 'number') {
contentLengthValue = String(totalBytes);
}
}
if (contentLengthValue) {
headers.set('Content-Length', contentLengthValue);
}
// HTTP-network-or-cache fetch step 2.11
if (!headers.has('User-Agent')) {
headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
}
// HTTP-network-or-cache fetch step 2.15
if (request.compress && !headers.has('Accept-Encoding')) {
headers.set('Accept-Encoding', 'gzip,deflate');
}
let agent = request.agent;
if (typeof agent === 'function') {
agent = agent(parsedURL);
}
if (!headers.has('Connection') && !agent) {
headers.set('Connection', 'close');
}
// HTTP-network fetch step 4.2
// chunked encoding is handled by Node.js
return Object.assign({}, parsedURL, {
method: request.method,
headers: exportNodeCompatibleHeaders$1(headers),
agent
});
} | /**
* Convert a Request to Node.js http request options.
*
* @param Request A Request instance
* @return Object The options object to be passed to http.request
*/ | https://github.com/anc95/ChatGPT-CodeReview/blob/ca9b6722ab7d015b71fe12c02ed24ac855b5d13a/action/github-action.js#L133633-L133697 | ca9b6722ab7d015b71fe12c02ed24ac855b5d13a |
ChatGPT-CodeReview | github_2023 | anc95 | javascript | parseipNotation | function parseipNotation (note) {
var pos = note.lastIndexOf('/');
var str = pos !== -1
? note.substring(0, pos)
: note;
if (!isip(str)) {
throw new TypeError('invalid IP address: ' + str)
}
var ip = parseip(str);
if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) {
// Store as IPv4
ip = ip.toIPv4Address();
}
var max = ip.kind() === 'ipv6'
? 128
: 32;
var range = pos !== -1
? note.substring(pos + 1, note.length)
: null;
if (range === null) {
range = max;
} else if (DIGIT_REGEXP.test(range)) {
range = parseInt(range, 10);
} else if (ip.kind() === 'ipv4' && isip(range)) {
range = parseNetmask(range);
} else {
range = null;
}
if (range <= 0 || range > max) {
throw new TypeError('invalid range on address: ' + note)
}
return [ip, range]
} | /**
* Parse IP notation string into range subnet.
*
* @param {String} note
* @private
*/ | https://github.com/anc95/ChatGPT-CodeReview/blob/ca9b6722ab7d015b71fe12c02ed24ac855b5d13a/action/github-action.js#L179070-L179110 | ca9b6722ab7d015b71fe12c02ed24ac855b5d13a |
FanSky_Qs | github_2023 | AFanSKyQs | javascript | getTeyvatData | async function getTeyvatData (TBody, type = 'single') {
const apiMap = {
single: 'https://api.lelaer.com/ys/getDamageResult.php',
team: 'https://api.lelaer.com/ys/getTeamResult.php'
}
try {
const response = await fetch(apiMap[type], {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers // 假设您已经定义了 `headers` 对象
},
body: JSON.stringify(TBody),
timeout: 15000
})
const resJson = await response.json()
return resJson
} catch (error) {
console.error('提瓦特小助手接口无法访问或返回错误', error)
return {}
}
} | /**
* 获取小助手对应功能的数据
* @param {String} TBody 请求需要的数据
* @param {String} type 功能对应api 默认为 Single
* @returns 小助手返回数据
*/ | https://github.com/AFanSKyQs/FanSky_Qs/blob/86d002866114fa1dd1c765325fde621925938adc/apps/Teyvat/GetData/getTeyvatData.js#L15-L36 | 86d002866114fa1dd1c765325fde621925938adc |
safari | github_2023 | HazyResearch | javascript | fixInput | function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
} | // Fix IE bugs, see support tests | https://github.com/HazyResearch/safari/blob/02220c69d247e5473616cd053a443ad99fd2559b/csrc/fftconv/mathdx/22.02/include/cufftdx/docs/_static/jquery-3.5.1.js#L6034-L6045 | 02220c69d247e5473616cd053a443ad99fd2559b |
win32.run | github_2023 | ducbao414 | javascript | resizeBilinear$2 | function resizeBilinear$2(args) {
var inputs = args.inputs,
backend = args.backend,
attrs = args.attrs;
var images = inputs.images;
var alignCorners = attrs.alignCorners,
halfPixelCenters = attrs.halfPixelCenters,
size = attrs.size;
var newHeight = size[0],
newWidth = size[1];
var program = env().getBool('WEBGL_PACK_IMAGE_OPERATIONS') ? new ResizeBilinearPackedProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters) : new ResizeBilinearProgram(images.shape, newHeight, newWidth, alignCorners, halfPixelCenters);
return backend.runWebGLProgram(program, [images], 'float32');
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/ducbao414/win32.run/blob/05160523659c100d85802f15e164a0b9358b38b7/static/html/jspaint/lib/tracky-mouse/lib/tf.js#L119284-L119296 | 05160523659c100d85802f15e164a0b9358b38b7 |
win32.run | github_2023 | ducbao414 | javascript | getElementOffset | function getElementOffset(element) {
var docElem,
doc = element && element.ownerDocument,
box = { left: 0, top: 0 },
offset = { left: 0, top: 0 },
scrollLeftTop,
offsetAttributes = {
borderLeftWidth: 'left',
borderTopWidth: 'top',
paddingLeft: 'left',
paddingTop: 'top'
};
if (!doc) {
return offset;
}
for (var attr in offsetAttributes) {
offset[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
}
docElem = doc.documentElement;
if ( typeof element.getBoundingClientRect !== 'undefined' ) {
box = element.getBoundingClientRect();
}
scrollLeftTop = getScrollLeftTop(element);
return {
left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset.left,
top: box.top + scrollLeftTop.top - (docElem.clientTop || 0) + offset.top
};
} | /**
* Returns offset for a given element
* @function
* @memberOf fabric.util
* @param {HTMLElement} element Element to get offset for
* @return {Object} Object with "left" and "top" properties
*/ | https://github.com/ducbao414/win32.run/blob/05160523659c100d85802f15e164a0b9358b38b7/static/html/photon/dist/tui-image-editor.js#L3269-L3301 | 05160523659c100d85802f15e164a0b9358b38b7 |
openordex | github_2023 | orenyomtov | javascript | _getAndroid | function _getAndroid() {
var android = false;
var sAgent = navigator.userAgent;
if (/android/i.test(sAgent)) { // android
android = true;
aMat = sAgent.toString().match(/android ([0-9]\.[0-9])/i);
if (aMat && aMat[1]) {
android = parseFloat(aMat[1]);
}
}
return android;
} | // android 2.x doesn't support Data-URI spec | https://github.com/orenyomtov/openordex/blob/44581ec727c439c15178413b1d46c8f6176f253a/js/qrcode.js#L157-L171 | 44581ec727c439c15178413b1d46c8f6176f253a |
Ukrainian_IT_Communities | github_2023 | nikit0ns | javascript | normalizeArray | function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
} | // Copyright Joyent, Inc. and other Node contributors. | https://github.com/nikit0ns/Ukrainian_IT_Communities/blob/e0cea263be2e7d1da8e0e655134d787475dee526/site/assets/javascripts/lunr/wordcut.js#L4112-L4136 | e0cea263be2e7d1da8e0e655134d787475dee526 |
diffusion_model | github_2023 | wangjia184 | javascript | avgPoolGrad | function avgPoolGrad(args) {
const { inputs, backend, attrs } = args;
const { dy, input } = inputs;
const x = input;
assertNotComplex([dy, input], 'avgPoolGrad');
const { filterSize, strides, pad } = attrs;
const convInfo = tfjsCore.backend_util.computePool2DInfo(x.shape, filterSize, strides, 1 /* dilations */, pad);
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const dilationHeight = convInfo.dilationHeight;
const dilationWidth = convInfo.dilationWidth;
const effectiveFilterHeight = convInfo.effectiveFilterHeight;
const effectiveFilterWidth = convInfo.effectiveFilterWidth;
const padLeft = effectiveFilterWidth - 1 - convInfo.padInfo.left;
const padTop = effectiveFilterHeight - 1 - convInfo.padInfo.top;
const dx = tfjsCore.buffer(x.shape, 'float32');
const avgMultiplier = 1 / (filterHeight * filterWidth);
const dyData = backend.data.get(dy.dataId).values;
const dyBuf = tfjsCore.buffer(dy.shape, 'float32', dyData);
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d = 0; d < convInfo.inChannels; ++d) {
for (let dxR = 0; dxR < convInfo.inHeight; ++dxR) {
for (let dxC = 0; dxC < convInfo.inWidth; ++dxC) {
// Shader code begins.
const dyRCorner = dxR - padTop;
const dyCCorner = dxC - padLeft;
let dotProd = 0;
for (let wR = 0; wR < effectiveFilterHeight; wR += dilationHeight) {
const dyR = (dyRCorner + wR) / strideHeight;
if (dyR < 0 || dyR >= convInfo.outHeight ||
Math.floor(dyR) !== dyR) {
continue;
}
for (let wC = 0; wC < effectiveFilterWidth; wC += dilationWidth) {
const dyC = (dyCCorner + wC) / strideWidth;
if (dyC < 0 || dyC >= convInfo.outWidth ||
Math.floor(dyC) !== dyC) {
continue;
}
const pixel = dyBuf.get(b, dyR, dyC, d);
dotProd += pixel;
}
}
dx.set(dotProd * avgMultiplier, b, dxR, dxC, d);
}
}
}
}
return backend.makeTensorInfo(dx.shape, dx.dtype, dx.values);
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-backend-cpu/dist/tf-backend-cpu.es2017.js#L4774-L4825 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | stringToHashBucketFast | function stringToHashBucketFast(args) {
var inputs = args.inputs, backend = args.backend, attrs = args.attrs;
var numBuckets = attrs.numBuckets;
var input = inputs.input;
if (input.dtype !== 'string') {
throw new Error('Input must be of datatype string');
}
if (numBuckets <= 0) {
throw new Error("Number of buckets must be at least 1");
}
var $input = backend.readSync(input.dataId);
var output = stringToHashBucketFastImplCPU($input, numBuckets);
return backend.makeTensorInfo(input.shape, 'int32', output);
} | /**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-backend-webgl/dist/tf-backend-webgl.node.js#L17270-L17283 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | copy | function copy(f, t) {
t.i = f.i;
t.j = f.j;
t.S = f.S.slice();
return t;
} | // | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-converter/dist/tf-converter.es2017.js#L20137-L20142 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | argMin_ | function argMin_(x, axis = 0) {
const $x = convertToTensor(x, 'x', 'argMin');
const inputs = { x: $x };
const attrs = { axis };
return ENGINE.runKernel(ArgMin, inputs, attrs);
} | /**
* @license
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-converter/dist/tf-converter.fesm.js#L12280-L12285 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | avgPool3d_ | function avgPool3d_(x, filterSize, strides, pad, dimRoundingMode, dataFormat = 'NDHWC') {
const $x = convertToTensor(x, 'x', 'avgPool3d', 'float32');
let x5D = $x;
let reshapedTo5D = false;
if ($x.rank === 4) {
reshapedTo5D = true;
x5D = reshape($x, [1, $x.shape[0], $x.shape[1], $x.shape[2], $x.shape[3]]);
}
assert(x5D.rank === 5, () => `Error in avgPool3d: x must be rank 5 but got rank ${x5D.rank}.`);
assert(dataFormat === 'NDHWC', () => `Error in avgPool3d: Only NDHWC is currently supported, ` +
`but got dataFormat of ${dataFormat}`);
assert((typeof strides === 'number' && strides > 0) ||
(Array.isArray(strides) && strides[0] > 0 && strides[1] > 0 &&
strides[2] > 0), () => `Error in avgPool3d: Stride must be > 0, but got '${strides}'`);
checkPadOnDimRoundingMode('avgPool3d', pad, dimRoundingMode);
const inputs = { x: x5D };
const attrs = { filterSize, strides, pad, dimRoundingMode, dataFormat };
// tslint:disable-next-line: no-unnecessary-type-assertion
let res = ENGINE.runKernel(AvgPool3D, inputs, attrs);
res = cast(res, x5D.dtype);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-converter/dist/tf-converter.fesm.js#L12917-L12941 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | minimum_ | function minimum_(a, b) {
let $a = convertToTensor(a, 'a', 'minimum');
let $b = convertToTensor(b, 'b', 'minimum');
[$a, $b] = makeTypesMatch($a, $b);
if ($a.dtype === 'bool') {
$a = cast($a, 'int32');
$b = cast($b, 'int32');
}
assertAndGetBroadcastShape($a.shape, $b.shape);
const inputs = { a: $a, b: $b };
return ENGINE.runKernel(Minimum, inputs);
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-converter/dist/tf-converter.fesm.js#L18225-L18236 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | movingAverage_ | function movingAverage_(v, x, decay, step, zeroDebias = true) {
const $v = convertToTensor(v, 'v', 'movingAverage');
const $x = convertToTensor(x, 'x', 'movingAverage');
const $decay = convertToTensor(decay, 'decay', 'movingAverage');
assertTypesMatch($v, $x);
assert(arraysEqual($v.shape, $x.shape), () => 'Shape mismatch in v and x');
const one = scalar(1);
const oneMinusDecay = sub(one, $decay);
let update = mul(sub($x, $v), oneMinusDecay);
if (zeroDebias) {
assert(step != null, () => 'When using zeroDebias: true, step is required.');
const $step = convertToTensor(step, 'step', 'movingAverage');
update = div(update, sub(one, pow($decay, $step)));
}
return add($v, update);
} | /**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-converter/dist/tf-converter.fesm.js#L23247-L23262 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | conv3DBackpropInput_ | function conv3DBackpropInput_(xShape, dy, filter, strides, pad) {
assert(xShape.length === dy.rank, function () { return "Length of inShape " +
"(".concat(xShape.length, ") and rank of dy (").concat(dy.rank, ") must match"); });
var xShape5D = xShape;
var dy5D = dy;
var reshapedTo5D = false;
if (dy.rank === 4) {
reshapedTo5D = true;
dy5D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2], dy.shape[3]]);
xShape5D = [1, xShape[0], xShape[1], xShape[2], xShape[3]];
}
var inDepth = xShape5D[4];
var outDepth = dy5D.shape[4];
assert(xShape5D.length === 5, function () { return "Error in conv3dDerInput: inShape must be length 5, but got length " +
"".concat(xShape5D.length, "."); });
assert(dy5D.rank === 5, function () { return "Error in conv3dDerInput: dy must be rank 5, but got " +
"rank ".concat(dy5D.rank); });
assert(filter.rank === 5, function () { return "Error in conv3dDerInput: filter must be rank 5, but got " +
"rank ".concat(filter.rank); });
assert(inDepth === filter.shape[3], function () { return "Error in conv3dDerInput: depth of input (".concat(inDepth, ") must ") +
"match input depth for filter ".concat(filter.shape[3], "."); });
assert(outDepth === filter.shape[4], function () { return "Error in conv3dDerInput: depth of output (".concat(outDepth, ") must ") +
"match output depth for filter ".concat(filter.shape[4], "."); });
var inputs = { dy: dy5D, filter: filter };
var attrs = { pad: pad, strides: strides, inputShape: xShape5D };
// tslint:disable-next-line: no-unnecessary-type-assertion
var res = ENGINE.runKernel(Conv3DBackpropInputV2, inputs, attrs);
if (reshapedTo5D) {
return reshape(res, [res.shape[1], res.shape[2], res.shape[3], res.shape[4]]);
}
return res;
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-converter/dist/tf-converter.js#L14534-L14565 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | meshgrid | function meshgrid(x, y, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.indexing, indexing = _c === void 0 ? 'xy' : _c;
if (indexing !== 'xy' && indexing !== 'ij') {
throw new TypeError("".concat(indexing, " is not a valid third argument to meshgrid"));
}
if (x === undefined) {
return [];
}
var $x = convertToTensor(x, 'x', 'meshgrid', x instanceof Tensor ? x.dtype : 'float32');
if (y === undefined) {
return [$x];
}
var $y = convertToTensor(y, 'y', 'meshgrid', y instanceof Tensor ? y.dtype : 'float32');
var w = sizeFromShape($x.shape);
var h = sizeFromShape($y.shape);
if (indexing === 'xy') {
$x = reshape($x, [1, -1]);
$y = reshape($y, [-1, 1]);
return [
matMul$1(ones([h, 1], $x.dtype), $x),
matMul$1($y, ones([1, w], $y.dtype)),
];
}
$x = reshape($x, [-1, 1]);
$y = reshape($y, [1, -1]);
return [
matMul$1($x, ones([1, h], $x.dtype)),
matMul$1(ones([w, 1], $y.dtype), $y),
];
} | /**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-converter/dist/tf-converter.js#L18081-L18110 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | depthwiseConv2dNativeBackpropFilter_ | function depthwiseConv2dNativeBackpropFilter_(x, dy, filterShape, strides, pad, dilations, dimRoundingMode) {
if (dilations === void 0) { dilations = [1, 1]; }
var x4D = x;
if (x.rank === 3) {
x4D = reshape(x, [1, x.shape[0], x.shape[1], x.shape[2]]);
}
var dy4D = dy;
if (dy4D.rank === 3) {
dy4D = reshape(dy, [1, dy.shape[0], dy.shape[1], dy.shape[2]]);
}
var inputs = { x: x4D, dy: dy4D };
var attrs = { strides: strides, pad: pad, dimRoundingMode: dimRoundingMode, dilations: dilations, filterShape: filterShape };
// tslint:disable-next-line: no-unnecessary-type-assertion
return ENGINE.runKernel(DepthwiseConv2dNativeBackpropFilter, inputs, attrs);
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-converter/dist/tf-converter.js#L23878-L23892 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | IORouterRegistry.registerLoadRouter | static registerLoadRouter(loadRouter) {
IORouterRegistry.getInstance().loadRouters.push(loadRouter);
} | /**
* Register a load-handler router.
*
* @param loadRouter A function that maps a URL-like string onto an instance
* of `IOHandler` with the `load` method defined or `null`.
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-core/dist/tf-core.fesm.js#L6360-L6362 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | makeTensor | function makeTensor(values, shape, inferredShape, dtype) {
if (dtype == null) {
dtype = inferDtype(values);
}
else if (dtype === 'complex64') {
throw new Error("Cannot construct a complex64 tensor directly. " +
"Please use tf.complex(real, imag).");
}
if (typeof values === 'object' &&
('texture' in values ||
('buffer' in values && !(values.buffer instanceof ArrayBuffer)))) {
if (dtype !== 'float32' && dtype !== 'int32') {
throw new Error("Creating tensor from GPU data only supports " +
"'float32'|'int32' dtype, while the dtype is ".concat(dtype, "."));
}
return ENGINE.backend.createTensorFromGPUData(values, shape || inferredShape, dtype);
}
if (!isTypedArray(values) && !Array.isArray(values) &&
typeof values !== 'number' && typeof values !== 'boolean' &&
typeof values !== 'string') {
throw new Error('values passed to tensor(values) must be a number/boolean/string or ' +
'an array of numbers/booleans/strings, or a TypedArray');
}
// Verify that the shape matches the inferred shape.
if (shape != null) {
assertNonNegativeIntegerDimensions(shape);
var providedSize_1 = sizeFromShape(shape);
var inferredSize_1 = sizeFromShape(inferredShape);
assert(providedSize_1 === inferredSize_1, function () { return "Based on the provided shape, [".concat(shape, "], the tensor should have ") +
"".concat(providedSize_1, " values but has ").concat(inferredSize_1); });
for (var i = 0; i < inferredShape.length; ++i) {
var inferred = inferredShape[i];
var flatDimsDontMatch = i === inferredShape.length - 1 ?
inferred !== sizeFromShape(shape.slice(i)) :
true;
assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, function () { return "Error creating a new Tensor. Inferred shape " +
"(".concat(inferredShape, ") does not match the provided ") +
"shape (".concat(shape, "). "); });
}
}
if (!isTypedArray(values) && !Array.isArray(values)) {
values = [values];
}
shape = shape || inferredShape;
values = dtype !== 'string' ?
toTypedArray(values, dtype) :
flatten(values, [], true);
return ENGINE.makeTensor(values, shape, dtype);
} | /**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-core/dist/tf-core.js#L5637-L5685 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | cropAndResize_ | function cropAndResize_(image, boxes, boxInd, cropSize, method, extrapolationValue) {
if (method === void 0) { method = 'bilinear'; }
if (extrapolationValue === void 0) { extrapolationValue = 0; }
var $image = convertToTensor(image, 'image', 'cropAndResize');
var $boxes = convertToTensor(boxes, 'boxes', 'cropAndResize', 'float32');
var $boxInd = convertToTensor(boxInd, 'boxInd', 'cropAndResize', 'int32');
var numBoxes = $boxes.shape[0];
assert($image.rank === 4, function () { return 'Error in cropAndResize: image must be rank 4,' +
"but got rank ".concat($image.rank, "."); });
assert($boxes.rank === 2 && $boxes.shape[1] === 4, function () { return "Error in cropAndResize: boxes must be have size [".concat(numBoxes, ",4] ") +
"but had shape ".concat($boxes.shape, "."); });
assert($boxInd.rank === 1 && $boxInd.shape[0] === numBoxes, function () { return "Error in cropAndResize: boxInd must be have size [".concat(numBoxes, "] ") +
"but had shape ".concat($boxes.shape, "."); });
assert(cropSize.length === 2, function () { return "Error in cropAndResize: cropSize must be of length 2, but got " +
"length ".concat(cropSize.length, "."); });
assert(cropSize[0] >= 1 && cropSize[1] >= 1, function () { return "cropSize must be atleast [1,1], but was ".concat(cropSize); });
assert(method === 'bilinear' || method === 'nearest', function () { return "method must be bilinear or nearest, but was ".concat(method); });
var inputs = { image: $image, boxes: $boxes, boxInd: $boxInd };
var attrs = { method: method, extrapolationValue: extrapolationValue, cropSize: cropSize };
var res = ENGINE.runKernel(CropAndResize, inputs, attrs);
return res;
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-core/dist/tf-core.js#L20861-L20882 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | fromInt | function fromInt(value, unsigned) {
var obj, cachedObj, cache;
if (unsigned) {
value >>>= 0;
if (cache = (0 <= value && value < 256)) {
cachedObj = UINT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
if (cache)
UINT_CACHE[value] = obj;
return obj;
}
else {
value |= 0;
if (cache = (-128 <= value && value < 128)) {
cachedObj = INT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = fromBits(value, value < 0 ? -1 : 0, false);
if (cache)
INT_CACHE[value] = obj;
return obj;
}
} | /**
* @param {number} value
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs-layers/dist/tf-layers.js#L5451-L5477 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | softmaxCrossEntropyWithLogits_ | function softmaxCrossEntropyWithLogits_(labels, logits, dim = -1) {
if (dim === -1) {
dim = logits.rank - 1;
}
if (dim !== logits.rank - 1) {
throw Error(`Softmax cross entropy along a non-last dimension is not yet ` +
`supported. Labels / logits was rank ${logits.rank} ` +
`and dim was ${dim}`);
}
// Use a custom gradient for numerical stability.
const customOp = customGrad((labels, logits, save) => {
// Reference:
// 1. http://cs231n.github.io/linear-classify/#softmax
// 2. https://blog.feedly.com/tricks-of-the-trade-logsumexp/
const keepDims = true;
const lse = logSumExp(logits, [dim], keepDims);
const logResult = sub(cast(logits, 'float32'), lse);
save([labels, logResult]);
const costVector = neg(mul(logResult, labels));
const value = sum$1(costVector, [dim]);
const gradFunc = (dy, saved) => {
const [labels, logResult] = saved;
const dyShape = expandShapeToKeepDim(dy.shape, [dim]);
return [
mul(reshape(dy, dyShape), sub(cast(labels, 'float32'), exp(logResult))),
mul(reshape(dy, dyShape), sub(exp(logResult), cast(labels, 'float32'))),
];
};
return { value, gradFunc };
});
return customOp(labels, logits);
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.es2017.js#L22957-L22988 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | simpleRNN | function simpleRNN(args) {
return new SimpleRNN(args);
} | /**
* Fully-connected RNN where the output is to be fed back to input.
*
* This is an `RNN` layer consisting of one `SimpleRNNCell`. However, unlike
* the underlying `SimpleRNNCell`, the `apply` method of `SimpleRNN` operates
* on a sequence of inputs. The shape of the input (not including the first,
* batch dimension) needs to be at least 2-D, with the first dimension being
* time steps. For example:
*
* ```js
* const rnn = tf.layers.simpleRNN({units: 8, returnSequences: true});
*
* // Create an input with 10 time steps.
* const input = tf.input({shape: [10, 20]});
* const output = rnn.apply(input);
*
* console.log(JSON.stringify(output.shape));
* // [null, 10, 8]: 1st dimension is unknown batch size; 2nd dimension is the
* // same as the sequence length of `input`, due to `returnSequences`: `true`;
* // 3rd dimension is the `SimpleRNNCell`'s number of units.
* ```
*
* @doc {heading: 'Layers', subheading: 'Recurrent', namespace: 'layers'}
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.es2017.js#L53836-L53838 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | binaryCrossentropy$2 | function binaryCrossentropy$2(yTrue, yPred) {
return binaryCrossentropy$1(yTrue, yPred);
} | /**
* Binary crossentropy metric function.
*
* Example:
* ```js
* const x = tf.tensor2d([[0], [1], [1], [1]]);
* const y = tf.tensor2d([[0], [0], [0.5], [1]]);
* const crossentropy = tf.metrics.binaryCrossentropy(x, y);
* crossentropy.print();
* ```
*
* @param yTrue Binary Tensor of truth.
* @param yPred Binary Tensor of prediction, probabilities for the `1` case.
* @return Accuracy Tensor.
*
* @doc {heading: 'Metrics', namespace: 'metrics'}
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.es2017.js#L54464-L54466 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | oneHot$2 | function oneHot$2(args) {
const { inputs, backend, attrs } = args;
const { indices } = inputs;
const { dtype, depth, onValue, offValue } = attrs;
assertNotComplex(indices, 'oneHot');
const indicesSize = sizeFromShape(indices.shape);
const res = new Float32Array(indicesSize * depth);
res.fill(offValue);
const indicesVal = backend.data.get(indices.dataId).values;
for (let event = 0; event < indicesSize; ++event) {
if (indicesVal[event] >= 0 && indicesVal[event] < depth) {
res[event * depth + indicesVal[event]] = onValue;
}
}
return backend.makeTensorInfo([...indices.shape, depth], dtype, res);
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.es2017.js#L78823-L78838 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | transform$2 | function transform$2(args) {
const { inputs, backend, attrs } = args;
const { image, transforms } = inputs;
const { interpolation, fillMode, fillValue, outputShape } = attrs;
const [batch, imageHeight, imageWidth, numChannels] = image.shape;
const [outHeight, outWidth] = outputShape != null ? outputShape : [imageHeight, imageWidth];
const outShape = [batch, outHeight, outWidth,
numChannels];
const program = new TransformProgram(imageHeight, imageWidth, interpolation, fillMode, fillValue, outShape);
return backend.runWebGLProgram(program, [image, transforms], 'float32');
} | /**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.es2017.js#L101389-L101399 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | bandPart_ | function bandPart_(a, numLower, numUpper) {
assert(numLower % 1 === 0, () => `bandPart(): numLower must be an integer, got ${numLower}.`);
assert(numUpper % 1 === 0, () => `bandPart(): numUpper must be an integer, got ${numUpper}.`);
const $a = convertToTensor(a, 'a', 'bandPart');
assert($a.rank >= 2, () => `bandPart(): Rank must be at least 2, got ${$a.rank}.`);
const shape = $a.shape;
const [M, N] = $a.shape.slice(-2);
if (!(numLower <= M)) {
throw new Error(`bandPart(): numLower (${numLower})` +
` must not be greater than the number of rows (${M}).`);
}
if (!(numUpper <= N)) {
throw new Error(`bandPart(): numUpper (${numUpper})` +
` must not be greater than the number of columns (${N}).`);
}
if (numLower < 0) {
numLower = M;
}
if (numUpper < 0) {
numUpper = N;
}
const i = reshape(range(0, M, 1, 'int32'), [-1, 1]);
const j = range(0, N, 1, 'int32');
const ij = sub(i, j);
const inBand = logicalAnd(lessEqual(ij, scalar(+numLower, 'int32')), greaterEqual(ij, scalar(-numUpper, 'int32')));
const zero = zeros([M, N], $a.dtype);
return reshape(stack(unstack(reshape($a, [-1, M, N]))
.map(mat => where(inBand, mat, zero))), shape);
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.fesm.js#L22236-L22264 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | standardizeSampleOrClassWeights | function standardizeSampleOrClassWeights(xWeight, outputNames, weightType) {
const numOutputs = outputNames.length;
if (xWeight == null || (Array.isArray(xWeight) && xWeight.length === 0)) {
return outputNames.map(name => null);
}
if (numOutputs === 1) {
if (Array.isArray(xWeight) && xWeight.length === 1) {
return xWeight;
}
else if (typeof xWeight === 'object' && outputNames[0] in xWeight) {
return [xWeight[outputNames[0]]];
}
else {
return [xWeight];
}
}
if (Array.isArray(xWeight)) {
if (xWeight.length !== numOutputs) {
throw new Error(`Provided ${weightType} is an array of ${xWeight.length} ` +
`element(s), but the model has ${numOutputs} outputs. ` +
`Make sure a set of weights is provided for each model output.`);
}
return xWeight;
}
else if (typeof xWeight === 'object' && Object.keys(xWeight).length > 0 &&
typeof xWeight[Object.keys(xWeight)[0]] ===
'object') {
const output = [];
outputNames.forEach(outputName => {
if (outputName in xWeight) {
output.push(xWeight[outputName]);
}
else {
output.push(null);
}
});
return output;
}
else {
throw new Error(`The model has multiple (${numOutputs}) outputs, ` +
`so ${weightType} must be either an array with ` +
`${numOutputs} elements or an object with ${outputNames} keys. ` +
`Provided ${weightType} not understood: ${JSON.stringify(xWeight)}`);
}
} | /**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.fesm.js#L42060-L42104 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | gatherV2Impl | function gatherV2Impl(xBuf, indicesBuf, flattenOutputShape) {
const outBuf = buffer(flattenOutputShape, xBuf.dtype);
for (let i = 0; i < outBuf.size; ++i) {
const newLoc = outBuf.indexToLoc(i);
const originalLoc = newLoc.slice();
const batchIdx = originalLoc[0];
const indicesIdx = originalLoc[2];
const indicesIndex = indicesBuf.locToIndex([batchIdx, indicesIdx]);
originalLoc[2] = indicesBuf.values[indicesIndex];
const originalIndex = xBuf.locToIndex(originalLoc);
if (0 <= originalIndex && originalIndex < xBuf.values.length) {
outBuf.values[i] = xBuf.values[originalIndex];
} // Else, index is out of bounds, so leave the default zero val in outBuf.
}
return outBuf;
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.fesm.js#L71298-L71313 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | getEinsumPermutation | function getEinsumPermutation(nDims, idDims) {
var permutationIndices = new Array(nDims);
permutationIndices.fill(-1);
for (var i = 0; i < idDims.length; ++i) {
permutationIndices[idDims[i]] = i;
}
var expandDims = [];
for (var _i4 = 0; _i4 < nDims; ++_i4) {
if (permutationIndices[_i4] === -1) {
expandDims.push(_i4);
}
}
permutationIndices = permutationIndices.filter(function (d) {
return d !== -1;
});
return {
permutationIndices: permutationIndices,
expandDims: expandDims
};
} | /**
* Get the permutation for a given input tensor.
*
* @param nDims Total number of dimension of all tensors involved in the einsum
* operation.
* @param idDims Dimension indices involve in the tensor in question.
* @returns An object consisting of the following fields:
* - permutationIndices: Indices to permute the axes of the tensor with.
* - expandDims: Indices to the dimension that need to be expanded from the
* tensor after permutation.
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.js#L48675-L48698 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | truncatedNormal_ | function truncatedNormal_(shape, mean = 0, stdDev = 1, dtype, seed) {
assertNonNegativeIntegerDimensions(shape);
if (dtype != null && dtype === 'bool') {
throw new Error(`Unsupported data type $ { dtype }`);
}
const randGauss = new MPRandGauss(mean, stdDev, dtype, true /* truncated */, seed);
const res = buffer(shape, dtype);
for (let i = 0; i < res.values.length; i++) {
res.values[i] = randGauss.nextValue();
}
return res.toTensor();
} | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.node.js#L22415-L22426 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | OptimizerConstructors.adadelta | static adadelta(learningRate = .001, rho = .95, epsilon = null) {
return new AdadeltaOptimizer(learningRate, rho, epsilon);
} | /**
* Constructs a `tf.AdadeltaOptimizer` that uses the Adadelta algorithm.
* See [https://arxiv.org/abs/1212.5701](https://arxiv.org/abs/1212.5701)
*
* @param learningRate The learning rate to use for the Adadelta gradient
* descent algorithm.
* @param rho The learning rate decay over each update.
* @param epsilon A constant epsilon used to better condition the grad
* update.
*
* @doc {heading: 'Training', subheading: 'Optimizers', namespace: 'train'}
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.node.js#L27574-L27576 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | getComplexWithIndex | function getComplexWithIndex(complex, index) {
const real = complex[index * 2];
const imag = complex[index * 2 + 1];
return { real, imag };
} | /**
* Get the map representing a complex value in the given array.
* @param complex The complex tensor values.
* @param index An index of the target complex value.
*/ | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/@tensorflow/tfjs/dist/tf.node.js#L28174-L28178 | 5ea111bd405c1f893976808b768681d61e11c979 |
diffusion_model | github_2023 | wangjia184 | javascript | Toast.Default | static get Default() {
return Default;
} | // Getters | https://github.com/wangjia184/diffusion_model/blob/5ea111bd405c1f893976808b768681d61e11c979/docs/bootstrap/dist/js/bootstrap.esm.js#L5031-L5033 | 5ea111bd405c1f893976808b768681d61e11c979 |
Software-Architecture-with-C-Sharp-12-and-.NET-8-4E | github_2023 | PacktPublishing | javascript | createCache | function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return ( cache[ key + " " ] = value );
}
return cache;
} | /**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/ | https://github.com/PacktPublishing/Software-Architecture-with-C-Sharp-12-and-.NET-8-4E/blob/bb5f06a93c7a6ca281f88b0e3e16fb1302ebf943/ch11/MvcDockerTest/MvcDockerTest/wwwroot/lib/jquery/dist/jquery.js#L907-L921 | bb5f06a93c7a6ca281f88b0e3e16fb1302ebf943 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.