type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
ArrowFunction
async () => { const template = (await readFile(path.join(getTemplatePath("msi"), "template.xml"), "utf8")) .replace(/{{/g, "<%") .replace(/}}/g, "%>") .replace(/\${([^}]+)}/g, "<%=$1%>") return ejs.compile(template) }
Eshva/electron-builder
packages/app-builder-lib/src/targets/MsiTarget.ts
TypeScript
ArrowFunction
file => { const packagePath = file.substring(appOutDir.length + 1) const lastSlash = packagePath.lastIndexOf(path.sep) const fileName = lastSlash > 0 ? packagePath.substring(lastSlash + 1) : packagePath let directoryId: string | null = null let dirName = "" // Wix Directory.FileSource doesn't work - https://stackoverflow.com/questions/21519388/wix-filesource-confusion if (lastSlash > 0) { // This Name attribute may also define multiple directories using the inline directory syntax. // For example, "ProgramFilesFolder:\My Company\My Product\bin" would create a reference to a Directory element with Id="ProgramFilesFolder" then create directories named "My Company" then "My Product" then "bin" nested beneath each other. // This syntax is a shortcut to defining each directory in an individual Directory element. dirName = packagePath.substring(0, lastSlash) // https://github.com/electron-userland/electron-builder/issues/3027 directoryId = "d" + createHash("md5").update(dirName).digest("base64").replace(/\//g, "_").replace(/\+/g, ".").replace(/=+$/, "") if (!dirNames.has(dirName)) { dirNames.add(dirName) dirs.push(`<Directory Id="${directoryId}" Name="${ROOT_DIR_ID}:\\${dirName.replace(/\//g, "\\")}\\"/>`) } } else if (!isRootDirAddedToRemoveTable) { isRootDirAddedToRemoveTable = true } // since RegistryValue can be part of Component, *** *** *** *** *** *** *** *** *** wix cannot auto generate guid // https://stackoverflow.com/questions/1405100/change-my-component-guid-in-wix let result = `<Component${directoryId === null ? "" : ` Directory="${directoryId}"`}>` result += `\n${fileSpace} <File Name="${fileName}" Source="$(var.appDir)${path.sep}${packagePath}" ReadOnly="yes" KeyPath="yes"` const isMainExecutable = packagePath === `${appInfo.productFilename}.exe` if (isMainExecutable) { result += ' Id="mainExecutable"' } else if (directoryId === null) { result += ` Id="${path.basename(packagePath)}_f"` } const isCreateDesktopShortcut = commonOptions.isCreateDesktopShortcut !== DesktopShortcutCreationPolicy.NEVER if (isMainExecutable && (isCreateDesktopShortcut || commonOptions.isCreateStartMenuShortcut)) { result += `>\n` const shortcutName = commonOptions.shortcutName if (isCreateDesktopShortcut) { result += `${fileSpace} <Shortcut Id="desktopShortcut" Directory="DesktopFolder" Name="${shortcutName}" WorkingDirectory="APPLICATIONFOLDER" Advertise="yes" Icon="icon.ico"/>\n` } const hasMenuCategory = commonOptions.menuCategory != null const startMenuShortcutDirectoryId = hasMenuCategory ? "AppProgramMenuDir" : "ProgramMenuFolder" if (commonOptions.isCreateStartMenuShortcut) { if (hasMenuCategory) { dirs.push(`<Directory Id="${startMenuShortcutDirectoryId}" Name="ProgramMenuFolder:\\${commonOptions.menuCategory}\\"/>`) } result += `${fileSpace} <Shortcut Id="startMenuShortcut" Directory="${startMenuShortcutDirectoryId}" Name="${shortcutName}" WorkingDirectory="APPLICATIONFOLDER" Advertise="yes" Icon="icon.ico">\n` result += `${fileSpace} <ShortcutProperty Key="System.AppUserModel.ID" Value="${this.packager.appInfo.id}"/>\n` result += `${fileSpace} </Shortcut>\n` } result += `${fileSpace}</File>` if (hasMenuCategory) { result += `<RemoveFolder Id="${startMenuShortcutDirectoryId}" Directory="${startMenuShortcutDirectoryId}" On="uninstall"/>\n` } } else { result += `/>` } return `${result}\n${fileSpace}</Component>` }
Eshva/electron-builder
packages/app-builder-lib/src/targets/MsiTarget.ts
TypeScript
MethodDeclaration
async build(appOutDir: string, arch: Arch) { const packager = this.packager const artifactName = packager.expandArtifactBeautyNamePattern(this.options, "msi", arch) const artifactPath = path.join(this.outDir, artifactName) await packager.info.callArtifactBuildStarted({ targetPresentableName: "MSI", file: artifactPath, arch, }) const stageDir = await createStageDir(this, packager, arch) const vm = this.vm const commonOptions = getEffectiveOptions(this.options, this.packager) if (commonOptions.isAssisted) { // F*** *** *** *** *** *** *** *** *** *** *** *** *** WiX *** *** *** *** *** *** *** *** *** // cannot understand how to set MSIINSTALLPERUSER on radio box change. In any case installed per user. log.warn(`MSI DOESN'T SUPPORT assisted installer. Please use NSIS instead.`) } const projectFile = stageDir.getTempFile("project.wxs") const objectFiles = ["project.wixobj"] const uiFile = commonOptions.isAssisted ? stageDir.getTempFile(ASSISTED_UI_FILE_NAME) : null await writeFile(projectFile, await this.writeManifest(appOutDir, arch, commonOptions)) if (uiFile !== null) { await writeFile(uiFile, await readFile(path.join(getTemplatePath("msi"), ASSISTED_UI_FILE_NAME), "utf8")) objectFiles.push(ASSISTED_UI_FILE_NAME.replace(".wxs", ".wixobj")) } // noinspection SpellCheckingInspection const vendorPath = await getBinFromUrl("wix", "4.0.0.5512.2", "/X5poahdCc3199Vt6AP7gluTlT1nxi9cbbHhZhCMEu+ngyP1LiBMn+oZX7QAZVaKeBMc2SjVp7fJqNLqsUnPNQ==") // noinspection SpellCheckingInspection const candleArgs = [ "-arch", arch === Arch.ia32 ? "x86" : (arch === Arch.armv7l ? "arm" : "x64"), `-dappDir=${vm.toVmFile(appOutDir)}`, ].concat(this.getCommonWixArgs()) candleArgs.push("project.wxs") if (uiFile !== null) { candleArgs.push(ASSISTED_UI_FILE_NAME) } await vm.exec(vm.toVmFile(path.join(vendorPath, "candle.exe")), candleArgs, { cwd: stageDir.dir, }) await this.light(objectFiles, vm, artifactPath, appOutDir, vendorPath, stageDir.dir) await stageDir.cleanup() await packager.sign(artifactPath) await packager.info.callArtifactBuildCompleted({ file: artifactPath, packager, arch, safeArtifactName: packager.computeSafeArtifactName(artifactName, "msi"), target: this, isWriteUpdateInfo: false, }) }
Eshva/electron-builder
packages/app-builder-lib/src/targets/MsiTarget.ts
TypeScript
MethodDeclaration
private async light(objectFiles: Array<string>, vm: VmManager, artifactPath: string, appOutDir: string, vendorPath: string, tempDir: string) { // noinspection SpellCheckingInspection const lightArgs = [ "-out", vm.toVmFile(artifactPath), "-v", // https://github.com/wixtoolset/issues/issues/5169 "-spdb", // https://sourceforge.net/p/wix/bugs/2405/ // error LGHT1076 : ICE61: This product should remove only older versions of itself. The Maximum version is not less than the current product. (1.1.0.42 1.1.0.42) "-sw1076", `-dappDir=${vm.toVmFile(appOutDir)}`, // "-dcl:high", ].concat(this.getCommonWixArgs()) // http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/Build-3-5-2229-0-give-me-the-following-error-error-LGHT0216-An-unexpected-Win32-exception-with-errorn-td5707443.html if (process.platform !== "win32") { // noinspection SpellCheckingInspection lightArgs.push("-sval") } if (this.options.oneClick === false) { lightArgs.push("-ext", "WixUIExtension") } // objectFiles - only filenames, we set current directory to our temp stage dir lightArgs.push(...objectFiles) await vm.exec(vm.toVmFile(path.join(vendorPath, "light.exe")), lightArgs, { cwd: tempDir, }) }
Eshva/electron-builder
packages/app-builder-lib/src/targets/MsiTarget.ts
TypeScript
MethodDeclaration
private getCommonWixArgs() { const args: Array<string> = ["-pedantic"] if (this.options.warningsAsErrors !== false) { args.push("-wx") } return args }
Eshva/electron-builder
packages/app-builder-lib/src/targets/MsiTarget.ts
TypeScript
MethodDeclaration
private async writeManifest(appOutDir: string, arch: Arch, commonOptions: FinalCommonWindowsInstallerOptions) { const appInfo = this.packager.appInfo const {files, dirs} = await this.computeFileDeclaration(appOutDir) const companyName = appInfo.companyName if (!companyName) { log.warn(`Manufacturer is not set for MSI — please set "author" in the package.json`) } const compression = this.packager.compression const options = this.options const iconPath = await this.packager.getIconPath() return (await projectTemplate.value)({ ...commonOptions, isCreateDesktopShortcut: commonOptions.isCreateDesktopShortcut !== DesktopShortcutCreationPolicy.NEVER, isRunAfterFinish: options.runAfterFinish !== false, iconPath: iconPath == null ? null : this.vm.toVmFile(iconPath), compressionLevel: compression === "store" ? "none" : "high", version: appInfo.getVersionInWeirdWindowsForm(), productName: appInfo.productName, upgradeCode: (options.upgradeCode || UUID.v5(appInfo.id, ELECTRON_BUILDER_UPGRADE_CODE_NS_UUID)).toUpperCase(), manufacturer: companyName || appInfo.productName, appDescription: appInfo.description, // https://stackoverflow.com/questions/1929038/compilation-error-ice80-the-64bitcomponent-uses-32bitdirectory programFilesId: arch === Arch.x64 ? "ProgramFiles64Folder" : "ProgramFilesFolder", // wix in the name because special wix format can be used in the name installationDirectoryWixName: getWindowsInstallationDirName(appInfo, commonOptions.isPerMachine === true), dirs, files, }) }
Eshva/electron-builder
packages/app-builder-lib/src/targets/MsiTarget.ts
TypeScript
MethodDeclaration
private async computeFileDeclaration(appOutDir: string) { const appInfo = this.packager.appInfo let isRootDirAddedToRemoveTable = false const dirNames = new Set<string>() const dirs: Array<string> = [] const fileSpace = " ".repeat(6) const commonOptions = getEffectiveOptions(this.options, this.packager) const files = await BluebirdPromise.map(walk(appOutDir), file => { const packagePath = file.substring(appOutDir.length + 1) const lastSlash = packagePath.lastIndexOf(path.sep) const fileName = lastSlash > 0 ? packagePath.substring(lastSlash + 1) : packagePath let directoryId: string | null = null let dirName = "" // Wix Directory.FileSource doesn't work - https://stackoverflow.com/questions/21519388/wix-filesource-confusion if (lastSlash > 0) { // This Name attribute may also define multiple directories using the inline directory syntax. // For example, "ProgramFilesFolder:\My Company\My Product\bin" would create a reference to a Directory element with Id="ProgramFilesFolder" then create directories named "My Company" then "My Product" then "bin" nested beneath each other. // This syntax is a shortcut to defining each directory in an individual Directory element. dirName = packagePath.substring(0, lastSlash) // https://github.com/electron-userland/electron-builder/issues/3027 directoryId = "d" + createHash("md5").update(dirName).digest("base64").replace(/\//g, "_").replace(/\+/g, ".").replace(/=+$/, "") if (!dirNames.has(dirName)) { dirNames.add(dirName) dirs.push(`<Directory Id="${directoryId}" Name="${ROOT_DIR_ID}:\\${dirName.replace(/\//g, "\\")}\\"/>`) } } else if (!isRootDirAddedToRemoveTable) { isRootDirAddedToRemoveTable = true } // since RegistryValue can be part of Component, *** *** *** *** *** *** *** *** *** wix cannot auto generate guid // https://stackoverflow.com/questions/1405100/change-my-component-guid-in-wix let result = `<Component${directoryId === null ? "" : ` Directory="${directoryId}"`}>` result += `\n${fileSpace} <File Name="${fileName}" Source="$(var.appDir)${path.sep}${packagePath}" ReadOnly="yes" KeyPath="yes"` const isMainExecutable = packagePath === `${appInfo.productFilename}.exe` if (isMainExecutable) { result += ' Id="mainExecutable"' } else if (directoryId === null) { result += ` Id="${path.basename(packagePath)}_f"` } const isCreateDesktopShortcut = commonOptions.isCreateDesktopShortcut !== DesktopShortcutCreationPolicy.NEVER if (isMainExecutable && (isCreateDesktopShortcut || commonOptions.isCreateStartMenuShortcut)) { result += `>\n` const shortcutName = commonOptions.shortcutName if (isCreateDesktopShortcut) { result += `${fileSpace} <Shortcut Id="desktopShortcut" Directory="DesktopFolder" Name="${shortcutName}" WorkingDirectory="APPLICATIONFOLDER" Advertise="yes" Icon="icon.ico"/>\n` } const hasMenuCategory = commonOptions.menuCategory != null const startMenuShortcutDirectoryId = hasMenuCategory ? "AppProgramMenuDir" : "ProgramMenuFolder" if (commonOptions.isCreateStartMenuShortcut) { if (hasMenuCategory) { dirs.push(`<Directory Id="${startMenuShortcutDirectoryId}" Name="ProgramMenuFolder:\\${commonOptions.menuCategory}\\"/>`) } result += `${fileSpace} <Shortcut Id="startMenuShortcut" Directory="${startMenuShortcutDirectoryId}" Name="${shortcutName}" WorkingDirectory="APPLICATIONFOLDER" Advertise="yes" Icon="icon.ico">\n` result += `${fileSpace} <ShortcutProperty Key="System.AppUserModel.ID" Value="${this.packager.appInfo.id}"/>\n` result += `${fileSpace} </Shortcut>\n` } result += `${fileSpace}</File>` if (hasMenuCategory) { result += `<RemoveFolder Id="${startMenuShortcutDirectoryId}" Directory="${startMenuShortcutDirectoryId}" On="uninstall"/>\n` } } else { result += `/>` } return `${result}\n${fileSpace}</Component>` }) return {dirs: listToString(dirs, 2), files: listToString(files, 3)} }
Eshva/electron-builder
packages/app-builder-lib/src/targets/MsiTarget.ts
TypeScript
InterfaceDeclaration
/** * The state of a pivot table section. */ export interface SectionState { /** * Indicates whether the section contents are currently being displayed. * * Otherwise only the total row is visible. */ open: boolean; }
codestothestars/react-pivot-table
src/sections/SectionState.tsx
TypeScript
ArrowFunction
() => { const CSV = `#group,false,false,true,true,false,true,true,true,true,true #datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,double,string,string,string,string #default,_result,,,,,,,,, ,result,table,_start,_stop,_time,_value,_field,_measurement,cpu,host ,,0,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:33Z,10,usage_guest,cpu,cpu-total,oox4k.local ,,1,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:43Z,20,usage_guest,cpu,cpu-total,oox4k.local #group,false,false,true,true,false,true,true,true,true,true #datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,string,string,string,string,string #default,_result,,,,,,,,, ,result,table,_start,_stop,_time,_value,_field,_measurement,cpu,host ,,2,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:33Z,thirty,usage_guest,cpu,cpu0,oox4k.local ,,3,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:43Z,fourty,usage_guest,cpu,cpu0,oox4k.local` const actual = fromFlux(CSV) expect(actual.table.getColumn('result', 'string')).toEqual([ '_result', '_result', '_result', '_result', ]) expect(actual.table.getColumn('_start', 'time')).toEqual([ 1549064312524, 1549064312524, 1549064312524, 1549064312524, ]) expect(actual.table.getColumn('_stop', 'time')).toEqual([ 1549064342524, 1549064342524, 1549064342524, 1549064342524, ]) expect(actual.table.getColumn('_time', 'time')).toEqual([ 1549064313000, 1549064323000, 1549064313000, 1549064323000, ]) expect(actual.table.getColumn('_value (number)', 'number')).toEqual([ 10, 20, undefined, undefined, ]) expect(actual.table.getColumn('_value (string)', 'string')).toEqual([ undefined, undefined, 'thirty', 'fourty', ]) expect(actual.table.getColumn('_field', 'string')).toEqual([ 'usage_guest', 'usage_guest', 'usage_guest', 'usage_guest', ]) expect(actual.table.getColumn('_measurement', 'string')).toEqual([ 'cpu', 'cpu', 'cpu', 'cpu', ]) expect(actual.table.getColumn('cpu', 'string')).toEqual([ 'cpu-total', 'cpu-total', 'cpu0', 'cpu0', ]) expect(actual.table.getColumn('host', 'string')).toEqual([ 'oox4k.local', 'oox4k.local', 'oox4k.local', 'oox4k.local', ]) expect(actual.table.getColumn('table', 'number')).toEqual([0, 1, 2, 3]) expect(actual.table.getColumnName('_value (number)')).toEqual('_value') expect(actual.table.getColumnName('_value (string)')).toEqual('_value') expect(actual.fluxGroupKeyUnion).toEqual([ '_value (number)', '_value (string)', '_start', '_stop', '_field', '_measurement', 'cpu', 'host', ]) }
bonitoo-io/giraffe
giraffe/src/utils/fromFlux.test.ts
TypeScript
ArrowFunction
() => { const CSV = `#group,false,false,true,true,true,true #datatype,string,long,string,string,long,long #default,_result,,,cpu,,6 ,result,table,a,b,c,d ,,1,usage_guest,,4, ,,1,usage_guest,,5,` const actual = fromFlux(CSV).table expect(actual.getColumn('result')).toEqual(['_result', '_result']) expect(actual.getColumn('a')).toEqual(['usage_guest', 'usage_guest']) expect(actual.getColumn('b')).toEqual(['cpu', 'cpu']) expect(actual.getColumn('c')).toEqual([4, 5]) expect(actual.getColumn('d')).toEqual([6, 6]) }
bonitoo-io/giraffe
giraffe/src/utils/fromFlux.test.ts
TypeScript
ArrowFunction
() => { const CSV = `#group,true,false,false,true #datatype,string,string,string,string #default,,,, ,a,b,c,d #group,false,false,true,false #datatype,string,string,string,string #default,,,, ,a,b,c,d` const {fluxGroupKeyUnion} = fromFlux(CSV) expect(fluxGroupKeyUnion).toEqual(['a', 'c', 'd']) }
bonitoo-io/giraffe
giraffe/src/utils/fromFlux.test.ts
TypeScript
ArrowFunction
() => { const CSV = `#group,false,false,true,true,false,true,true,true,true,true #datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,double,string,string,string,string #default,_result,,,,,,,,, ,result,table,_start,_stop,_time,_value,_field,_measurement,cpu,host ,,0,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:33Z,10,usage_guest,cpu,cpu-total,oox4k.local ,,1,2019-02-01T23:38:32.524234Z,2019-02-01T23:39:02.524234Z,2019-02-01T23:38:43Z,,usage_guest,cpu,cpu-total,oox4k.local` const {table} = fromFlux(CSV) expect(table.getColumn('_value')).toEqual([10, null]) }
bonitoo-io/giraffe
giraffe/src/utils/fromFlux.test.ts
TypeScript
ArrowFunction
() => { const CSV = `#group,false,false,false,false #datatype,string,long,string,long #default,_result,,, ,result,table,message,value ,,0,howdy,5 ,,0,"hello there",5 ,,0,hi,6 #group,false,false,false,false #datatype,string,long,string,long #default,_result,,, ,result,table,message,value ,,1,howdy,5 ,,1,"hello there",5 ,,1,hi,6` const {table} = fromFlux(CSV) expect(table.getColumn('value')).toEqual([5, 5, 6, 5, 5, 6]) expect(table.getColumn('message')).toEqual([ 'howdy', 'hello\n\nthere', 'hi', 'howdy', 'hello\n\nthere', 'hi', ]) }
bonitoo-io/giraffe
giraffe/src/utils/fromFlux.test.ts
TypeScript
ArrowFunction
() => ({ id: { type: GraphQLString }, name: { type: GraphQLString }, last4: { type: GraphQLString }, data: { type: GraphQLJSONObject }, privateData: { type: GraphQLJSONObject }, provider: { type: VirtualCardProvider }, })
WikiRik/opencollective-api
server/graphql/v2/input/VirtualCardInput.ts
TypeScript
InterfaceDeclaration
interface language
MaxiCoinDev/MaxiCoin
src/qt/locale/bitcoin_bg.ts
TypeScript
InterfaceDeclaration
interface and
MaxiCoinDev/MaxiCoin
src/qt/locale/bitcoin_bg.ts
TypeScript
InterfaceDeclaration
/** * Transaction details. */ export interface TransactionDetails { /** * the Transaction Id can be used as access-ID in the API, where more details on an transaction is offered. If this data attribute is provided this shows that the AIS can get access on more details about this transaction using the Get transaction details request. */ transactionId?: string; /** * Is the identification of the transaction as used e.g. for reference for deltafunction on application level. The same identification as for example used within camt.05x messages. */ entryReference?: string; /** * Unique end to end identity. */ endToEndId?: string; /** * Identification of Mandates, e.g. a SEPA Mandate ID. */ mandateId?: string; /** * Identification of a Cheque. */ checkId?: string; /** * Identification of Creditors, e.g. a SEPA Creditor ID. */ creditorId?: string; /** * The date when an entry is posted to an account on the ASPSPs books. */ bookingDate?: string; /** * The Date at which assets become available to the account owner in case of a credit. */ valueDate?: string; transactionAmount: Amount; /** * Array of exchange rates. */ currencyExchange?: Array<ReportExchangeRate>; /** * Creditor Name. */ creditorName?: string; creditorAccount?: AccountReference; /** * Ultimate Creditor. */ ultimateCreditor?: string; /** * Debtor Name. */ debtorName?: string; debtorAccount?: AccountReference; /** * Ultimate Debtor. */ ultimateDebtor?: string; /** * Unstructured remittance information. */ remittanceInformationUnstructured?: string; /** * Reference as contained in the structured remittance reference structure (without the surrounding XML structure). Different from other places the content is containt in plain form not in form of a structered field. */ remittanceInformationStructured?: string; /** * Might be used by the ASPSP to transport additional transaction related information to the PSU. */ additionalInformation?: string; purposeCode?: PurposeCode; /** * Bank transaction code as used by the ASPSP and using the sub elements of this structured code defined by ISO 20022. This code type is concatenating the three ISO20022 Codes * Domain Code, * Family Code, and * SubFamiliy Code by hyphens, resulting in �DomainCode�-�FamilyCode�-�SubFamilyCode�. */ bankTransactionCode?: string; /** * Proprietary bank transaction code as used within a community or within an ASPSP e.g. for MT94x based transaction reports. */ proprietaryBankTransactionCode?: string; }
Guillerbr/open-banking-gateway
fintech-examples/fintech-ui/src/app/api/model/transactionDetails.ts
TypeScript
ClassDeclaration
@Injectable({ providedIn: 'root' }) export class UserinfoService { private usersUrl = 'https://localhost:8443/users'; private friendsUrl = 'https://localhost:8443/friends'; constructor(private http: HttpClient,private router: Router) { } getUser(user: string): Observable<User>{ return this.http.get<User>(this.usersUrl+"/"+user); } getUserByID(id:number): Observable<User> { const url = this.usersUrl + '/getbyid/' + id; return this.http.get<User>(url); } getFriendsAndRequests(id:number): Observable<Friends[]> { return this.http.get<Friends[]>(this.friendsUrl+ '/findall/' + id); } sendFriendRequest(u1:number,u2:number): Observable<Friends>{ var friends:Friends; friends=new Friends(); friends.user_one=u1; friends.user_two=u2; friends.state="pending"; return this.http.post<Friends>(this.friendsUrl,friends); } getFriends(id:number): Observable<Friends[]> { return this.http.get<Friends[]>(this.friendsUrl+ '/' + id); } }
LtVaios/My-LinkedIn
frontend/src/app/userinfo/userinfo.service.ts
TypeScript
MethodDeclaration
getUser(user: string): Observable<User>{ return this.http.get<User>(this.usersUrl+"/"+user); }
LtVaios/My-LinkedIn
frontend/src/app/userinfo/userinfo.service.ts
TypeScript
MethodDeclaration
getUserByID(id:number): Observable<User> { const url = this.usersUrl + '/getbyid/' + id; return this.http.get<User>(url); }
LtVaios/My-LinkedIn
frontend/src/app/userinfo/userinfo.service.ts
TypeScript
MethodDeclaration
getFriendsAndRequests(id:number): Observable<Friends[]> { return this.http.get<Friends[]>(this.friendsUrl+ '/findall/' + id); }
LtVaios/My-LinkedIn
frontend/src/app/userinfo/userinfo.service.ts
TypeScript
MethodDeclaration
sendFriendRequest(u1:number,u2:number): Observable<Friends>{ var friends:Friends; friends=new Friends(); friends.user_one=u1; friends.user_two=u2; friends.state="pending"; return this.http.post<Friends>(this.friendsUrl,friends); }
LtVaios/My-LinkedIn
frontend/src/app/userinfo/userinfo.service.ts
TypeScript
MethodDeclaration
getFriends(id:number): Observable<Friends[]> { return this.http.get<Friends[]>(this.friendsUrl+ '/' + id); }
LtVaios/My-LinkedIn
frontend/src/app/userinfo/userinfo.service.ts
TypeScript
ClassDeclaration
export default class Vote implements Model { id: string; decision: VOTE_DECISION; event_minutes_item_ref: string; event_minutes_item?: EventMinutesItem; event_ref: string; event?: Event; external_source_id?: string; in_majority?: boolean; matter_ref: string; matter?: Matter; person_ref: string; person?: Person; constructor(jsonData: ResponseData) { this.id = jsonData["id"]; this.event_minutes_item_ref = jsonData["event_minutes_item_ref"].id; this.event_ref = jsonData["event_ref"].id; this.matter_ref = jsonData["matter_ref"].id; this.person_ref = jsonData["person_ref"].id; this.decision = jsonData["decision"]; if ( typeof jsonData["event_ref"] === "object" && !(jsonData["event_ref"] instanceof DocumentReference) ) { this.event = new Event(jsonData["event_ref"]); } if ( typeof jsonData["event_minutes_item_ref"] === "object" && !(jsonData["event_minutes_item_ref"] instanceof DocumentReference) ) { this.event_minutes_item = new EventMinutesItem(jsonData["event_minutes_item_ref"]); } if (jsonData["external_source_id"]) { this.external_source_id = jsonData["external_source_id"]; } if (jsonData["in_majority"]) { this.in_majority = jsonData["in_majority"]; } if ( typeof jsonData["matter_ref"] === "object" && !(jsonData["matter_ref"] instanceof DocumentReference) ) { this.matter = new Matter(jsonData["matter_ref"]); } if ( typeof jsonData["person_ref"] === "object" && !(jsonData["person_ref"] instanceof DocumentReference) ) { this.person = new Person(jsonData["person_ref"]); } } }
CouncilDataProject/cdp-instance
src/models/Vote.ts
TypeScript
ArrowFunction
role => member.roles.has(role.id)
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
ArrowFunction
c => c.id === channel.id
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
ArrowFunction
r => setTimeout(() => r(this.minify()), 50)
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
ArrowFunction
() => r(this.minify())
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
ArrowFunction
c => `${c.get("userID")}`
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
ArrowFunction
r => [message.guild.id].includes(r.id)
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
ArrowFunction
(num, word) => (text.includes(word) ? num + 2 : num)
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
ArrowFunction
(num, word) => (text.includes(word) ? num + 1 : num)
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public static generateXp(level: number): number { if (level >= 60) { return level * 20; } if (level >= 35) { return level * 10; } else if (level >= 27) { return Leveling.randomNum(110, 115); } else { return Leveling.randomNum(10, 15); } }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public static randomNum(min: number, max: number): number { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public static checkEligibility( member: GuildMember, channel: TextChannel ): boolean { const excludedRoles: Role[] = (member.guild as FoxGuild).leveling .excludedRoles; const excludedChannels: TextChannel[] = (member.guild as FoxGuild).leveling .excludedChannels; if ( excludedRoles.length && excludedRoles.some(role => member.roles.has(role.id)) ) { return undefined; } else if ( excludedChannels.length && excludedChannels.some(c => c.id === channel.id) ) { return undefined; } return true; }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public async _loadSettings(): Promise<void> { const settings: FoxLeveling = await this.guild.client.mongo.leveling.findOne( { guildID: this.guild.id, type: "settings" } ); if (!settings) { const levelsettings: FoxLeveling = new this.guild.client.mongo.leveling({ guildID: this.guild.id, type: "settings" }); await levelsettings.save(); } else { for (const key of Object.keys(this)) { if (key === "guild") { continue; } const value: any = settings.get(key); if (value === undefined) { continue; } this[key] = value; } } }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public minify(): Leveling { // @ts-ignore const current: Leveling = { ...this }; delete current.guild; return current; }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public async set(key: string, value: any): Promise<boolean | Object> { const settings: FoxLeveling = await this.guild.client.mongo.leveling.findOne( { guildID: this.guild.id, type: "settings" } ); if (!settings) { return false; } if (!this.hasOwnProperty(key)) { return; } await settings.unset(key); await settings.set({ [key]: value }); await settings.save(); await this._loadSettings(); return new Promise(r => setTimeout(() => r(this.minify()), 50)); }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public async listen(message: FoxMessage): Promise<void> { if (!message.guild) { return; } if (message.content.startsWith(message.guild.config.prefix)) { return; } if (!message.guild.packages.get("Leveling").enabled) { return; } if (!Leveling.validate(message)) { return; } const isEligible: boolean = Leveling.checkEligibility( message.member, message.channel ); if (!isEligible) { return; } await LevelMigrate(message); await this._loadSettings(); const memberdata: FoxLeveling = await this.guild.client.mongo.leveling.findOne( { guildID: message.guild.id, userID: message.author.id } ); if (memberdata) { const level: number = memberdata.get("level"); const calculatedXp: number = Leveling.generateXp(level); memberdata.set({ xp: memberdata.get("xp") + calculatedXp, totalXP: memberdata.get("totalXP") + calculatedXp }); await memberdata.save(); if (memberdata.get("xp") >= memberdata.get("tonextlevel")) { memberdata.set({ xp: 0, level: memberdata.get("level") + 1, tonextlevel: Math.round(memberdata.get("tonextlevel") * 1.19) }); await memberdata.save(); message.client.emit("levelUp", message, memberdata.get("level")); } } else { const entry: FoxLeveling = new this.guild.client.mongo.leveling({ guildID: message.guild.id, userID: message.author.id, level: 1, xp: 0, totalXP: 0, tonextlevel: 100 }); await entry.save(); } }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public async rankOf(member: any): Promise<number> { const data: FoxLeveling[] = await member.client.mongo.leveling .sort("totalXP", "desc") .find({ guildID: member.guild.id }); const mapped: string[] = data.map(c => `${c.get("userID")}`); return mapped.indexOf(member.id) + 1; }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public async levelOf(member: any): Promise<number> { const entry: FoxLeveling = await member.client.mongo.leveling.findOne({ guildID: member.guild.id, userID: member.id }); if (!entry) { return undefined; } return entry.get("level"); }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
MethodDeclaration
public static validate(message: FoxMessage): boolean | number { const text: string = message.content.toLowerCase(); const mentions: MessageMentions = message.mentions; const substantialWords: string[] = [ "js", "javascript", "node", "nodejs", "code", "pars", "script", "clojure", "sql", "discord", "moment", "snekfetch", "dithcord", "guide", "video", "bot", "dev", "git", "github", "discord.js", "snekie", "mod.banhammer", "mrfox", "rtexel", "jacz", "the", "this", "that", "hello" // @ts-ignore ].concat(Object.keys(process.binding("natives"))); // Words that might indicate that this message is lower quality const insubstantialWords: string[] = [ "lol", "lul", "lel", "kek", "xd", "¯\\_(ツ)_/¯", "dicksword", "gus", "kys", "dumbass", "!", "-", ".", message.guild.config.prefix ]; const necessarySubstance: number = 10; if (mentions.roles.some(r => [message.guild.id].includes(r.id))) { return false; } let substance: number = 0; if (text.length > "lol xD".length) (substance += 400) * ((substance - 5) / 1995) + 7; // tslint:disable-line substance += substantialWords.reduce( (num, word) => (text.includes(word) ? num + 2 : num), 0 ); substance -= insubstantialWords.reduce( (num, word) => (text.includes(word) ? num + 1 : num), 0 ); if (mentions.users.size > 0) { substance -= mentions.users.size; } else if (mentions.roles.size > 3) { substance -= mentions.roles.size; } else if (mentions.channels.size > 5) { substance -= mentions.channels.size; } else { substance += 2; } return substance >= necessarySubstance; }
Texlo-Dev/fox-legacy
src/util/leveling/LevelSettings.ts
TypeScript
ArrowFunction
invitation => { this.invitation = invitation; if (this.invitation.status != "pending") { // If the invitation is valid but its status is not "pending", throw a 404 error this.error({ status: 404, statusText: "Invitation Not Found", json: function() { return {}; } }); } else { this.dataLoaded["invitation"] = true; } }
orimarti/apicurio-studio
front-end/studio/src/app/pages/apis/{apiId}/collaboration/accept/api-accept.page.ts
TypeScript
ArrowFunction
error => { console.error("[ApiAcceptPageComponent] Error getting API"); this.error(error); }
orimarti/apicurio-studio
front-end/studio/src/app/pages/apis/{apiId}/collaboration/accept/api-accept.page.ts
TypeScript
ArrowFunction
() => { let link: string[] = [ "/apis", this.invitation.designId ]; console.info("[ApiAcceptPageComponent] Navigating to: %o", link); this.router.navigate(link); }
orimarti/apicurio-studio
front-end/studio/src/app/pages/apis/{apiId}/collaboration/accept/api-accept.page.ts
TypeScript
ArrowFunction
error => { this.error(error); }
orimarti/apicurio-studio
front-end/studio/src/app/pages/apis/{apiId}/collaboration/accept/api-accept.page.ts
TypeScript
ClassDeclaration
@Component({ moduleId: module.id, selector: "api-accept-page", templateUrl: "api-accept.page.html", styleUrls: ["api-accept.page.css"] }) export class ApiAcceptPageComponent extends AbstractPageComponent { public invitation: Invitation; public _accepting: boolean = false; /** * Constructor. * @param {Router} router * @param {ActivatedRoute} route * @param {IApisService} apis */ constructor(private router: Router, route: ActivatedRoute, @Inject(IApisService) private apis: IApisService) { super(route); } /** * Called to kick off loading the page's async data. * @param params */ public loadAsyncPageData(params: any): void { console.info("[ApiAcceptPageComponent] Loading async page data"); let apiId: string = params["apiId"]; let inviteId: string = params["inviteId"]; this.apis.getInvitation(apiId, inviteId).then(invitation => { this.invitation = invitation; if (this.invitation.status != "pending") { // If the invitation is valid but its status is not "pending", throw a 404 error this.error({ status: 404, statusText: "Invitation Not Found", json: function() { return {}; } }); } else { this.dataLoaded["invitation"] = true; } }).catch(error => { console.error("[ApiAcceptPageComponent] Error getting API"); this.error(error); }); } /** * Called to accept the invite. */ public acceptInvitation(): void { this._accepting = true; this.apis.acceptInvitation(this.invitation.designId, this.invitation.inviteId).then( () => { let link: string[] = [ "/apis", this.invitation.designId ]; console.info("[ApiAcceptPageComponent] Navigating to: %o", link); this.router.navigate(link); }).catch( error => { this.error(error); }); } /** * Called to reject the invite. */ public rejectInvitation(): void { // this.apis.rejectInvitation(this.invitation.designId, this.invitation.inviteId); let link: string[] = [ "/" ]; this.router.navigate(link); } }
orimarti/apicurio-studio
front-end/studio/src/app/pages/apis/{apiId}/collaboration/accept/api-accept.page.ts
TypeScript
MethodDeclaration
/** * Called to kick off loading the page's async data. * @param params */ public loadAsyncPageData(params: any): void { console.info("[ApiAcceptPageComponent] Loading async page data"); let apiId: string = params["apiId"]; let inviteId: string = params["inviteId"]; this.apis.getInvitation(apiId, inviteId).then(invitation => { this.invitation = invitation; if (this.invitation.status != "pending") { // If the invitation is valid but its status is not "pending", throw a 404 error this.error({ status: 404, statusText: "Invitation Not Found", json: function() { return {}; } }); } else { this.dataLoaded["invitation"] = true; } }).catch(error => { console.error("[ApiAcceptPageComponent] Error getting API"); this.error(error); }); }
orimarti/apicurio-studio
front-end/studio/src/app/pages/apis/{apiId}/collaboration/accept/api-accept.page.ts
TypeScript
MethodDeclaration
/** * Called to accept the invite. */ public acceptInvitation(): void { this._accepting = true; this.apis.acceptInvitation(this.invitation.designId, this.invitation.inviteId).then( () => { let link: string[] = [ "/apis", this.invitation.designId ]; console.info("[ApiAcceptPageComponent] Navigating to: %o", link); this.router.navigate(link); }).catch( error => { this.error(error); }); }
orimarti/apicurio-studio
front-end/studio/src/app/pages/apis/{apiId}/collaboration/accept/api-accept.page.ts
TypeScript
MethodDeclaration
/** * Called to reject the invite. */ public rejectInvitation(): void { // this.apis.rejectInvitation(this.invitation.designId, this.invitation.inviteId); let link: string[] = [ "/" ]; this.router.navigate(link); }
orimarti/apicurio-studio
front-end/studio/src/app/pages/apis/{apiId}/collaboration/accept/api-accept.page.ts
TypeScript
ArrowFunction
(source: Id<Source>, limit: number) => { for (let op of Memory.respawnManager.remoteMiningOperations) { if (op.id === source) { op.limit = limit; return; } } Memory.respawnManager.remoteMiningOperations.push({ id: source, limit: limit }); }
HappyCerberus/screeps
src/globals.ts
TypeScript
ArrowFunction
(source: Id<Source>, limit: number) => { for (let op of Memory.respawnManager.remoteBuildingOperations) { if (op.id === source) { op.limit = limit; return; } } Memory.respawnManager.remoteBuildingOperations.push({ id: source, limit: limit }); }
HappyCerberus/screeps
src/globals.ts
TypeScript
ArrowFunction
(room: string, limit: number) => { for (let op of Memory.respawnManager.remoteRaidOperations) { if (op.room === room) { op.limit = limit; return; } } Memory.respawnManager.remoteRaidOperations.push({ room: room, limit: limit }); }
HappyCerberus/screeps
src/globals.ts
TypeScript
ArrowFunction
(room: string) => { for (let op of Memory.respawnManager.scoutOperations) { if (op.room === room) { return; } } Memory.respawnManager.scoutOperations.push({ room: room }); }
HappyCerberus/screeps
src/globals.ts
TypeScript
ArrowFunction
(room: string) => { for (let i = 0; i < Memory.respawnManager.scoutOperations.length; i++) { if (Memory.respawnManager.scoutOperations[i].room === room) { Memory.respawnManager.scoutOperations.splice(i, 1); return; } } }
HappyCerberus/screeps
src/globals.ts
TypeScript
ArrowFunction
(room: string, ownership: DesiredOwnership) => { if (!Memory.rooms[room]) { Memory.rooms[room] = {}; } Memory.rooms[room].respawnManager = { desiredOwnership: ownership, ...Memory.rooms[room].respawnManager }; }
HappyCerberus/screeps
src/globals.ts
TypeScript
ArrowFunction
(room: string, chunk: string) => { if (!Memory.chunks) { Memory.chunks = {}; } if (!Memory.chunks[chunk]) { Memory.chunks[chunk] = { rooms: [room] }; return; } if (Memory.chunks[chunk].rooms.includes(room)) return; Memory.chunks[chunk] = { rooms: [room, ...Memory.chunks[chunk].rooms] }; }
HappyCerberus/screeps
src/globals.ts
TypeScript
ArrowFunction
(room: string, chunk: string) => { if (!Memory.chunks || !Memory.chunks[chunk]) { return; } const rooms = Memory.chunks[chunk].rooms; for (let i = 0; i < rooms.length; i++) { if (rooms[i] === room) { rooms.splice(i, 1); return; } } }
HappyCerberus/screeps
src/globals.ts
TypeScript
ClassDeclaration
export class Job { constructor(public type: string, public target?: AnyStructure | ConstructionSite | Resource<ResourceConstant>) { } }
HappyCerberus/screeps
src/globals.ts
TypeScript
ClassDeclaration
/** * This is a wrapper class around the API client for your Cog. An instance of * this class is passed to the constructor of each of your steps, and can be * accessed on each step as this.client. */ export class ClientWrapper { /** * This is an array of field definitions, each corresponding to a field that * your API client requires for authentication. Depending on the underlying * system, this could include bearer tokens, basic auth details, endpoints, * etc. * * If your Cog does not require authentication, set this to an empty array. */ public static expectedAuthFields: Field[] = [{ field: 'userAgent', type: FieldDefinition.Type.STRING, description: 'User Agent String', }]; /** * Private instance of the wrapped API client. You will almost certainly want * to swap this out for an API client specific to your Cog's needs. */ private client: any; /** * Constructs an instance of the ClientWwrapper, authenticating the wrapped * client in the process. * * @param auth - An instance of GRPC Metadata for a given RunStep or RunSteps * call. Will be populated with authentication metadata according to the * expectedAuthFields array defined above. * * @param clientConstructor - An optional parameter Used only as a means to * simplify automated testing. Should default to the class/constructor of * the underlying/wrapped API client. */ constructor (auth: grpc.Metadata, clientConstructor = {}) { // Call auth.get() for any field defined in the static expectedAuthFields // array here. The argument passed to get() should match the "field" prop // declared on the definition object above. const uaString: string = auth.get('userAgent').toString(); this.client = clientConstructor; // Authenticate the underlying client here. this.client.defaults = { user_agent: uaString }; } }
amcpanaligan/cog-pardot
src/client/client-wrapper.ts
TypeScript
FunctionDeclaration
export default function Cart(props: SvgProps) { return ( <Svg viewBox="0 0 16 16" height="25" width="25" fill="currentColor" {...props}> <Path d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .49.598l-1 5a.5.5 0 0 1-.465.401l-9.397.472L4.415 11H13a.5.5 0 0 1 0 1H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l.84 4.479 9.144-.459L13.89 4H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 1 0 2 1 1 0 0 1 0-2zm7 0a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"></Path> </Svg> ); }
Growth-UI/Growth-UI-Native
packages/growth-ui-native/src/atoms/Icon/Cart.tsx
TypeScript
ArrowFunction
(_get, set, _data) => { return set(checkoutAtom, defaultCheckout); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).billing_address
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set, data: Address) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, billing_address: data }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).shipping_address
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set, data: Address) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, shipping_address: data }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).delivery_time
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set, data: DeliveryTime) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, delivery_time: data }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).payment_gateway
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set, data: PaymentMethodName) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, payment_gateway: data }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).token
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set, data: string) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, token: data }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).customer_contact
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set, data: string) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, customer_contact: data }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).verified_response
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set, data: VerifiedResponse | null) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, verified_response: data }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).coupon
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set, data: Coupon | null) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, coupon: data }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).coupon?.amount
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).use_wallet
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, use_wallet: !prev.use_wallet }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get) => get(checkoutAtom).payable_amount
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
ArrowFunction
(get, set, data: number) => { const prev = get(checkoutAtom); return set(checkoutAtom, { ...prev, payable_amount: data }); }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
InterfaceDeclaration
interface DeliveryTime { id: string; title: string; description: string; }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
InterfaceDeclaration
interface VerifiedResponse { total_tax: number; shipping_charge: number; unavailable_products: any[]; wallet_amount: number; wallet_currency: number; }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
InterfaceDeclaration
interface CheckoutState { billing_address: Address | null; shipping_address: Address | null; payment_gateway: PaymentMethodName; delivery_time: DeliveryTime | null; customer_contact: string; verified_response: VerifiedResponse | null; coupon: Coupon | null; payable_amount: number; use_wallet: boolean; [key: string]: unknown; }
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
TypeAliasDeclaration
export type PaymentMethodName = 'CASH_ON_DELIVERY' | 'STRIPE';
lazynerd-studios/Grrenline-cart
shop/src/store/checkout.ts
TypeScript
FunctionDeclaration
export default function (params) { if (!params) return if (Object.keys(params).length === 0) return const fields = {} for (const key of Object.keys(params)) { try { const type = getField(params[key].type) fields[key] = {type} } catch (error) { throw new Error(`Error creating GraphQL resolver params argument ${key}: ${error.message}`) } } return fields }
ConsueloHerrera/orionjs
packages/graphql/src/buildSchema/getArgs/index.ts
TypeScript
FunctionDeclaration
export function resetPluginBackgroundStatsDelta() { pluginBackgroundStats.forEach(stat => { stat.cpuTimeDelta = 0; stat.messageCountDelta = 0; }); }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
FunctionDeclaration
export function getPluginBackgroundStats(): { cpuTime: number; // amount of ms cpu used since the last stats (typically every minute) byPlugin: {[plugin: string]: StatEntry}; } { let cpuTime: number = 0; const byPlugin = Array.from(pluginBackgroundStats.entries()).reduce( (aggregated, [pluginName, data]) => { cpuTime += data.cpuTimeDelta; aggregated[pluginName] = data; return aggregated; }, {} as {[plugin: string]: StatEntry}, ); return { cpuTime, byPlugin, }; }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
FunctionDeclaration
function addBackgroundStat(plugin: string, cpuTime: number) { if (!pluginBackgroundStats.has(plugin)) { pluginBackgroundStats.set(plugin, { cpuTimeDelta: 0, cpuTimeTotal: 0, messageCountDelta: 0, messageCountTotal: 0, maxTime: 0, }); } const stat = pluginBackgroundStats.get(plugin)!; stat.cpuTimeDelta += cpuTime; stat.cpuTimeTotal += cpuTime; stat.messageCountDelta += 1; stat.messageCountTotal += 1; stat.maxTime = Math.max(stat.maxTime, cpuTime); if (cpuTime > MAX_BACKGROUND_TASK_TIME) { console.warn( `Plugin ${plugin} took too much time while doing background: ${cpuTime}ms. Handling background messages should take less than ${MAX_BACKGROUND_TASK_TIME}ms.`, ); } }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
FunctionDeclaration
function processMessage( state: State, pluginKey: string, plugin: { id: string; persistedStateReducer: PersistedStateReducer | null; }, message: {method: string; params?: any}, ): State { const statName = `${plugin.id}.${message.method}`; const reducerStartTime = Date.now(); flipperRecorderAddEvent(pluginKey, message.method, message.params); try { const newPluginState = plugin.persistedStateReducer!( state, message.method, message.params, ); addBackgroundStat(statName, Date.now() - reducerStartTime); return newPluginState; } catch (e) { console.error(`Failed to process event for plugin ${plugin.id}`, e); return state; } }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
FunctionDeclaration
export function processMessageImmediately( store: MiddlewareAPI, pluginKey: string, plugin: { defaultPersistedState: any; id: string; persistedStateReducer: PersistedStateReducer | null; }, message: {method: string; params?: any}, ) { const persistedState = getCurrentPluginState(store, plugin, pluginKey); const newPluginState = processMessage( persistedState, pluginKey, plugin, message, ); if (persistedState !== newPluginState) { store.dispatch( setPluginState({ pluginKey, state: newPluginState, }), ); } }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
FunctionDeclaration
export function processMessageLater( store: MiddlewareAPI, pluginKey: string, plugin: { defaultPersistedState: any; id: string; persistedStateReducer: PersistedStateReducer | null; maxQueueSize?: number; }, message: {method: string; params?: any}, ) { const isSelected = pluginKey === getSelectedPluginKey(store.getState().connections); switch (true) { case plugin.id === 'Navigation': // Navigation events are always processed, to make sure the navbar stays up to date case isSelected && getPendingMessages(store, pluginKey).length === 0: processMessageImmediately(store, pluginKey, plugin, message); break; case isSelected: case plugin instanceof FlipperDevicePlugin: case pluginIsStarred(store.getState().connections, plugin.id): store.dispatch( queueMessage( pluginKey, message.method, message.params, plugin.maxQueueSize, ), ); break; // In all other cases, messages will be dropped... } }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
FunctionDeclaration
export async function processMessageQueue( plugin: { defaultPersistedState: any; id: string; persistedStateReducer: PersistedStateReducer | null; }, pluginKey: string, store: MiddlewareAPI, progressCallback?: (progress: {current: number; total: number}) => void, idler: BaseIdler = new Idler(), ): Promise<boolean> { if (!plugin.persistedStateReducer) { return true; } const total = getPendingMessages(store, pluginKey).length; let progress = 0; do { const messages = getPendingMessages(store, pluginKey); if (!messages.length) { break; } // there are messages to process! lets do so until we have to idle const persistedState = getCurrentPluginState(store, plugin, pluginKey); let offset = 0; let newPluginState = persistedState; do { newPluginState = processMessage( newPluginState, pluginKey, plugin, messages[offset], ); offset++; progress++; progressCallback?.({ total: Math.max(total, progress), current: progress, }); } while (offset < messages.length && !idler.shouldIdle()); // save progress // by writing progress away first and then idling, we make sure this logic is // resistent to kicking off this process twice; grabbing, processing messages, saving state is done synchronosly // until the idler has to break store.dispatch(clearMessageQueue(pluginKey, offset)); if (newPluginState !== persistedState) { store.dispatch( setPluginState({ pluginKey, state: newPluginState, }), ); } if (idler.isCancelled()) { return false; } await idler.idle(); // new messages might have arrived, so keep looping } while (getPendingMessages(store, pluginKey).length); return true; }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
FunctionDeclaration
function getPendingMessages( store: MiddlewareAPI, pluginKey: string, ): Message[] { return store.getState().pluginMessageQueue[pluginKey] || []; }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
FunctionDeclaration
function getCurrentPluginState( store: MiddlewareAPI, plugin: {defaultPersistedState: any}, pluginKey: string, ) { // possible optimization: don't spread default state here by put proper default state when initializing clients return { ...plugin.defaultPersistedState, ...store.getState().pluginStates[pluginKey], }; }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
ArrowFunction
stat => { stat.cpuTimeDelta = 0; stat.messageCountDelta = 0; }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
ArrowFunction
(aggregated, [pluginName, data]) => { cpuTime += data.cpuTimeDelta; aggregated[pluginName] = data; return aggregated; }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript
ArrowFunction
() => { console.table( Array.from(pluginBackgroundStats.entries()).map( ([ plugin, { cpuTimeDelta, cpuTimeTotal, messageCountDelta, messageCountTotal, maxTime, }, ]) => ({ plugin, cpuTimeTotal, messageCountTotal, cpuTimeDelta, messageCountDelta, maxTime, }), ), ); }
PalDeshpande/flipper
src/utils/messageQueue.tsx
TypeScript