repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
siyuan-unlock | github_2023 | appdev | typescript | winOnClose | const winOnClose = (close = false) => {
exportLayout({
cb() {
if (window.siyuan.config.appearance.closeButtonBehavior === 1 && !close) {
// 最小化
if ("windows" === window.siyuan.config.system.os) {
ipcRenderer.send(Constan... | /// #if !BROWSER | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/boot/onGetConfig.ts#L115-L133 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | updateTab | const updateTab = () => {
const indexList: number[] = [];
const inputValue = inputElement.value;
configIndex.map((item, index) => {
item.map((subItem) => {
if (!subItem) {
console.warn("Search config miss language: ", item, index);
... | /// #endif | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/config/search.ts#L110-L173 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | getUnInitTab | const getUnInitTab = (options: IOpenFileOptions) => {
return getAllTabs().find(item => {
const initData = item.headElement?.getAttribute("data-initdata");
if (initData) {
const initObj = JSON.parse(initData);
if (initObj.instance === "Editor" &&
(initObj.rootI... | // 没有初始化的页签无法检测到 | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/editor/util.ts#L323-L346 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | importstdmd | const importstdmd = (label: string, isDoc?: boolean) => {
return {
id: isDoc ? "importMarkdownDoc" : "importMarkdownFolder",
icon: isDoc ? "iconMarkdown" : "iconFolder",
label,
click: async () => {
let filters: FileFilter[] = [];
if... | /// #if !BROWSER | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/menus/navigation.ts#L732-L760 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | getModelByDockType | const getModelByDockType = (type: TDock | string) => {
/// #if MOBILE
return window.siyuan.mobile.docks[type];
/// #else
return getDockByType(type).data[type];
/// #endif
}; | /// #endif | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/plugin/API.ts#L171-L177 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Protyle.constructor | constructor(app: App, id: HTMLElement, options?: IProtyleOptions) {
this.version = Constants.SIYUAN_VERSION;
let pluginsOptions: IProtyleOptions = options;
app.plugins.forEach(item => {
if (item.protyleOptions) {
pluginsOptions = merge(pluginsOptions, item.protyleOpti... | /**
* @param id 要挂载 Protyle 的元素或者元素 ID。
* @param options Protyle 参数
*/ | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L57-L287 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Protyle.focus | public focus() {
this.protyle.wysiwyg.element.focus();
} | /** 聚焦到编辑器 */ | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L378-L380 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Protyle.isUploading | public isUploading() {
return this.protyle.upload.isUploading;
} | /** 上传是否还在进行中 */ | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L383-L385 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Protyle.clearStack | public clearStack() {
this.protyle.undo.clear();
} | /** 清空 undo & redo 栈 */ | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L388-L390 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Protyle.destroy | public destroy() {
destroy(this.protyle);
} | /** 销毁编辑器 */ | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L393-L395 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Protyle.turnIntoOneTransaction | public turnIntoOneTransaction(selectsElement: Element[], type: TTurnIntoOne, subType?: TTurnIntoOneSub) {
turnsIntoOneTransaction({
protyle: this.protyle,
selectsElement,
type,
level: subType
});
} | /**
* 多个块转换为一个块
* @param {TTurnIntoOneSub} [subType] type 为 "BlocksMergeSuperBlock" 时必传
*/ | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L417-L424 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Protyle.turnIntoTransaction | public turnIntoTransaction(nodeElement: Element, type: TTurnInto, subType?: number) {
turnsIntoTransaction({
protyle: this.protyle,
nodeElement,
type,
level: subType,
});
} | /**
* 多个块转换
* @param {Element} [nodeElement] 优先使用包含 protyle-wysiwyg--select 的块,否则使用 nodeElement 单块
* @param {number} [subType] type 为 "Blocks2Hs" 时必传
*/ | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L431-L438 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | renderPDF | const renderPDF = async (id: string) => {
const localData = window.siyuan.storage[Constants.LOCAL_EXPORTPDF];
const servePath = window.location.protocol + "//" + window.location.host;
const isDefault = (window.siyuan.config.appearance.mode === 1 && window.siyuan.config.appearance.themeDark === "midnight") |... | /// #if !BROWSER | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/export/index.ts#L83-L578 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Gutter.genHeights | private genHeights(nodeElements: Element[], protyle: IProtyle) {
const matchHeight = nodeElements.find(item => {
if (!item.classList.contains("p") && !item.classList.contains("code-block") && !item.classList.contains("render-node")) {
return true;
}
});
if... | // TODO https://github.com/siyuan-note/siyuan/issues/11055 | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/gutter/index.ts#L2163-L2247 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | getAbcParams | const getAbcParams = (abcString: string): any => {
let params = {
responsive: "resize",
};
const firstLine = abcString.substring(0, abcString.indexOf("\n"));
if (firstLine.startsWith(ABCJS_PARAMS_KEY)) {
try {
params = looseJsonParse(firstLine.substring(ABCJS_PARAMS_KEY.lengt... | // Read the abcjsParams from the content if it exists. | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/render/abcRender.ts#L12-L25 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Scroll.constructor | constructor(protyle: IProtyle) {
this.parentElement = document.createElement("div");
this.parentElement.classList.add("protyle-scroll");
this.parentElement.innerHTML = `<div class="protyle-scroll__up ariaLabel" data-position="right4top" aria-label="${updateHotkeyTip("⌘Home")}">
<svg><use xli... | // 保持加载内容 | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/scroll/index.ts#L16-L58 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | Toolbar.mergeNode | private mergeNode(nodes: NodeListOf<ChildNode>) {
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType !== 3 && (nodes[i] as HTMLElement).tagName === "WBR") {
nodes[i].remove();
i--;
}
}
for (let i = 0; i < nodes.length; i++) {
... | // 合并多个 text 为一个 text | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/toolbar/index.ts#L1681-L1700 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | RecordMedia.cloneChannelData | public cloneChannelData(leftChannelData: Float32List, rightChannelData: Float32List) {
this.leftChannel.push(new Float32Array(leftChannelData));
this.rightChannel.push(new Float32Array(rightChannelData));
this.recordingLength += 2048;
} | // Publicly accessible methods: | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/util/RecordMedia.ts#L50-L54 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | goPreviousCell | const goPreviousCell = (cellElement: HTMLElement, range: Range, isSelected = true) => {
let previousElement = cellElement.previousElementSibling;
if (!previousElement) {
if (cellElement.parentElement.previousElementSibling) {
previousElement = cellElement.parentElement.previousElementSibling... | // 光标设置到前一个表格中 | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/util/table.ts#L36-L57 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | WYSIWYG.escapeInline | private escapeInline(protyle: IProtyle, range: Range, event: InputEvent) {
if (!event.data && event.inputType !== "insertLineBreak") {
return;
}
const inputData = event.data;
protyle.toolbar.range = range;
const inlineElement = range.startContainer.parentElement;
... | // text block-ref file-annotation-ref a 结尾处打字应为普通文本 | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/wysiwyg/index.ts#L158-L220 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | promiseTransaction | const promiseTransaction = () => {
if (window.siyuan.transactions.length === 0) {
return;
}
const protyle = window.siyuan.transactions[0].protyle;
const doOperations = window.siyuan.transactions[0].doOperations;
const undoOperations = window.siyuan.transactions[0].undoOperations;
// 1. *... | // 用于执行操作,外加处理当前编辑器中块引用、嵌入块的更新 | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/wysiwyg/transaction.ts#L63-L260 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
siyuan-unlock | github_2023 | appdev | typescript | inputEvent | const inputEvent = (event?: InputEvent) => {
if (event && event.isComposing) {
return;
}
if (inputElement.value.trim() === "") {
searchListElement.classList.add("fn__none");
searchTreeElement.classList.remove("fn__none");
return;
}
... | /// #endif | https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/util/pathName.ts#L221-L262 | d6bf65b650165c80c1feadb9c6e19fe01a26105d |
bce-qianfan-sdk | github_2023 | baidubce | typescript | main | async function main() {
const stream = await client.chat({
messages: [
{
role: 'user',
content: '等额本金和等额本息有什么区别?',
},
],
stream: true,
}, 'ERNIE-Bot-turbo');
console.log('流式返回结果');
for await (const chunk of stream as AsyncI... | // 手动传AK/SK 测试 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/chatCompletion.ts#L30-L44 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | main | async function main() {
const stream = await client.completions({
prompt: 'Introduce the city Beijing',
stream: true,
}, 'SQLCoder-7B');
console.log('流式返回结果');
for await (const chunk of stream as AsyncIterableIterator<any>) {
console.log(chunk);
}
} | // 手动传AK/SK 测试 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/completiont.ts#L39-L48 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | main | async function main() {
const resp = await client.embedding({
input: ['Introduce the city Beijing'],
}, 'Embedding-V1');
console.log('返回结果');
console.log(resp.data);
} | // 手动传AK/SK 测试 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/embedding.ts#L30-L36 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | main | async function main() {
const resp = await client.image2Text({
prompt: '分析一下图片画了什么',
image: '图片的base64编码',
});
console.log(resp);
} | // 手动传AK/SK 测试 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/image2text.ts#L33-L39 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | weatherMain | async function weatherMain() {
const resp = await client.plugins({
query: '深圳今天天气如何',
plugins: [
'uuid-weatherforecast',
],
});
console.log('返回结果');
console.log(resp);
} | // 手动传AK/SK 测试 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L35-L44 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | weatherStreamMain | async function weatherStreamMain() {
const stream = await client.plugins({
query: '深圳今天天气如何',
plugins: [
'uuid-weatherforecast',
],
stream: true,
verbose: false,
});
console.log('返回结果');
for await (const chunk of stream as AsyncIterableIterator<any>) {... | // weatherMain(); | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L49-L62 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | main | async function main() {
const stream = await client.plugins({
query: '请解析这张图片, 告诉我怎么画这张图的简笔画',
plugins: [
'uuid-chatocr',
],
stream: true,
fileurl: 'https://xxx.bcebos.com/xxx/xxx.jpeg',
});
for await (const chunk of stream as AsyncIterableIterator<any>) {... | // 智慧图问插件 测试 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L65-L79 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | streamYiYanMain | async function streamYiYanMain() {
const resp = await client.plugins({
messages: [
{
'role': 'user',
'content': '<file>浅谈牛奶的营养与消费趋势.docx</file><url>https://xxx/xxx/xxx.docx</url>',
},
],
plugins: ['ImageAI'],
stream: false,
... | // weatherStreamMain(); | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L139-L153 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | yiYanMain | async function yiYanMain() {
const resp = await client.plugins({
messages: [
{'role': 'user', 'content': '<file>浅谈牛奶的营养与消费趋势.docx</file><url>https://xxx/xxx/xxx.docx</url>'},
// eslint-disable-next-line max-len
{'role': 'assistant', 'content': '以下是该文档的关键内容:\n牛奶作为一种营养丰富、易消... | // ChatFile测试 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L156-L169 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | main | async function main() {
const resp = await client.reranker({
query: '上海天气',
documents: ['上海气候', '北京美食'],
});
console.log('返回结果');
console.log(resp);
} | // 手动传AK/SK 测试 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/reranker.ts#L30-L37 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | main | async function main() {
const resp = await client.text2Image({
prompt: '生成爱莎公主的图片',
size: '768x768',
n: 1,
steps: 20,
sampler_index: 'Euler a',
}, 'Stable-Diffusion-XL');
console.log(resp);
const base64Image = resp.data[0].b64_image;
// 创建一个简单的服务器
const se... | // 手动传AK/SK 测试 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/test2image.ts#L31-L52 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | BaseClient.getAccessToken | private async getAccessToken(): Promise<AccessTokenResp> {
const url = getAccessTokenUrl(this.qianfanAk, this.qianfanSk, this.qianfanBaseUrl);
try {
const resp = await this.fetchInstance.makeRequest(url, {
headers: this.headers,
method: 'POST',
});... | /**
* 使用 AK,SK 生成鉴权签名(Access Token)
* @return string 鉴权签名信息(Access Token)
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Base/index.ts#L99-L117 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | BaseClient.getIAMPath | private async getIAMPath(type, model) {
if (this.qianfanBaseUrl.includes('aip.baidubce.com')) {
throw new Error('请设置proxy的baseUrl');
}
const dynamicModelEndpoint = new DynamicModelEndpoint(
null,
this.qianfanConsoleApiBaseUrl,
this.qianfanBaseUrl
... | /**
* 获取 IAM 路径 (配置proxy情况下)
*
* @param type 路径类型
* @param model 模型名称
* @returns 返回 IAM 路径
* @throws 当 qianfanBaseUrl 包含 'aip.baidubce.com' 时,抛出错误提示设置 proxy 的 baseUrl
* @throws 当 qianfanConsoleApiBaseUrl 未设置时,抛出错误提示未设置 qianfanConsoleApiBaseUrl
* @throws 当 Endpoint 未设置且 qianfanCon... | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Base/index.ts#L129-L139 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | ChatCompletion.chat | public async chat(body: ChatBody, model = 'ERNIE-Lite-8K'): Promise<Resp | AsyncIterable<Resp>> {
const stream = body.stream ?? false;
const modelKey = model.toLowerCase();
const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map();
const endPoint = typeMap.get(modelKey) || '';
... | /**
* chat
* @param body 聊天请求体
* @param model 聊天模型,默认为 'ERNIE-Bot-turbo'
* @param stream 是否开启流模式,默认为 false
* @returns Promise<ChatResp | AsyncIterable<ChatResp>>
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/ChatCompletion/index.ts#L30-L42 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Completions.completions | public async completions(
body: CompletionBody,
model = 'ERNIE-Bot-turbo'
): Promise<Resp | AsyncIterable<Resp>> {
const stream = body.stream ?? false;
const {modelInfoMapUppercase, modelUppercase} = getUpperCaseModelAndModelMap(model, modelInfoMap);
// 兼容Chat模型
const... | /**
* 续写
* @param body 续写请求体
* @param model 续写模型,默认为 'ERNIE-Bot-turbo'
* @returns 返回 Promise 对象,异步获取续写结果
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Completions/index.ts#L29-L66 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | DynamicModelEndpoint.getEndpoint | public async getEndpoint(type: string, model?: string): Promise<string> {
const mutex = new Mutex();
const release = await mutex.acquire(); // 等待获取互斥锁
try {
if (!DYNAMIC_INVALID.includes(type) && this.isDynamicMapExpired()) {
await this.updateDynamicModelEndpoint(type... | /**
* 获取终端节点
*
* @param type 类型
* @param model 模型(可选)
* @param endpoint 终端节点(可选)
* @returns 终端节点
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/DynamicModelEndpoint/index.ts#L40-L74 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | getEndpointUrl | const getEndpointUrl = (typeMap :Map<string, string>) => {
const modelKey = (model || '').toLowerCase();
const rawEndPoint = typeMap.get(modelKey) || '';
let endPoint = type === 'plugin' ? rawEndPoint : rawEndPoint.split('/').pop() || '';
return endPoint ?... | // 释放互斥锁 | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/DynamicModelEndpoint/index.ts#L54-L64 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | DynamicModelEndpoint.isDynamicMapExpired | private isDynamicMapExpired() {
// 获取当前时间戳(以秒为单位)
const now = Date.now() / 1000;
// 比较当前时间戳和动态映射过期时间戳
return now > this.dynamicMapExpireAt;
} | /**
* 判断动态映射是否已过期
*
* @return 如果动态映射已过期,返回true;否则返回false
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/DynamicModelEndpoint/index.ts#L80-L85 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | DynamicModelEndpoint.updateDynamicModelEndpoint | async updateDynamicModelEndpoint(type: string) {
const url = `${this.qianfanConsoleApiBaseUrl}${SERVER_LIST_API}`;
let fetchOption = {};
// 设置默认的请求选项
const defaultOptions = {
body: JSON.stringify({
apiTypefilter: [type],
}),
headers: {
... | /**
* 更新动态模型端点
*
* @param qianfanConsoleApiBaseUrl Qianfan控制台API基础URL
* @param apiTypefilter API类型过滤器数组
* @param headers HTTP请求头
* @returns 返回异步操作结果
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/DynamicModelEndpoint/index.ts#L94-L142 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Eembedding.embedding | public async embedding(body: EmbeddingBody, model = 'Embedding-V1'): Promise<EmbeddingResp> {
const type = ModelType.EMBEDDINGS;
const modelKey = model.toLowerCase();
const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map();
const endPoint = typeMap.get(modelKey) || '';
... | /**
* 向量化
* @param body 请求体
* @param model 向量化模型,默认为'Embedding-V1'
* @returns Promise<Resp | AsyncIterable<Resp>>
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Embedding/index.ts#L28-L41 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.constructor | constructor({
maxRetries = 3,
timeout = 600000,
backoffFactor = 0,
retryMaxWaitInterval = 120000,
}: {
maxRetries?: number | undefined;
timeout?: number | undefined;
backoffFactor?: number | undefined;
retryMaxWaitInterval?: number | undefined;
} =... | /**
* 使用带有超时的 fetch 请求获取资源
* @returns 返回 Promise<Response>,表示获取到的响应
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L110-L125 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.makeRequest | async makeRequest(url: string, options: RequestOptions, retriesRemaining?: number): Promise<Response | any> {
if (!retriesRemaining && retriesRemaining !== 0) {
retriesRemaining = options.maxRetries ?? this.maxRetries;
}
if (options.signal?.aborted) {
throw new Error('Re... | /**
* 发起请求并处理响应
*
* @param options 请求选项
* @param retriesRemaining 剩余重试次数,可以为 null
* @returns Promise<APIResponseProps> 响应对象,包含响应信息、请求选项和 AbortController 实例
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L162-L210 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.shouldRetry | private shouldRetry(response: Response): boolean {
const shouldRetryHeader = response.headers.get('x-should-retry');
if (shouldRetryHeader === 'true') {
return true;
}
if (shouldRetryHeader === 'false') {
return false;
}
if (response.status === 408... | /**
* 判断是否应该重试请求
*
* @param response HTTP响应对象
* @returns 返回布尔值,表示是否应该重试请求
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L218-L239 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.shouldRetryWithErrorCode | private shouldRetryWithErrorCode(data: {error_code?: number; error_description?: string}): boolean {
// 对于已识别为可重试的错误码继续重试
return RETRY_CODE.includes(data?.error_code ?? 0);
} | /**
* 判断是否应该根据错误码进行重试
*
* @param data 包含错误码和错误描述的对象
* @returns 如果错误码在可重试的错误码列表中,则返回true,否则返回false
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L247-L250 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.retryRequest | private async retryRequest(
url: string,
options: RequestOptions,
retriesRemaining: number,
responseHeaders?: Headers | undefined
): Promise<Response | any> {
let timeoutMillis: number | undefined;
const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];
... | /**
* 重试请求
*
* @param options 请求选项
* @param retriesRemaining 剩余重试次数
* @param responseHeaders 响应头,可选
* @returns 返回 API 响应属性
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L260-L291 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.calculateDefaultRetryTimeoutMillis | private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {
// 计算当前尝试的次数
const attempt = maxRetries - retriesRemaining;
// 应用指数退避算法,并确保不超过最大值
const sleepSeconds = Math.min(this.retryMaxWaitInterval, this.backoffFactor * Math.pow(2, attempt));
... | /**
* 计算默认的重试超时时间(毫秒)
*
* @param retriesRemaining 剩余重试次数
* @param maxRetries 最大重试次数
* @returns 返回重试超时时间(毫秒)
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L300-L309 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.constructor | constructor({
maxRetries = 3,
timeout = 600000,
backoffFactor = 0,
retryMaxWaitInterval = 120000
}: {
maxRetries?: number | undefined;
timeout?: number | undefined;
backoffFactor?: number | undefined;
retryMaxWaitInterval?: number | undefined;
} = ... | /**
* 使用带有超时的 fetch 请求获取资源
* @returns 返回 Promise<Response>,表示获取到的响应
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L115-L132 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.getTpmHeader | getTpmHeader(headers: any): void {
const val = headers.get('x-ratelimit-limit-tokens') ?? '0';
this.tokenLimiter.resetTokens(val);
return val;
} | /**
* 获取TPM头部信息
*
* @param headers HTTP请求头对象
* @returns 返回字符串类型的令牌限制数量
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L172-L176 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.makeRequest | async makeRequest(url: string, options: RequestOptions, retriesRemaining?: number): Promise<Response | any> {
if (!retriesRemaining && retriesRemaining !== 0) {
retriesRemaining = options.maxRetries ?? this.maxRetries;
}
if (options.signal?.aborted) {
throw new Error('Re... | /**
* 发起请求并处理响应
*
* @param options 请求选项
* @param retriesRemaining 剩余重试次数,可以为 null
* @returns Promise<APIResponseProps> 响应对象,包含响应信息、请求选项和 AbortController 实例
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L190-L265 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.shouldRetry | private shouldRetry(response: Response): boolean {
const shouldRetryHeader = response.headers.get('x-should-retry');
if (shouldRetryHeader === 'true') {
return true;
}
if (shouldRetryHeader === 'false') {
return false;
}
if (response.status === 408... | /**
* 判断是否应该重试请求
*
* @param response HTTP响应对象
* @returns 返回布尔值,表示是否应该重试请求
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L273-L294 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.shouldRetryWithErrorCode | private shouldRetryWithErrorCode(data: {error_code?: number; error_description?: string}): boolean {
// 对于已识别为可重试的错误码继续重试
return RETRY_CODE.includes(data?.error_code);
} | /**
* 判断是否应该根据错误码进行重试
*
* @param data 包含错误码和错误描述的对象
* @returns 如果错误码在可重试的错误码列表中,则返回true,否则返回false
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L302-L305 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.retryRequest | private async retryRequest(
url: string,
options: RequestOptions,
retriesRemaining: number,
responseHeaders?: Headers | undefined
): Promise<Response | any> {
let timeoutMillis: number | undefined;
const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];
... | /**
* 重试请求
*
* @param options 请求选项
* @param retriesRemaining 剩余重试次数
* @param responseHeaders 响应头,可选
* @returns 返回 API 响应属性
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L315-L345 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Fetch.calculateDefaultRetryTimeoutMillis | private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {
// 计算当前尝试的次数
const attempt = maxRetries - retriesRemaining;
// 应用指数退避算法,并确保不超过最大值
const sleepSeconds = Math.min(this.retryMaxWaitInterval, this.backoffFactor * Math.pow(2, attempt));
... | /**
* 计算默认的重试超时时间(毫秒)
*
* @param retriesRemaining 剩余重试次数
* @param maxRetries 最大重试次数
* @returns 返回重试超时时间(毫秒)
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L354-L363 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | HttpClient.getSignature | async getSignature(config): Promise<any> {
const {httpMethod, path, body, headers, params, signFunction} = config;
const method = httpMethod.toUpperCase();
const requestUrl = this._getRequestUrl(path);
const _headers = Object.assign({}, this.defaultHeaders, headers);
if (!_header... | /**
* 获取签名
*
* @param config 请求配置对象
* @returns 返回包含签名信息的 fetchOptions 对象
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/HttpClient/index.ts#L43-L65 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | HttpClient._guessContentLength | private _guessContentLength(data: string | Buffer | Blob | ArrayBuffer | any): number {
if (data == null) {
return 0;
}
else if (typeof data === 'string') {
return new TextEncoder().encode(data).length;
}
else if (typeof data === 'object') {
if... | /**
* 猜测数据长度
*
* @param data 数据,可以是字符串、Buffer、可读流
* @returns 返回数据长度
* @throws {Error} 当没有指定 Content-Length 时抛出异常
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/HttpClient/index.ts#L129-L153 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Image2Text.image2Text | public async image2Text(
body: Image2TextBody,
model = 'Fuyu-8B'
): Promise<RespBase> {
const type = ModelType.IMAGE_2_TEXT;
const modelKey = model.toLowerCase();
const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map();
const endPoint = typeMap.get(modelKe... | /**
* 图生文
* @param body 请求体
* @returns 返回图像转文本
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Images/image2text.ts#L27-L43 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Text2Image.text2Image | public async text2Image(
body: Text2ImageBody,
model = 'Stable-Diffusion-XL'
): Promise<Text2ImageResp> {
const type = ModelType.TEXT_2_IMAGE;
const modelKey = model.toLowerCase();
const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map();
const endPoint = t... | /**
* 文生图
* @param body 续写请求体
* @param model 续写模型,默认为 'ERNIE-Bot-turbo'
* @returns 返回 Promise 对象,异步获取续写结果
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Images/text2image.ts#L29-L45 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | RateLimiter.schedule | async schedule<T>(func: () => Promise<T>): Promise<T> {
return this.limiter.schedule(func);
} | /**
* 使用限流器调度函数执行
*
* @param func 要调度的函数,返回一个Promise<T>
* @returns 返回Promise<T>类型的调度结果
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/RateLimiter/index.ts#L72-L74 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | RateLimiter.updateLimits | async updateLimits(requestPerMinute: number): Promise<void> {
let release: () => void;
try {
// 使用hasReset检查是否已经进行过更新
if (this.hasReset) {
return;
}
release = await this.mutex.acquire();
// 防止多个任务同时更新限制
if (this.hasR... | /**
* 更新限制
*
* @param requestPerMinute 每分钟请求次数,可选参数
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/RateLimiter/index.ts#L81-L111 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | RateLimiter.safeParseInt | private safeParseInt(value?: number | string, envVarName?: string): number | undefined {
if (!value) {
return;
}
const parsedValue = Number.parseInt(String(value), 10);
if (isNaN(parsedValue) || parsedValue < 0) {
console.warn(`Invalid value for ${envVarName}: ${v... | /**
* 安全解析整数
*
* @param value 要解析的值,可以是数字或字符串
* @param envVarName 环境变量名,用于输出警告信息
* @returns 解析后的整数,若解析失败则返回 undefined
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/RateLimiter/index.ts#L120-L130 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | TokenLimiter.getTimeAtLastMinute | private getTimeAtLastMinute(): number {
return Math.floor(this.currentTime().getTime() / 60000) * 60000;
} | /**
* 获取当前时间所在分钟的开始时间戳
* @returns {number} 返回当前时间所在分钟的开始时间戳(毫秒)
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L51-L53 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | TokenLimiter.refreshTokens | private async refreshTokens(): Promise<void> {
const nowAtMinute = this.getTimeAtLastMinute();
if (nowAtMinute !== this.lastRefreshTime.getTime()) {
this.tokens = this.maxTokens;
this.lastRefreshTime = new Date(nowAtMinute);
}
} | /**
* 整分刷新令牌
* @returns Promise<void>
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L59-L65 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | TokenLimiter.timeUntilNextMinute | private timeUntilNextMinute(): number {
const now = this.currentTime();
const nextMinute = new Date(now);
nextMinute.setMinutes(now.getMinutes() + 1);
nextMinute.setSeconds(0);
nextMinute.setMilliseconds(0);
return nextMinute.getTime() - now.getTime();
} | /**
* 当前时间开始到下一分钟开始所需等待的时间(以毫秒为单位)
* 如果在一个时间窗口(例如一分钟)内可用的令牌已经用完,需要等待直到下一个时间窗口开始才能再次填充令牌
* @returns 等待时间
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L72-L79 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | TokenLimiter.acquireTokens | public async acquireTokens(tokenCount: number): Promise<boolean> {
if (this.maxTokens <= 0) {
return true;
}
let release: () => void;
try {
release = await this.mutex.acquire();
await this.refreshTokens();
if (this.tokens >= tokenCount) {
... | /**
* 当前是否有指定数量的可用令牌
* 如果当前令牌数不足,它将计算等待时间直到下一分钟开始,并尝试再次刷新令牌。
* @param tokenCount 令牌数量
* @returns 返回Promise<boolean>类型,如果成功获取令牌,则返回true;否则返回false
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L87-L112 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | TokenLimiter.resetTokens | public async resetTokens(totalTokens: number): Promise<void> {
let release: () => void;
try {
if (this.hasReset) {
return;
}
release = await this.mutex.acquire();
if (this.hasReset) {
return;
}
// 检查如... | /**
* 重置令牌
*
* @param totalTokens 总的令牌数量
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L119-L154 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | TokenLimiter.calculateTokens | public calculateTokens(text: string): number {
const chineseCharactersCount = text.match(/[\u4e00-\u9fa5]/g)?.length || 0;
const englishWordCount = text.match(/\b[a-zA-Z]+\b/g)?.length || 0;
return chineseCharactersCount * 0.625 + englishWordCount;
} | /**
* 计算文本中的 Token 数量
*
* @param text 要计算 Token 的文本
* @returns 返回计算出的 Token 数量
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L162-L166 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | Plugin.plugins | public async plugins(
body: PluginsBody | YiYanPluginBody,
model = 'EBPluginV2'
): Promise<PluginsResp | AsyncIterable<PluginsResp>> {
const stream = body.stream ?? false;
const type = ModelType.PLUGIN;
const modelKey = model.toLowerCase();
const typeMap = getTypeMap(... | /**
* 插件
* @param body 请求体
* @param model 续写模型,默认为 'ERNIE-Bot-turbo'
* @returns 返回 Promise 对象,异步获取续写结果
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Plugin/index.ts#L28-L47 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | concatUint8Arrays | function concatUint8Arrays(a: Uint8Array, b: Uint8Array): Uint8Array {
const result = new Uint8Array(a.length + b.length);
result.set(a, 0);
result.set(b, a.length);
return result;
} | // 合并两个 Uint8Array | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/streaming/index.ts#L330-L335 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
bce-qianfan-sdk | github_2023 | baidubce | typescript | splitUint8Array | function splitUint8Array(array: Uint8Array, delimiter: number): [Uint8Array[], Uint8Array] {
const result: Uint8Array[] = [];
let start = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] === delimiter) {
result.push(array.subarray(start, i));
start = i + 1; // 跳过 del... | /**
* 使用指定的分隔符将 Uint8Array 数组拆分为多个子数组和剩余部分。
*
* @param array 要拆分的 Uint8Array 数组。
* @param delimiter 分隔符的数值。
* @returns 包含拆分后的多个子数组和剩余部分的数组。
* 第一个元素是拆分后的子数组列表,类型为 Uint8Array[]。
* 第二个元素是剩余部分的 Uint8Array 数组。
*/ | https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/streaming/index.ts#L385-L398 | 96135c9bfa9cfc8178725fc303f966774f31b693 |
powerpipe | github_2023 | turbot | typescript | nodesAndEdgesToTree | const nodesAndEdgesToTree = (
nodesAndEdges: NodesAndEdges,
namedThemeColors,
): TreeItem[] => {
// const rootParentIds = { "": true };
// the resulting unflattened tree
// const rootItems: TreeItem[] = [];
// stores all already processed items with their ids as key so we can easily look them up
const l... | // Taken from https://github.com/philipstanislaus/performant-array-to-tree | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/index.ts#L976-L1041 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | generateColors | const generateColors = () => {
// echarts vintage
// return [
// "#d87c7c",
// "#919e8b",
// "#d7ab82",
// "#6e7074",
// "#61a0a8",
// "#efa18d",
// "#787464",
// "#cc7e63",
// "#724e58",
// "#4b565b",
// ];
// tableau.Tableau20
return [
"#4E79A7",
"#A0CBE8",
... | // TODO color scheme - need to find something better? | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/index.ts#L1054-L1091 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | getChartColors | const getChartColors = (theme: Theme) => {
if (theme.name === ThemeNames.STEAMPIPE_DARK) {
return [
"#486de8",
"#e07f9d",
"#018977",
"#b088f5",
"#c55305",
"#8ea9ff",
"#ffb0c8",
"#40bfa9",
];
} else {
return [
"#688ae8",
"#c33d69",
"#2ea59... | // Taken from https://cloudscape.design/foundation/visual-foundation/data-vis-colors/ | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/index.ts#L1094-L1118 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | getNodeAndEdgeDataFormat | const getNodeAndEdgeDataFormat = (
properties: NodeAndEdgeProperties | undefined,
): NodeAndEdgeDataFormat => {
if (!properties) {
return "LEGACY";
}
if (!properties.nodes && !properties.edges) {
return "LEGACY";
}
if (
(properties.nodes && properties.nodes.length > 0) ||
(properties.edges... | // Categories may be sourced from a node, an edge, a flow, a graph or a hierarchy | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/useNodeAndEdgeData.ts#L33-L52 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | useNodeAndEdgeData | const useNodeAndEdgeData = (
data: NodeAndEdgeData | undefined,
properties: NodeAndEdgeProperties | undefined,
status: DashboardRunState,
) => {
const { panelsMap } = useDashboardState();
const themeColors = useChartThemeColors();
const dataFormat = getNodeAndEdgeDataFormat(properties);
const panels = use... | // This function will normalise both the legacy and node/edge data formats into a data table. | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/useNodeAndEdgeData.ts#L126-L357 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | getNodeIntersection | function getNodeIntersection(intersectionNode, targetNode) {
// https://math.stackexchange.com/questions/1724792/an-algorithm-for-finding-the-intersection-point-between-a-center-of-vision-and-a
const { width: intersectionNodeWidth, position: intersectionNodePosition } =
intersectionNode;
const targetPosition ... | // this helper function returns the intersection point | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/graphs/Graph/utils.ts#L7-L70 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | getEdgePosition | function getEdgePosition(node, intersectionPoint) {
const n = { ...node.position, ...node };
const nx = Math.round(n.x);
const ny = Math.round(n.y);
const px = Math.round(intersectionPoint.x);
const py = Math.round(intersectionPoint.y);
if (px <= nx + 1) {
return Position.Left;
}
if (px >= nx + n.w... | // returns the position (top,right,bottom or right) passed node compared to the intersection point | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/graphs/Graph/utils.ts#L73-L94 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | circleGetControlWithCurvature | function circleGetControlWithCurvature({ x1, y1, x2, y2, c }) {
let ctX;
let ctY;
if (x1 > x2) {
ctX = x1 - calculateControlOffset(x2 - x1, c);
} else {
ctX = x1 + calculateControlOffset(x1 - x2, c);
}
if (y1 > y2) {
ctY = y1 - calculateControlOffset(y2 - y1, c);
} else {
ctY = y1 + calc... | /*
export function createNodesAndEdges() {
const nodes = [];
const edges = [];
const center = { x: window.innerWidth / 2, y: window.innerHeight / 2 };
nodes.push({ id: "target", data: { label: "Target" }, position: center });
for (let i = 0; i < 8; i++) {
const degrees = i * (360 / 8);
const radians... | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/graphs/Graph/utils.ts#L154-L171 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | runTestCases | function runTestCases(
testCases: TestCase[],
validationFunction: (input: any) => boolean,
) {
testCases.forEach((testCase) => {
it(`should return ${testCase.expected} for ${testCase.name}`, () => {
const result = validationFunction(testCase.input);
expect(result).toBe(testCase.expected);
});
... | // const orFilterTestCases: TestCase[] = [ | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/grouping/FilterEditor/index.test.ts#L103-L113 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | DatetimeInput | const DatetimeInput = (props: InputProps) => {
// return <Foo />;
return (
<Date
name={props.name}
display_type="datetime"
properties={props.properties}
/>
);
}; | // const Foo = () => { | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/inputs/DatetimeInput/index.tsx#L12-L21 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | getCheckGroupingKey | const getCheckGroupingKey = (
checkResult: CheckResult,
group: CheckDisplayGroup,
) => {
switch (group.type) {
case "dimension":
return getCheckDimensionGroupingKey(group.value, checkResult.dimensions);
case "control_tag":
return getCheckTagGroupingKey(group.value, checkResult.tags);
case ... | // const getCheckResultGroupingKey = (checkResult: CheckResult): string => { | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/hooks/useBenchmarkGrouping.tsx#L244-L274 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | handleResize | function handleResize() {
// Set window width/height to state
// @ts-ignore
setDimensions(ref.current.getBoundingClientRect().toJSON());
} | // Handler to call on window resize | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/hooks/useDimensions.ts#L14-L18 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | useWindowSize | const useWindowSize = (): readonly [number, number] => {
// @ts-ignore
const [size, setSize] = useState(
typeof window !== "undefined"
? ([window.innerWidth, window.innerHeight] as const)
: ([0, 0] as const),
);
useEffect(() => {
const updateSize = () => {
setSize([window.innerWidth, w... | // https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/hooks/useWindowSize.ts#L4-L19 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
powerpipe | github_2023 | turbot | typescript | getResponsivePanelWidthClass | const getResponsivePanelWidthClass = (width: number | undefined): string => {
switch (width) {
case 0:
// Hide anything with no width
return "hidden";
case 1:
return "md:col-span-3 lg:col-span-1";
case 2:
return "md:col-span-3 lg:col-span-2";
case 3:
return "md:col-span-3... | // Needs to be a single unbroken string so that the tailwind content purging | https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/utils/layout.ts#L4-L36 | e500c48d5bc38a63c694007f80a13c42b3da0d17 |
gadget | github_2023 | tangle-network | typescript | signAndSend | async function signAndSend(
signer: AddressOrPair,
tx: SubmittableExtrinsic<"promise">,
waitTillFinallized: boolean = false,
): Promise<void> {
// Sign and send the transaction and wait for it to be included.
await new Promise(async (resolve, reject) => {
const unsub = await tx.signAndSend(
signer,
... | // *** --- Helper Functions --- *** | https://github.com/tangle-network/gadget/blob/06ebab91cbb0fd361b2397a6221c2020173ebbf3/blueprints/incredible-squaring/deploy.ts#L148-L187 | 06ebab91cbb0fd361b2397a6221c2020173ebbf3 |
react-native-vercel-ai | github_2023 | bidah | typescript | createChunkDecoder | function createChunkDecoder(complex?: boolean) {
const decoder = new TextDecoder();
if (!complex) {
return function (chunk: Uint8Array | undefined): string {
if (!chunk) return '';
return decoder.decode(chunk, { stream: true });
};
}
return function (chunk: Uint8Array | undefined) {
co... | // Type overloads | https://github.com/bidah/react-native-vercel-ai/blob/3b5441140f61b5f480e112e2588dd2883ed35ad1/src/shared/utils.ts#L23-L37 | 3b5441140f61b5f480e112e2588dd2883ed35ad1 |
javavscode | github_2023 | oracle | typescript | matchTemplate | function matchTemplate(str1: string, str2: string): boolean {
const regexp = /\{[^\{\}]*\}/g;
const params1 = new Set([...str1.matchAll(regexp)].map((value) => value[0]));
const params2 = new Set([...str2.matchAll(regexp)].map((value) => value[0]));
return setEqual(params1, params2);
} | /**
*
* @param str1
* @param str2
* @returns Checks if the placeholders specified as {placeholder} match for str1 and str2
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L500-L505 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | placeholderMatch | function placeholderMatch(targetString: string, placeholders: Set<string>): boolean {
const regexp = /\{([^\{\}]*)\}/g;
const params1 = new Set([...targetString.matchAll(regexp)].map((value) => value[1]));
return setEqual(params1, placeholders);
} | /**
*
* @param targetString String containing placeholder in form of {placeholder}
* @param placeholders Set of required placeholders in the target string
* @returns Whether the placeholders present in the targetString and in the placeholders set are same
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L520-L524 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | getPlaceholders | function getPlaceholders(dictString: string): Set<string> {
const placeholders = new Set<string>();
const cleanedDictString = dictString.replace(/"[^"]*"/g, "SOME_STRING_VALUE").replace(/'[^']*'/g, "SOME_STRING_VALUE");
for (const keyVal of cleanedDictString.split(',')) {
// improve this so that if ... | /**
*
* @param dictString String having key value pairs {key1:value1,key2:value2...}
* @returns Set of keys used in the dictString
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L533-L541 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | checkL10nUsageInFile | function checkL10nUsageInFile(filePath: string, pattern: RegExp, validKeyValues: any): boolean {
const fileContent: string = fs.readFileSync(filePath, 'utf8');
const matches = fileContent.matchAll(pattern);
const keys = new Set(Object.keys(validKeyValues));
let result = true;
for (const matchArr of ... | /**
*
* @param filePath
* @param pattern To extract the keys and the placeholder map used when calling l10n.value
* @param validKeyValues From the bundle.en.json filee
* @returns All usage of l10n.value according to the pattern is having valid keys and placeholder map
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L550-L579 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | isLocalizedVal | function isLocalizedVal(value: string): boolean {
return value.length > 2 && value[0] === '%' && value[0] === value[value.length - 1];
} | /**
*
* @param value string to be checked
* @returns value of the form %key% where key is some string containing alphanumeric characters
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L586-L588 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | getlocalizingKey | function getlocalizingKey(str: string): string {
const length = str.length;
return str.substring(1, length - 1);
} | /**
*
* @param str localised value of the form %key%
* @returns key
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L596-L599 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | isLocalizedObj | function isLocalizedObj(obj: any, localisableFields: any, id: string, category: string, validKeys: Set<string>): boolean {
let localized: boolean = true;
let fieldVals: any;
let localizingKey: string;
for (const field of localisableFields) {
fieldVals = obj[field];
if (fieldVals === unde... | /**
*
* @param obj
* @param localisableFields Array or Scalar fields which are to be tested for localisation
* @param id
* @param category
* @param validKeys Keys present in the package.nls.json
* @returns Whether the object given has the required fields localised by some valid key
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L610-L630 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | _schemeFix | function _schemeFix(scheme: string, _strict: boolean): string {
if (_strict || _throwOnMissingSchema) {
return scheme || _empty;
}
if (!scheme) {
console.trace('BAD uri lacks scheme, falling back to file-scheme.');
scheme = 'file';
}
return scheme;
} | // for a while we allowed uris *without* schemes and this is the migration | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L102-L111 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | _referenceResolution | function _referenceResolution(scheme: string, path: string): string {
// the slash-character is our 'default base' as we don't
// support constructing URIs relative to other URIs. This
// also means that we alter and potentially break paths.
// see https://tools.ietf.org/html/rfc3986#section-5.1.4
s... | // implements a bit of https://tools.ietf.org/html/rfc3986#section-5 | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L114-L133 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | URI.constructor | protected constructor(
schemeOrData: string | UriComponents,
authority?: string,
path?: string,
query?: string,
fragment?: string,
_strict = false,
) {
if (typeof schemeOrData === 'object') {
this.scheme = schemeOrData.scheme || _empty;
... | /**
* @internal
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L217-L243 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | URI.fsPath | get fsPath(): string {
// if (this.scheme !== 'file') {
// console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
// }
return _makeFsPath(this);
} | /**
* Returns a string representing the corresponding file system path of this URI.
* Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
* platform specific path separator.
*
* * Will *not* validate the path for invalid characters and semanti... | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L271-L276 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | URI.with | with(change: {
scheme?: string;
authority?: string | null;
path?: string | null;
query?: string | null;
fragment?: string | null;
}): URI {
if (!change) {
return this;
}
let { scheme, authority, path, query, fragment } = change;
if... | // ---- modify to new ------------------------- | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L280-L330 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
javavscode | github_2023 | oracle | typescript | URI.parse | static parse(value: string, _strict = false): URI {
const match = _regexp.exec(value);
if (!match) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return new _URI(_empty, _empty, _empty, _empty, _empty);
}
// eslint-disable-next-line @typescr... | /**
* Creates a new URI from a string, e.g. `http://www.msft.com/some/path`,
* `file:///usr/home`, or `scheme:with/path`.
*
* @param value A string which represents an URI (see `URI#toString`).
* @param {boolean} [_strict=false]
*/ | https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L341-L356 | 40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.