text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.shibing624</groupId> <artifactId>similarity</artifactId> <version>1.1.6</version> <name>similarity</name> <description>compare text similarity for java</description> <url>path_to_url <licenses> <license> <url>path_to_url <distribution>repo</distribution> </license> </licenses> <developers> <developer> <name>XuMing</name> <email>shibing624@126.com</email> </developer> </developers> <scm> <connection>scm:git:git@github.com:shibing624/similarity.git</connection> <developerConnection>scm:git:git@github.com:shibing624/similarity.git</developerConnection> <url>git@github.com:shibing624/similarity.git</url> </scm> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <junit.version>4.13.1</junit.version> <slf4j.version>1.7.7</slf4j.version> <logback.version>1.3.12</logback.version> <commons.lang3.version>3.3.1</commons.lang3.version> </properties> <dependencies> <!-- --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-access</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <!-- --> <dependency> <groupId>com.hankcs</groupId> <artifactId>hanlp</artifactId> <version>portable-1.3.4</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>args4j</groupId> <artifactId>args4j</artifactId> <version>2.0.16</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>13.0.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons.lang3.version}</version> </dependency> <dependency> <groupId>com.google.collections</groupId> <artifactId>google-collections</artifactId> <version>1.0</version> </dependency> <!-- --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies> <repositories> <repository> <id>cengtral</id> <url>path_to_url </repository> <!-- java.net maven repository, for example java mail --> <repository> <id>Java.Net</id> <url>path_to_url </repository> <repository> <id>ansj-repo</id> <url>path_to_url </repository> <repository> <id>info-bliki-repository</id> <url>path_to_url <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>lib_id</id> <url>file://${project.basedir}/lib</url> </repository> </repositories> <distributionManagement> <snapshotRepository> <id>ossrh</id> <url>path_to_url </snapshotRepository> <repository> <id>ossrh</id> <url>path_to_url </repository> </distributionManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <id>attach-sources</id> <phase>verify</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.16</version> </plugin> <plugin> <groupId>org.sonatype.plugins</groupId> <artifactId>nexus-staging-maven-plugin</artifactId> <version>1.6.7</version> <extensions>true</extensions> <configuration> <serverId>ossrh</serverId> <nexusUrl>path_to_url <autoReleaseAfterClose>true</autoReleaseAfterClose> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.5.3</version> <configuration> <autoVersionSubmodules>true</autoVersionSubmodules> <useReleaseProfile>false</useReleaseProfile> <releaseProfiles>release</releaseProfiles> <goals>deploy</goals> </configuration> </plugin> </plugins> <finalName>${project.artifactId}-${project.version}</finalName> </build> </project> ```
/content/code_sandbox/pom.xml
xml
2016-11-09T02:02:01
2024-08-15T06:43:20
similarity
shibing624/similarity
1,389
1,656
```xml import { Region } from '../types/common' import * as cuid from 'scuid' import { sum } from 'lodash' async function runPing(url: string): Promise<number> { const pingUrl = async () => { const start = Date.now() if (process.env.NODE_ENV !== 'test') { await fetch(url) } return Date.now() - start } const pings = await Promise.all([0, 0].map(pingUrl)) return sum(pings) / pings.length } export const regions: Region[] = ['EU_WEST_1', 'AP_NORTHEAST_1', 'US_WEST_2'] export async function getPing(region: Region): Promise<number> { return runPing(getPingUrl(region)) } export async function getFastestRegion(): Promise<Region> { const pingResults = await Promise.all( regions.map(async (region: Region) => { const ping = await getPing(region) return { region, ping, } }), ) const fastestRegion: { region: Region; ping: number } = pingResults.reduce( (min, curr) => { if (curr.ping < min.ping) { return curr } return min }, { region: 'EU_WEST_1', ping: Infinity }, ) return fastestRegion.region } export const getDynamoUrl = (region: string) => `path_to_url{region.toLowerCase().replace(/_/g, '-')}.amazonaws.com` const getPingUrl = (region: string) => `${getDynamoUrl(region)}/ping?x=${cuid()}` ```
/content/code_sandbox/cli/packages/prisma-cli-engine/src/Client/ping.ts
xml
2016-09-25T12:54:40
2024-08-16T11:41:23
prisma1
prisma/prisma1
16,549
359
```xml import type { Ref } from 'react'; import { forwardRef } from 'react'; import type { ButtonProps } from '@proton/atoms'; import { Button } from '@proton/atoms'; export type UnderlineButtonProps = Omit<ButtonProps, 'shape'>; const UnderlineButton = (props: UnderlineButtonProps, ref: Ref<HTMLButtonElement>) => { return <Button shape="underline" color="norm" ref={ref} {...props} />; }; export default forwardRef<HTMLButtonElement, UnderlineButtonProps>(UnderlineButton); ```
/content/code_sandbox/packages/components/components/button/UnderlineButton.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
119
```xml /* * Wire * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see path_to_url * */ import {RegisteredClient} from '@wireapp/api-client/lib/client'; import {weeksPassedSinceDate} from 'Util/TimeUtil'; export const wasClientActiveWithinLast4Weeks = ({last_active: lastActiveISODate}: RegisteredClient): boolean => { //if client has not requested /notifications endpoint yet with backend supporting last_active field, we assume it is not active if (!lastActiveISODate) { return false; } const passedWeeksSinceLastActive = weeksPassedSinceDate(new Date(lastActiveISODate)); return passedWeeksSinceLastActive <= 4; }; /** * Check if client is MLS-capable device. * Client is considered MLS capable if it was registered and has uploaded MLS public keys. * @param client - client to check * @returns {boolean} */ export const isClientMLSCapable = ({mls_public_keys: mlsPublicKeys}: RegisteredClient): boolean => { return Object.values(mlsPublicKeys).length > 0; }; ```
/content/code_sandbox/src/script/client/ClientUtils.ts
xml
2016-07-21T15:34:05
2024-08-16T11:40:13
wire-webapp
wireapp/wire-webapp
1,125
300
```xml import type { Meta, StoryObj } from '@storybook/react'; import { Button } from './Button'; const meta = { title: 'examples/Button with Meta Description as Parameter', component: Button, argTypes: { backgroundColor: { control: 'color' }, }, globals: { sb_theme: 'light' }, parameters: { docs: { description: { component: ` These are the stories for the Button component _this description was written as a string in \`parameters.docs.description.component\`_ `, }, }, }, } satisfies Meta<typeof Button>; export default meta; type Story = StoryObj<typeof meta>; export const WithMetaDescriptionAsParamater: Story = { args: { primary: true, label: 'Button', }, }; ```
/content/code_sandbox/code/lib/blocks/src/examples/ButtonWithMetaDescriptionAsParameter.stories.tsx
xml
2016-03-18T04:23:44
2024-08-16T19:22:08
storybook
storybookjs/storybook
83,755
168
```xml /* * Wire * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see path_to_url * */ import {Message} from './Message'; import {SuperType} from '../../message/SuperType'; export class DeleteMessage extends Message { public deleted_timestamp: null | number; constructor() { super(); this.super_type = SuperType.DELETE; this.deleted_timestamp = null; } } ```
/content/code_sandbox/src/script/entity/message/DeleteMessage.ts
xml
2016-07-21T15:34:05
2024-08-16T11:40:13
wire-webapp
wireapp/wire-webapp
1,125
150
```xml import { constants as FS, promises as fs } from 'fs' import path from 'path' import { SourceMapConsumer } from 'next/dist/compiled/source-map08' import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' import { getRawSourceMap } from '../internal/helpers/getRawSourceMap' import { launchEditor } from '../internal/helpers/launchEditor' import { badRequest, findSourcePackage, getOriginalCodeFrame, internalServerError, json, noContent, type OriginalStackFrameResponse, } from './shared' export { getServerError } from '../internal/helpers/nodeStackFrames' export { parseStack } from '../internal/helpers/parseStack' import type { IncomingMessage, ServerResponse } from 'http' import type webpack from 'webpack' type Source = { map: () => any } | null function getModuleId(compilation: any, module: any) { return compilation.chunkGraph.getModuleId(module) } function getModuleById( id: string | undefined, compilation: webpack.Compilation ) { return [...compilation.modules].find( (searchModule) => getModuleId(compilation, searchModule) === id ) } function findModuleNotFoundFromError(errorMessage: string | undefined) { return errorMessage?.match(/'([^']+)' module/)?.[1] } function getModuleSource(compilation: any, module: any): any { if (!module) return null return ( compilation.codeGenerationResults.get(module)?.sources.get('javascript') ?? null ) } function getSourcePath(source: string) { return source.replace(/^(webpack:\/\/\/|webpack:\/\/|webpack:\/\/_N_E\/)/, '') } async function findOriginalSourcePositionAndContent( webpackSource: any, position: { line: number; column: number | null } ) { const consumer = await new SourceMapConsumer(webpackSource.map()) try { const sourcePosition = consumer.originalPositionFor({ line: position.line, column: position.column ?? 0, }) if (!sourcePosition.source) { return null } const sourceContent: string | null = consumer.sourceContentFor( sourcePosition.source, /* returnNullOnMissing */ true ) ?? null return { sourcePosition, sourceContent, } } finally { consumer.destroy() } } function findOriginalSourcePositionAndContentFromCompilation( moduleId: string | undefined, importedModule: string, compilation: webpack.Compilation ) { const module = getModuleById(moduleId, compilation) return module?.buildInfo?.importLocByPath?.get(importedModule) ?? null } export async function createOriginalStackFrame({ source, moduleId, modulePath, rootDirectory, frame, errorMessage, compilation, }: { source: any moduleId?: string modulePath?: string rootDirectory: string frame: StackFrame errorMessage?: string compilation?: webpack.Compilation }): Promise<OriginalStackFrameResponse | null> { const { lineNumber, column } = frame const moduleNotFound = findModuleNotFoundFromError(errorMessage) const result = await (async () => { if (moduleNotFound) { if (!compilation) return null return findOriginalSourcePositionAndContentFromCompilation( moduleId, moduleNotFound, compilation ) } // This returns 1-based lines and 0-based columns return await findOriginalSourcePositionAndContent(source, { line: lineNumber ?? 1, column, }) })() if (!result?.sourcePosition.source) return null const { sourcePosition, sourceContent } = result const filePath = path.resolve( rootDirectory, getSourcePath( // When sourcePosition.source is the loader path the modulePath is generally better. (sourcePosition.source.includes('|') ? modulePath : sourcePosition.source) || modulePath ) ) const traced = { file: sourceContent ? path.relative(rootDirectory, filePath) : sourcePosition.source, lineNumber: sourcePosition.line, column: (sourcePosition.column ?? 0) + 1, methodName: sourcePosition.name || // default is not a valid identifier in JS so webpack uses a custom variable when it's an unnamed default export // Resolve it back to `default` for the method name if the source position didn't have the method. frame.methodName ?.replace('__WEBPACK_DEFAULT_EXPORT__', 'default') ?.replace('__webpack_exports__.', ''), arguments: [], } satisfies StackFrame return { originalStackFrame: traced, originalCodeFrame: getOriginalCodeFrame(traced, sourceContent), sourcePackage: findSourcePackage(traced), } } export async function getSourceById( isFile: boolean, id: string, compilation?: webpack.Compilation ): Promise<Source> { if (isFile) { const fileContent: string | null = await fs .readFile(id, 'utf-8') .catch(() => null) if (fileContent == null) { return null } const map = getRawSourceMap(fileContent) if (map == null) { return null } return { map() { return map }, } } try { if (!compilation) { return null } const module = getModuleById(id, compilation) const moduleSource = getModuleSource(compilation, module) return moduleSource } catch (err) { console.error(`Failed to lookup module by ID ("${id}"):`, err) return null } } export function getOverlayMiddleware(options: { rootDirectory: string stats(): webpack.Stats | null serverStats(): webpack.Stats | null edgeServerStats(): webpack.Stats | null }) { return async function ( req: IncomingMessage, res: ServerResponse, next: Function ) { const { pathname, searchParams } = new URL(`path_to_url{req.url}`) const frame = { file: searchParams.get('file') as string, methodName: searchParams.get('methodName') as string, lineNumber: parseInt(searchParams.get('lineNumber') ?? '0', 10) || 0, column: parseInt(searchParams.get('column') ?? '0', 10) || 0, arguments: searchParams.getAll('arguments').filter(Boolean), } satisfies StackFrame const isServer = searchParams.get('isServer') === 'true' const isEdgeServer = searchParams.get('isEdgeServer') === 'true' const isAppDirectory = searchParams.get('isAppDirectory') === 'true' if (pathname === '/__nextjs_original-stack-frame') { const isClient = !isServer && !isEdgeServer let sourcePackage = findSourcePackage(frame) if ( !( /^(webpack-internal:\/\/\/|(file|webpack):\/\/)/.test(frame.file) && frame.lineNumber ) ) { if (sourcePackage) return json(res, { sourcePackage }) return badRequest(res) } const moduleId: string = frame.file.replace( /^(webpack-internal:\/\/\/|file:\/\/|webpack:\/\/(_N_E\/)?)/, '' ) const modulePath = frame.file.replace( /^(webpack-internal:\/\/\/|file:\/\/|webpack:\/\/(_N_E\/)?)(\(.*\)\/?)/, '' ) let source: Source = null let compilation: webpack.Compilation | undefined const isFile = frame.file.startsWith('file:') try { if (isClient || isAppDirectory) { compilation = options.stats()?.compilation // Try Client Compilation first // In `pages` we leverage `isClientError` to check // In `app` it depends on if it's a server / client component and when the code throws. E.g. during HTML rendering it's the server/edge compilation. source = await getSourceById(isFile, moduleId, compilation) } // Try Server Compilation // In `pages` this could be something imported in getServerSideProps/getStaticProps as the code for those is tree-shaken. // In `app` this finds server components and code that was imported from a server component. It also covers when client component code throws during HTML rendering. if ((isServer || isAppDirectory) && source === null) { compilation = options.serverStats()?.compilation source = await getSourceById(isFile, moduleId, compilation) } // Try Edge Server Compilation // Both cases are the same as Server Compilation, main difference is that it covers `runtime: 'edge'` pages/app routes. if ((isEdgeServer || isAppDirectory) && source === null) { compilation = options.edgeServerStats()?.compilation source = await getSourceById(isFile, moduleId, compilation) } } catch (err) { console.log('Failed to get source map:', err) return internalServerError(res) } if (!source) { if (sourcePackage) return json(res, { sourcePackage }) return noContent(res) } try { const originalStackFrameResponse = await createOriginalStackFrame({ frame, source, moduleId, modulePath, rootDirectory: options.rootDirectory, compilation, }) if (originalStackFrameResponse === null) { if (sourcePackage) return json(res, { sourcePackage }) return noContent(res) } return json(res, originalStackFrameResponse) } catch (err) { console.log('Failed to parse source map:', err) return internalServerError(res) } } else if (pathname === '/__nextjs_launch-editor') { if (!frame.file) return badRequest(res) // frame files may start with their webpack layer, like (middleware)/middleware.js const filePath = path.resolve( options.rootDirectory, frame.file.replace(/^\([^)]+\)\//, '') ) const fileExists = await fs.access(filePath, FS.F_OK).then( () => true, () => false ) if (!fileExists) return noContent(res) try { await launchEditor(filePath, frame.lineNumber, frame.column ?? 1) } catch (err) { console.log('Failed to launch editor:', err) return internalServerError(res) } return noContent(res) } return next() } } ```
/content/code_sandbox/packages/next/src/client/components/react-dev-overlay/server/middleware.ts
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
2,289
```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" xmlns:android="path_to_url" xmlns:tools="path_to_url"> <TextView android:id="@+id/years_button" style="@style/CuViewTypeButton" android:text="@string/years_view_button" /> <TextView android:id="@+id/months_button" style="@style/CuViewTypeButton" android:text="@string/months_view_button" /> <TextView android:id="@+id/days_button" style="@style/CuViewTypeButton" android:text="@string/days_view_button" /> <TextView android:id="@+id/all_button" style="@style/CuViewTypeButton" android:text="@string/all_view_button" tools:background="@drawable/background_18dp_rounded_selected_button" tools:textAppearance="@style/TextAppearance.Mega.Subtitle2.Medium.WhiteGrey87" /> </LinearLayout> ```
/content/code_sandbox/app/src/main/res/layout/cu_view_type_layout.xml
xml
2016-05-04T11:46:20
2024-08-15T16:29:10
android
meganz/android
1,537
243
```xml <?xml version="1.0" encoding="utf-8"?> <resources xmlns:tools="path_to_url" tools:ignore="ImpliedQuantity, ExtraTranslation, MissingTranslation"> <!-- Label to show that an SDK operation has been complete successfully. --> <string name="api_ok"></string> <!-- Label to show that an Internal error occurs during a SDK operation. --> <string name="api_einternal"></string> <!-- Label to show that an error of Invalid argument occurs during a SDK operation. --> <string name="api_eargs"></string> <!-- Label to show that a request error occurs during a SDK operation. --> <string name="api_eagain"></string> <!-- Label to show that the rate limit has been reached during a SDK operation. --> <string name="api_eratelimit"></string> <!-- Label to show that a SDK operation has failed permanently. --> <string name="api_efailed"></string> <!-- Error shown when terms of service are breached during download. --> <string name="api_etoomany_ec_download"></string> <!-- Label to show that an error for multiple concurrent connections or transfers occurs during a SDK operation. --> <string name="api_etoomay"></string> <!-- Label to show that an error of Out of range occurs during a SDK operation. --> <string name="api_erange"></string> <!-- State to indicate something has expired (achivements of business status account for instance) --> <string name="api_eexpired"></string> <!-- Label to show that an error related with a resource Not found occurs during a SDK operation. --> <string name="api_enoent"></string> <!-- Label to show that an error related with a circular linkage occurs during a SDK operation. --> <string name="api_ecircular"></string> <!-- Label to show that an error related with an denied access occurs during a SDK operation. --> <string name="api_eaccess"></string> <!-- Label to show that an error related with an existent resource occurs during a SDK operation. --> <string name="api_eexist"></string> <!-- Label to show that an error related with an Incomplete SDK operation. --> <string name="api_eincomplete"></string> <!-- Label to show that an error related with the decryption process of a node occurs during a SDK operation. --> <string name="api_ekey"></string> <!-- Label to show that an error related with a bad session ID occurs during a SDK operation. --> <string name="api_esid">ID</string> <!-- Label to show that an error related with a blocked account occurs during a SDK operation. --> <string name="api_eblocked"></string> <!-- Label to show that an error related with an over quota occurs during a SDK operation. --> <string name="api_eoverquota"></string> <!-- Label to show that an error related with a temporary problem occurs during a SDK operation. --> <string name="api_etempunavail"></string> <!-- Label to show that an error related with too many connections occurs during a SDK operation. --> <string name="api_etoomanyconnections"></string> <!-- Label to show that an error related with an write error occurs during a SDK operation. --> <string name="api_ewrite"></string> <!-- Label to show that an error related with an read error occurs during a SDK operation. --> <string name="api_eread"></string> <!-- Label to show that an error related with an invalid or missing application key occurs during a SDK operation. --> <string name="api_eappkey"></string> <!-- Error shown when SSL check has failed --> <string name="api_essl">SSL</string> <!-- Label shown when current account does not have enough quota to complete the operation --> <string name="api_egoingoverquota"></string> <!-- Label to show that an error of Multi-factor authentication required occurs during a SDK operation. --> <string name="api_emfarequired"></string> <!-- Label to show that an error of Access denied for users occurs during a SDK operation. --> <string name="api_emasteronly"></string> <!-- A dialog title shown to users when their business account is expired. --> <string name="api_ebusinesspastdue"></string> <!-- Label to show that an error of Credit card rejected occurs during a SDK operation. --> <string name="payment_ecard"></string> <!-- Label to show that an error of Billing failed occurs during a SDK operation. --> <string name="payment_ebilling"></string> <!-- Label to show that an error of Rejected by fraud protection occurs during a SDK operation. --> <string name="payment_efraud"></string> <!-- Message shown when the SDK is waiting for the server to complete a request due to a rate limit (API error -4) - (String as short as possible). --> <string name="payment_etoomay"></string> <!-- Label to show that an error of Balance occurs during a SDK operation. --> <string name="payment_ebalance"></string> <!-- Label to show that an error related with an unknown error occurs during a SDK operation. --> <string name="payment_egeneric_api_error_unknown"></string> <!-- Label to show that an error related with an HTTP error occurs during a SDK operation. --> <string name="api_error_http">HTTP</string> <!-- Label to show that a transfer error happened during a SDK operation (sync a recursive folders structure). Only can happen if user syncs a folder with recursive links (link to the parent folder). --> <string name="api_ecircular_ec_upload"></string> </resources> ```
/content/code_sandbox/app/src/main/res/values-zh-rCN/strings_sdk_errors.xml
xml
2016-05-04T11:46:20
2024-08-15T16:29:10
android
meganz/android
1,537
1,216
```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="path_to_url" xmlns:tools="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.styleimageview.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="180dp"> <ImageView android:src="@drawable/test_house" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <ImageView android:id="@+id/image" android:src="@drawable/test_house" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="5dp"> <TextView android:text="Animation" android:textSize="20sp" android:textColor="@color/black" android:layout_gravity="center_vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <CheckBox android:layout_weight="1" android:id="@+id/animation_checkbox" android:checked="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="Duration" android:textSize="20sp" android:textColor="@color/black" android:layout_gravity="center_vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/duration_edittext" android:text="500" android:textColor="@color/black" android:inputType="number" android:layout_width="100dp" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp"> <TextView android:text="Brightness" android:textSize="20sp" android:textColor="@color/black" android:layout_gravity="center_vertical" android:layout_weight="2" android:layout_width="0dp" android:layout_height="wrap_content" /> <SeekBar android:id="@+id/seekbar_brightness" android:layout_gravity="center_vertical" android:max="510" android:progress="255" android:layout_weight="5" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp"> <TextView android:text="Contrast" android:textSize="20sp" android:textColor="@color/black" android:layout_gravity="center_vertical" android:layout_weight="2" android:layout_width="0dp" android:layout_height="wrap_content" /> <SeekBar android:id="@+id/seekbar_contrast" android:layout_gravity="center_vertical" android:max="200" android:progress="100" android:layout_weight="5" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout> <View android:background="@color/grey" android:layout_width="match_parent" android:layout_height="1dp"/> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> ```
/content/code_sandbox/styler_test/src/main/res/layout/activity_main.xml
xml
2016-08-17T10:49:18
2024-08-14T01:14:47
StyleImageView
chengdazhi/StyleImageView
1,450
837
```xml import * as React from 'react'; import { useId, Label, Slider, makeStyles } from '@fluentui/react-components'; const useStyles = makeStyles({ wrapper: { display: 'flex', alignItems: 'center', }, }); export const MinMax = () => { const styles = useStyles(); const id = useId(); const min = 10; const max = 50; return ( <> <Label htmlFor={id}>Min/Max Example</Label> <div className={styles.wrapper}> <Label aria-hidden>{min}</Label> <Slider min={min} max={max} defaultValue={20} id={id} /> <Label aria-hidden>{max}</Label> </div> </> ); }; MinMax.parameters = { docs: { description: { story: 'A slider with min and max values displayed', }, }, }; ```
/content/code_sandbox/packages/react-components/react-slider/stories/src/Slider/SliderMinMax.stories.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
193
```xml <!-- ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <dataset> <metadata table-name="t_order_details" data-nodes="db_${0..9}.t_order_details" /> </dataset> ```
/content/code_sandbox/test/e2e/sql/src/test/resources/cases/ddl/dataset/db/drop_table.xml
xml
2016-01-18T12:49:26
2024-08-16T15:48:11
shardingsphere
apache/shardingsphere
19,707
103
```xml <?xml version="1.0" encoding="UTF-8"?> <spocosy version="1.0" responsetime="2011-03-15 13:53:12" exec="0.171"> <!-- <query-response requestid="" service="objectquery"> <sport name="Soccer" enetSportCode="s" del="no" n="1" ut="2009-12-29 15:36:24" id="1"> </sport> </query-response> --> </spocosy> ```
/content/code_sandbox/test/manual/indent/nxml.xml
xml
2016-11-22T23:29:21
2024-08-12T19:26:13
remacs
remacs/remacs
4,582
124
```xml <clickhouse> <!-- Will be overwritten by the test --> </clickhouse> ```
/content/code_sandbox/tests/integration/test_throttling/configs/users_overrides.xml
xml
2016-06-02T08:28:18
2024-08-16T18:39:33
ClickHouse
ClickHouse/ClickHouse
36,234
18
```xml type Props = { children: string; }; export default function PostTitle({ children }: Props) { return ( <h1 className="text-6xl md:text-7xl lg:text-8xl font-bold tracking-tighter leading-tight md:leading-none mb-12 text-center md:text-left" dangerouslySetInnerHTML={{ __html: children }} /> ); } ```
/content/code_sandbox/examples/cms-enterspeed/components/post-title.tsx
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
83
```xml import RedisClient, { Pipeline, Redis } from "ioredis"; import { Config } from "coral-server/config"; import { WrappedInternalError } from "coral-server/errors"; import logger from "coral-server/logger"; interface AugmentedRedisCommands { mhincrby(key: string, ...args: any[]): Promise<void>; } export interface AugmentedPipeline extends Pipeline { mhincrby(key: string, ...args: any[]): Pipeline; } export type AugmentedRedis = Omit<Redis, "pipeline"> & AugmentedRedisCommands & { pipeline(commands?: string[][]): AugmentedPipeline; }; function augmentRedisClient(redis: Redis): AugmentedRedis { // mhincrby will increment many hash values. redis.defineCommand("mhincrby", { numberOfKeys: 1, lua: ` for i = 1, #ARGV, 2 do redis.call('HINCRBY', KEYS[1], ARGV[i], ARGV[i + 1]) end `, }); return redis as AugmentedRedis; } function attachHandlers(redis: Redis) { // There appears to already be 10 error listeners on Redis. They must be added // by the framework. Increase the maximum number of listeners to avoid the // memory leak warning. redis.setMaxListeners(11); redis.on("error", (err: Error) => { logger.error({ err }, "an error occurred with redis"); }); redis.on("close", () => { logger.warn("redis connection has been closed"); }); redis.on("reconnecting", () => { logger.warn("redis has reconnected"); }); } export function createRedisClient(config: Config, lazyConnect = false): Redis { try { const options = config.get("redis_options") || {}; const redis = new RedisClient(config.get("redis"), { // Merge in the custom options. ...options, // Enforce the lazyConnect option as provided by the function invocation. lazyConnect, }); // Configure the redis client with the handlers for logging attachHandlers(redis); return redis; } catch (err) { throw new WrappedInternalError(err as Error, "could not connect to redis"); } } export function createRedisClientFactory(config: Config) { let redis: Redis | undefined; return (): Redis => { if (!redis) { redis = createRedisClient(config); } return redis; }; } /** * createAugmentedRedisClient will connect to the Redis instance identified in * the configuration. * @param config application configuration. */ export async function createAugmentedRedisClient( config: Config ): Promise<AugmentedRedis> { try { const redis = augmentRedisClient(createRedisClient(config, true)); // Connect the redis client. await redis.connect(); return redis; } catch (err) { throw new WrappedInternalError(err as Error, "could not connect to redis"); } } ```
/content/code_sandbox/server/src/core/server/services/redis/index.ts
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
640
```xml import { defaultNativeWebControlElements, QueryBuilderNative, } from '@react-querybuilder/native'; import { useState } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import type { Field, RuleGroupType } from 'react-querybuilder'; import { formatQuery } from 'react-querybuilder'; const fields: Field[] = [ { name: 'firstName', label: 'First Name' }, { name: 'lastName', label: 'Last Name' }, ]; const defaultQuery: RuleGroupType = { combinator: 'and', rules: [ { field: 'firstName', operator: 'beginsWith', value: 'Stev' }, { field: 'lastName', operator: 'in', value: 'Vai, Vaughan' }, ], }; export const App = () => { const [query, setQuery] = useState(defaultQuery); return ( <View style={styles.outer}> <Text style={styles.outer}>React Query Builder React Native Example</Text> <QueryBuilderNative fields={fields} query={query} onQueryChange={setQuery} controlElements={defaultNativeWebControlElements} /> <Text style={styles.code}>{formatQuery(query, 'sql')}</Text> </View> ); }; const styles = StyleSheet.create({ outer: { padding: 10, gap: 20 }, code: { fontFamily: 'monospace' }, }); ```
/content/code_sandbox/examples/native/src/App.tsx
xml
2016-06-17T22:03:19
2024-08-16T10:28:42
react-querybuilder
react-querybuilder/react-querybuilder
1,131
309
```xml import { describe, expect, it } from 'vitest'; import { client } from '../../../mocks/client'; import getProjectByDeployment from '../../../../src/util/projects/get-project-by-deployment'; import { useTeams } from '../../../mocks/team'; import { useUser } from '../../../mocks/user'; import { useDeployment } from '../../../mocks/deployment'; import { defaultProject, useProject } from '../../../mocks/project'; describe('getProjectByDeployment', () => { it('should get project and deployment', async () => { const user = useUser(); const { project: p } = useProject({ ...defaultProject, id: 'foo', name: 'foo', }); const d = useDeployment({ creator: user, createdAt: Date.now(), project: p, }); const { deployment, project } = await getProjectByDeployment({ client, deployId: d.id, output: client.output, }); expect(project.id).toBe(p.id); expect(deployment.id).toBe(d.id); }); it('should get project and deployment associated to a team', async () => { const [team] = useTeams('team_dummy'); const user = useUser(); const { project: p } = useProject({ ...defaultProject, id: 'foo', name: 'foo', }); const d = useDeployment({ creator: { id: team.id, name: team.name, email: user.email, username: team.slug, }, createdAt: Date.now(), project: p, }); client.config.currentTeam = team.id; d.team = team; const { deployment, project } = await getProjectByDeployment({ client, deployId: d.id, output: client.output, }); expect(project.id).toBe(p.id); expect(deployment.id).toBe(d.id); }); it("should error if deployment team doesn't match current user's team", async () => { const [team] = useTeams('team_dummy'); const user = useUser(); const { project: p } = useProject({ ...defaultProject, id: 'foo', name: 'foo', }); const d = useDeployment({ creator: { id: team.id, name: team.name, email: user.email, username: team.slug, }, createdAt: Date.now(), project: p, }); client.config.currentTeam = team.id; await expect( getProjectByDeployment({ client, deployId: d.id, output: client.output, }) ).rejects.toThrowError("Deployment doesn't belong to current team"); client.config.currentTeam = undefined; d.team = team; await expect( getProjectByDeployment({ client, deployId: d.id, output: client.output, }) ).rejects.toThrowError('Deployment belongs to a different team'); }); }); ```
/content/code_sandbox/packages/cli/test/unit/util/projects/get-project-by-deployment.test.ts
xml
2016-09-09T01:12:08
2024-08-16T17:39:45
vercel
vercel/vercel
12,545
642
```xml // auto generated file, do not edit export type SupportedFrameworks = | 'angular' | 'ember' | 'experimental-nextjs-vite' | 'html-vite' | 'html-webpack5' | 'nextjs' | 'preact-vite' | 'preact-webpack5' | 'react-vite' | 'react-webpack5' | 'server-webpack5' | 'svelte-vite' | 'svelte-webpack5' | 'sveltekit' | 'vue3-vite' | 'vue3-webpack5' | 'web-components-vite' | 'web-components-webpack5' | 'qwik' | 'solid' | 'react-rsbuild' | 'vue3-rsbuild'; ```
/content/code_sandbox/code/core/src/types/modules/frameworks.ts
xml
2016-03-18T04:23:44
2024-08-16T19:22:08
storybook
storybookjs/storybook
83,755
174
```xml <!-- ~ ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ --> <window xmlns="path_to_url" messagesPack="com.haulmont.cuba.gui.app.security.role.edit" class="com.haulmont.cuba.gui.app.security.role.edit.tabs.ScreenPermissionsFrame"> <companions> <web class="com.haulmont.cuba.web.app.ui.security.role.ScreenPermissionsFrameCompanion"/> <desktop class="com.haulmont.cuba.desktop.app.security.role.ScreenPermissionsFrameCompanion"/> </companions> <dsContext> <collectionDatasource id="screenPermissionsDs" class="com.haulmont.cuba.security.entity.Permission" view="role.edit" datasourceClass="com.haulmont.cuba.gui.app.security.ds.PermissionsCollectionDatasource"> <query>select p from sec$Permission p where p.role.id = :ds$roleDs.id and p.type = 10</query> </collectionDatasource> <collectionDatasource id="screenPermissionsTreeDs" class="com.haulmont.cuba.gui.app.security.entity.BasicPermissionTarget" allowCommit="false" view="_local" datasourceClass="com.haulmont.cuba.gui.app.security.ds.ScreenPermissionTreeDatasource"> </collectionDatasource> </dsContext> <layout margin="true"> <split width="100%" height="100%" pos="80" orientation="horizontal"> <vbox expand="screenPermissionsTree" height="100%" margin="false;true;false;false"> <hbox margin="false;false,true;false" width="100%" spacing="true" expand="spring"> <label align="MIDDLE_LEFT" value="msg://screenFilter"/> <textField id="screenFilter" width="theme://cuba.gui.screens-permission-tab.screenFilter.width" align="MIDDLE_LEFT"/> <button caption="msg://actions.Apply" align="MIDDLE_LEFT" invoke="applyFilter"/> <label id="spring"/> <checkBox id="screenWildcardCheckBox" caption="msg://allowAllScreens" align="MIDDLE_RIGHT"/> </hbox> <treeTable id="screenPermissionsTree" width="100%" multiselect="true"> <columns> <column id="caption" caption="msg://target"/> <column id="permissionVariant" caption="msg://value"/> </columns> <rows datasource="screenPermissionsTreeDs"/> </treeTable> </vbox> <vbox margin="false;false;false;true" height="100%"> <groupBox id="screensEditPane" height="100%" caption="msg://permissions"> <vbox id="selectedScreenPanel" width="100%" visible="false" spacing="true"> <label property="caption" datasource="screenPermissionsTreeDs" stylename="h2" align="MIDDLE_CENTER"/> <checkBox id="allowCheckBox" caption="msg://checkbox.allow"/> <checkBox id="disallowCheckBox" caption="msg://checkbox.deny"/> </vbox> </groupBox> </vbox> </split> </layout> </window> ```
/content/code_sandbox/modules/gui/src/com/haulmont/cuba/gui/app/security/role/edit/tabs/screens-permission-tab.xml
xml
2016-03-24T07:55:56
2024-07-14T05:13:48
cuba
cuba-platform/cuba
1,342
715
```xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="path_to_url"> <TextView android:id="@+id/messageView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/bottomBar" android:gravity="center" android:text="Hi mom!" /> <com.roughike.bottombar.BottomBar android:id="@+id/bottomBar" android:layout_width="match_parent" android:layout_height="60dp" android:layout_alignParentBottom="true" app:bb_tabXmlResource="@xml/bottombar_tabs_three" /> </RelativeLayout> ```
/content/code_sandbox/app/src/main/res/layout/activity_three_tabs.xml
xml
2016-03-16T01:31:05
2024-08-16T16:21:09
BottomBar
roughike/BottomBar
8,424
178
```xml <?xml version="1.0" encoding="utf-8"?> <WixLocalization Culture="pl-pl" xmlns="path_to_url"> <String Id="Locale" Overridable="yes">pl</String> <String Id="ProductName" Overridable="yes">Aspia Client</String> <String Id="ShortcutName" Overridable="yes">Aspia Client</String> <String Id="DowngradeErrorMessage" Overridable="yes">A newer version of the application is already installed.</String> <String Id="CreateDesktopShortcut" Overridable="yes">Create desktop shortcut</String> <String Id="CreateProgramMenuShortcut" Overridable="yes">Create shortcut in the Start menu</String> </WixLocalization> ```
/content/code_sandbox/installer/translations/client.pl-pl.wxl
xml
2016-10-26T16:17:31
2024-08-16T13:37:42
aspia
dchapyshev/aspia
1,579
165
```xml 'use strict'; import * as chai from 'chai'; import { Boot, Kernel } from '../lib/kernel/kernel'; const expect = chai.expect; const MINS = 60 * 1000; // milliseconds const IS_KARMA = typeof window !== 'undefined' && typeof (<any>window).__karma__ !== 'undefined'; const ROOT = IS_KARMA ? '/base/fs/' : '/fs/'; export const name = 'test-grep'; describe('grep /a /b', function(): void { this.timeout(10 * MINS); const A_CONTENTS = 'the horse raced\npast the barn fell.'; const B_CONTENTS = 'the past plate\npassed last.'; let kernel: Kernel = null; it('should boot', function(done: MochaDone): void { Boot('XmlHttpRequest', ['index.json', ROOT, true], function(err: any, freshKernel: Kernel): void { expect(err).to.be.null; expect(freshKernel).not.to.be.null; kernel = freshKernel; done(); }); }); it('should create /a', function(done: MochaDone): void { kernel.fs.writeFile('/a', A_CONTENTS, function(err: any): void { expect(err).to.be.undefined; done(); }); }); it('should create /b', function(done: MochaDone): void { kernel.fs.writeFile('/b', B_CONTENTS, function(err: any): void { expect(err).to.be.undefined; done(); }); }); it('should run `grep past /a /b`', function(done: MochaDone): void { let stdout: string = ''; let stderr: string = ''; kernel.system('/usr/bin/grep past /a /b', onExit, onStdout, onStderr); function onStdout(pid: number, out: string): void { stdout += out; } function onStderr(pid: number, out: string): void { stderr += out; } function onExit(pid: number, code: number): void { try { expect(code).to.equal(0); expect(stdout).to.equal('past the barn fell.\nthe past plate.'); expect(stderr).to.equal(""); done(); } catch (e) { done(e); } } }); }); ```
/content/code_sandbox/test/test-grep.ts
xml
2016-02-17T16:29:16
2024-08-12T22:21:27
browsix
plasma-umass/browsix
3,147
510
```xml /** * With this module is possible to manage components inside the canvas. You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](path_to_url * ```js * const editor = grapesjs.init({ * domComponents: { * // options * } * }) * ``` * * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. * * ```js * // Listen to events * editor.on('component:create', () => { ... }); * * // Use the API * const cmp = editor.Components; * cmp.addType(...); * ``` * * ## Available Events * * `component:create` - Component is created (only the model, is not yet mounted in the canvas), called after the init() method * * `component:mount` - Component is mounted to an element and rendered in canvas * * `component:add` - Triggered when a new component is added to the editor, the model is passed as an argument to the callback * * `component:remove` - Triggered when a component is removed, the model is passed as an argument to the callback * * `component:remove:before` - Triggered before the remove of the component, the model, remove function (if aborted via options, with this function you can complete the remove) and options (use options.abort = true to prevent remove), are passed as arguments to the callback * * `component:clone` - Triggered when a component is cloned, the new model is passed as an argument to the callback * * `component:update` - Triggered when a component is updated (moved, styled, etc.), the model is passed as an argument to the callback * * `component:update:{propertyName}` - Listen any property change, the model is passed as an argument to the callback * * `component:styleUpdate` - Triggered when the style of the component is updated, the model is passed as an argument to the callback * * `component:styleUpdate:{propertyName}` - Listen for a specific style property change, the model is passed as an argument to the callback * * `component:selected` - New component selected, the selected model is passed as an argument to the callback * * `component:deselected` - Component deselected, the deselected model is passed as an argument to the callback * * `component:toggled` - Component selection changed, toggled model is passed as an argument to the callback * * `component:type:add` - New component type added, the new type is passed as an argument to the callback * * `component:type:update` - Component type updated, the updated type is passed as an argument to the callback * * `component:drag:start` - Component drag started. Passed an object, to the callback, containing the `target` (component to drag), `parent` (parent of the component) and `index` (component index in the parent) * * `component:drag` - During component drag. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the current pointer * * `component:drag:end` - Component drag ended. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the final pointer * * `component:resize` - During component resize. * * ## Methods * * [getWrapper](#getwrapper) * * [getComponents](#getcomponents) * * [addComponent](#addcomponent) * * [clear](#clear) * * [addType](#addtype) * * [getType](#gettype) * * [getTypes](#gettypes) * * * [Component]: component.html * * @module Components */ import { debounce, isArray, isBoolean, isEmpty, isFunction, isString, isSymbol, result } from 'underscore'; import { ItemManagerModule } from '../abstract/Module'; import { AddOptions, ObjectAny } from '../common'; import EditorModel from '../editor/model/Editor'; import { isComponent } from '../utils/mixins'; import defaults, { DomComponentsConfig } from './config/config'; import Component, { IComponent, keyUpdate, keyUpdateInside } from './model/Component'; import ComponentComment from './model/ComponentComment'; import ComponentFrame from './model/ComponentFrame'; import ComponentImage from './model/ComponentImage'; import ComponentLabel from './model/ComponentLabel'; import ComponentLink from './model/ComponentLink'; import ComponentMap from './model/ComponentMap'; import ComponentScript from './model/ComponentScript'; import ComponentSvg from './model/ComponentSvg'; import ComponentSvgIn from './model/ComponentSvgIn'; import ComponentTable from './model/ComponentTable'; import ComponentTableBody from './model/ComponentTableBody'; import ComponentTableCell from './model/ComponentTableCell'; import ComponentTableFoot from './model/ComponentTableFoot'; import ComponentTableHead from './model/ComponentTableHead'; import ComponentTableRow from './model/ComponentTableRow'; import ComponentText from './model/ComponentText'; import ComponentTextNode from './model/ComponentTextNode'; import ComponentVideo from './model/ComponentVideo'; import ComponentWrapper from './model/ComponentWrapper'; import Components from './model/Components'; import { ComponentAdd, ComponentDefinition, ComponentDefinitionDefined, ComponentStackItem } from './model/types'; import ComponentCommentView from './view/ComponentCommentView'; import ComponentFrameView from './view/ComponentFrameView'; import ComponentImageView from './view/ComponentImageView'; import ComponentLabelView from './view/ComponentLabelView'; import ComponentLinkView from './view/ComponentLinkView'; import ComponentMapView from './view/ComponentMapView'; import ComponentScriptView from './view/ComponentScriptView'; import ComponentSvgView from './view/ComponentSvgView'; import ComponentTableBodyView from './view/ComponentTableBodyView'; import ComponentTableCellView from './view/ComponentTableCellView'; import ComponentTableFootView from './view/ComponentTableFootView'; import ComponentTableHeadView from './view/ComponentTableHeadView'; import ComponentTableRowView from './view/ComponentTableRowView'; import ComponentTableView from './view/ComponentTableView'; import ComponentTextNodeView from './view/ComponentTextNodeView'; import ComponentTextView from './view/ComponentTextView'; import ComponentVideoView from './view/ComponentVideoView'; import ComponentView, { IComponentView } from './view/ComponentView'; import ComponentWrapperView from './view/ComponentWrapperView'; import ComponentsView from './view/ComponentsView'; import ComponentHead, { type as typeHead } from './model/ComponentHead'; import { getSymbolMain, getSymbolInstances, getSymbolsToUpdate, isSymbolMain, isSymbolInstance, detachSymbolInstance, isSymbolRoot, } from './model/SymbolUtils'; import { ComponentsEvents, SymbolInfo } from './types'; import Symbols from './model/Symbols'; import { BlockProperties } from '../block_manager/model/Block'; export type ComponentEvent = | 'component:create' | 'component:mount' | 'component:add' | 'component:remove' | 'component:remove:before' | 'component:clone' | 'component:update' | 'component:styleUpdate' | 'component:selected' | 'component:deselected' | 'component:toggled' | 'component:type:add' | 'component:type:update' | 'component:drag:start' | 'component:drag' | 'component:drag:end' | 'component:resize'; export interface ComponentModelDefinition extends IComponent { defaults?: ComponentDefinition | (() => ComponentDefinition); [key: string]: any; } export interface ComponentViewDefinition extends IComponentView { [key: string]: any; } export interface AddComponentTypeOptions { isComponent?: (el: HTMLElement) => boolean | ComponentDefinitionDefined | undefined; model?: Partial<ComponentModelDefinition> & ThisType<ComponentModelDefinition & Component>; view?: Partial<ComponentViewDefinition> & ThisType<ComponentViewDefinition & ComponentView>; block?: boolean | Partial<BlockProperties>; extend?: string; extendView?: string; extendFn?: string[]; extendFnView?: string[]; } /** @private */ export enum CanMoveReason { /** * Invalid source. This is a default value and should be ignored in case the `result` is true */ InvalidSource = 0, /** * Source doesn't accept target as destination. */ SourceReject = 1, /** * Target doesn't accept source. */ TargetReject = 2, } export interface CanMoveResult { result: boolean; reason: CanMoveReason; target: Component; source?: Component | null; } export default class ComponentManager extends ItemManagerModule<DomComponentsConfig, any> { componentTypes: ComponentStackItem[] = [ { id: 'cell', model: ComponentTableCell, view: ComponentTableCellView, }, { id: 'row', model: ComponentTableRow, view: ComponentTableRowView, }, { id: 'table', model: ComponentTable, view: ComponentTableView, }, { id: 'thead', model: ComponentTableHead, view: ComponentTableHeadView, }, { id: 'tbody', model: ComponentTableBody, view: ComponentTableBodyView, }, { id: 'tfoot', model: ComponentTableFoot, view: ComponentTableFootView, }, { id: 'map', model: ComponentMap, view: ComponentMapView, }, { id: 'link', model: ComponentLink, view: ComponentLinkView, }, { id: 'label', model: ComponentLabel, view: ComponentLabelView, }, { id: 'video', model: ComponentVideo, view: ComponentVideoView, }, { id: 'image', model: ComponentImage, view: ComponentImageView, }, { id: 'script', model: ComponentScript, view: ComponentScriptView, }, { id: 'svg-in', model: ComponentSvgIn, view: ComponentSvgView, }, { id: 'svg', model: ComponentSvg, view: ComponentSvgView, }, { id: 'iframe', model: ComponentFrame, view: ComponentFrameView, }, { id: 'comment', model: ComponentComment, view: ComponentCommentView, }, { id: 'textnode', model: ComponentTextNode, view: ComponentTextNodeView, }, { id: typeHead, model: ComponentHead, view: ComponentView, }, { id: 'wrapper', model: ComponentWrapper, view: ComponentWrapperView, }, { id: 'text', model: ComponentText, view: ComponentTextView, }, { id: 'default', model: Component, view: ComponentView, }, ]; componentsById: { [id: string]: Component } = {}; componentView?: ComponentWrapperView; Component = Component; Components = Components; ComponentView = ComponentView; ComponentsView = ComponentsView; /** * Name of the module * @type {String} * @private */ //name = "DomComponents"; storageKey = 'components'; keySymbols = 'symbols'; shallow?: Component; symbols: Symbols; events = ComponentsEvents; /** * Initialize module. Called on a new instance of the editor with configurations passed * inside 'domComponents' field * @param {Object} config Configurations * @private */ constructor(em: EditorModel) { super(em, 'DomComponents', new Components(undefined, { em })); const { config } = this; this.symbols = new Symbols([], { em, config, domc: this }); if (em) { //@ts-ignore this.config.components = em.config.components || this.config.components; } for (let name in defaults) { //@ts-ignore if (!(name in this.config)) this.config[name] = defaults[name]; } const ppfx = this.config.pStylePrefix; if (ppfx) this.config.stylePrefix = ppfx + this.config.stylePrefix; // Load dependencies if (em) { em.get('Parser').compTypes = this.componentTypes; em.on('change:componentHovered', this.componentHovered, this); const selected = em.get('selected'); em.listenTo(selected, 'add', (sel, c, opts) => this.selectAdd(selected.getComponent(sel), opts)); em.listenTo(selected, 'remove', (sel, c, opts) => this.selectRemove(selected.getComponent(sel), opts)); } return this; } postLoad() { const { em, symbols } = this; const { UndoManager } = em; UndoManager.add(symbols); } load(data: any) { const result = this.loadProjectData(data, { onResult: (result: Component) => { let wrapper = this.getWrapper()!; if (!wrapper) { this.em.Pages.add({}, { select: true }); wrapper = this.getWrapper()!; } if (isArray(result)) { result.length && wrapper.components(result); } else { const { components = [], ...rest } = result; wrapper.set(rest); //@ts-ignore wrapper.components(components); } }, }); this.symbols.reset(data[this.keySymbols] || []); return result; } store() { return { [this.keySymbols]: this.symbols, }; } /** * Returns the main wrapper. * @return {Object} * @private */ getComponent() { const sel = this.em.Pages.getSelected(); const frame = sel?.getMainFrame(); return frame?.getComponent(); } /** * Returns root component inside the canvas. Something like `<body>` inside HTML page * The wrapper doesn't differ from the original Component Model * @return {[Component]} Root Component * @example * // Change background of the wrapper and set some attribute * var wrapper = cmp.getWrapper(); * wrapper.set('style', {'background-color': 'red'}); * wrapper.set('attributes', {'title': 'Hello!'}); */ getWrapper() { return this.getComponent(); } /** * Returns wrapper's children collection. Once you have the collection you can * add other Components(Models) inside. Each component can have several nested * components inside and you can nest them as more as you wish. * @return {Components} Collection of components * @example * // Let's add some component * var wrapperChildren = cmp.getComponents(); * var comp1 = wrapperChildren.add({ * style: { 'background-color': 'red'} * }); * var comp2 = wrapperChildren.add({ * tagName: 'span', * attributes: { title: 'Hello!'} * }); * // Now let's add an other one inside first component * // First we have to get the collection inside. Each * // component has 'components' property * var comp1Children = comp1.get('components'); * // Procede as before. You could also add multiple objects * comp1Children.add([ * { style: { 'background-color': 'blue'}}, * { style: { height: '100px', width: '100px'}} * ]); * // Remove comp2 * wrapperChildren.remove(comp2); */ getComponents(): Components { const wrp = this.getWrapper(); return wrp?.components()!; } /** * Add new components to the wrapper's children. It's the same * as 'cmp.getComponents().add(...)' * @param {Object|[Component]|Array<Object>} component Component/s to add * @param {string} [component.tagName='div'] Tag name * @param {string} [component.type=''] Type of the component. Available: ''(default), 'text', 'image' * @param {boolean} [component.removable=true] If component is removable * @param {boolean} [component.draggable=true] If is possible to move the component around the structure * @param {boolean} [component.droppable=true] If is possible to drop inside other components * @param {boolean} [component.badgable=true] If the badge is visible when the component is selected * @param {boolean} [component.stylable=true] If is possible to style component * @param {boolean} [component.copyable=true] If is possible to copy&paste the component * @param {string} [component.content=''] String inside component * @param {Object} [component.style={}] Style object * @param {Object} [component.attributes={}] Attribute object * @param {Object} opt the options object to be used by the [Components.add]{@link getComponents} method * @return {[Component]|Array<[Component]>} Component/s added * @example * // Example of a new component with some extra property * var comp1 = cmp.addComponent({ * tagName: 'div', * removable: true, // Can't remove it * draggable: true, // Can't move it * copyable: true, // Disable copy/past * content: 'Content text', // Text inside component * style: { color: 'red'}, * attributes: { title: 'here' } * }); */ addComponent(component: ComponentAdd, opt: AddOptions = {}): Component | Component[] { return this.getComponents().add(component, opt); } /** * Render and returns wrapper element with all components inside. * Once the wrapper is rendered, and it's what happens when you init the editor, * the all new components will be added automatically and property changes are all * updated immediately * @return {HTMLElement} * @private */ render() { return this.componentView?.render().el; } /** * Remove all components * @return {this} */ clear(opts = {}) { const components = this.getComponents(); //@ts-ignore components?.filter(Boolean).forEach((i) => i.remove(opts)); return this; } /** * Set components * @param {Object|string} components HTML string or components model * @param {Object} opt the options object to be used by the {@link addComponent} method * @return {this} * @private */ setComponents(components: ComponentAdd, opt: AddOptions = {}) { this.clear(opt).addComponent(components, opt); } /** * Add new component type. * Read more about this in [Define New Component](path_to_url#define-new-component) * @param {string} type Component ID * @param {Object} methods Component methods * @return {this} */ addType(type: string, methods: AddComponentTypeOptions) { const { em } = this; const { model = {}, view = {}, isComponent, extend, extendView, extendFn = [], extendFnView = [], block } = methods; const compType = this.getType(type); const extendType = this.getType(extend!); const extendViewType = this.getType(extendView!); const typeToExtend = extendType ? extendType : compType ? compType : this.getType('default'); const modelToExt = typeToExtend.model as typeof Component; const viewToExt = extendViewType ? extendViewType.view : typeToExtend.view; // Function for extending source object methods const getExtendedObj = (fns: any[], target: any, srcToExt: any) => fns.reduce((res, next) => { const fn = target[next]; const parentFn = srcToExt.prototype[next]; if (fn && parentFn) { res[next] = function (...args: any[]) { parentFn.bind(this)(...args); fn.bind(this)(...args); }; } return res; }, {}); // If the model/view is a simple object I need to extend it if (typeof model === 'object') { const modelDefaults = { defaults: model.defaults }; delete model.defaults; const typeExtends = new Set(modelToExt.typeExtends); typeExtends.add(modelToExt.getDefaults().type); methods.model = modelToExt.extend( { ...model, ...getExtendedObj(extendFn, model, modelToExt), }, { typeExtends, isComponent: compType && !extendType && !isComponent ? modelToExt.isComponent : isComponent || (() => 0), }, ); // Reassign the defaults getter to the model Object.defineProperty(methods.model!.prototype, 'defaults', { get: () => ({ ...(result(modelToExt.prototype, 'defaults') || {}), ...(result(modelDefaults, 'defaults') || {}), }), }); } if (typeof view === 'object') { methods.view = viewToExt.extend({ ...view, ...getExtendedObj(extendFnView, view, viewToExt), }); } if (compType) { compType.model = methods.model; compType.view = methods.view; } else { // @ts-ignore methods.id = type; this.componentTypes.unshift(methods as any); } if (block) { const defBlockProps: BlockProperties = { id: type, label: type, content: { type }, }; const blockProps: BlockProperties = block === true ? defBlockProps : { ...defBlockProps, ...block }; em.Blocks.add(blockProps.id || type, blockProps); } const event = `component:type:${compType ? 'update' : 'add'}`; em?.trigger(event, compType || methods); return this; } /** * Get component type. * Read more about this in [Define New Component](path_to_url#define-new-component) * @param {string} type Component ID * @return {Object} Component type definition, eg. `{ model: ..., view: ... }` */ getType(type: 'default'): { id: string; model: any; view: any }; getType(type: string): { id: string; model: any; view: any } | undefined; getType(type: string) { var df = this.componentTypes; for (var it = 0; it < df.length; it++) { var dfId = df[it].id; if (dfId == type) { return df[it]; } } return; } /** * Remove component type * @param {string} type Component ID * @returns {Object|undefined} Removed component type, undefined otherwise */ removeType(id: string) { const df = this.componentTypes; const type = this.getType(id); if (!type) return; const index = df.indexOf(type); df.splice(index, 1); return type; } /** * Return the array of all types * @return {Array} */ getTypes() { return this.componentTypes; } selectAdd(component: Component, opts = {}) { if (component) { component.set({ status: 'selected', }); ['component:selected', 'component:toggled'].forEach((event) => this.em.trigger(event, component, opts)); } } selectRemove(component: Component, opts = {}) { if (component) { const { em } = this; component.set({ status: '', state: '', }); ['component:deselected', 'component:toggled'].forEach((event) => this.em.trigger(event, component, opts)); } } /** * Triggered when the component is hovered * @private */ componentHovered() { const { em } = this; const model = em.get('componentHovered'); const previous = em.previous('componentHovered'); const state = 'hovered'; // Deselect the previous component previous && previous.get('status') == state && previous.set({ status: '', state: '', }); model && isEmpty(model.get('status')) && model.set('status', state); } getShallowWrapper() { let { shallow, em } = this; if (!shallow && em) { const shallowEm = em.shallow; if (!shallowEm) return; const domc = shallowEm.Components; domc.componentTypes = this.componentTypes; shallow = domc.getWrapper(); if (shallow) { const events = [keyUpdate, keyUpdateInside].join(' '); shallow.on( events, debounce(() => shallow?.components(''), 100), ); } this.shallow = shallow; } return shallow; } /** * Check if the object is a [Component]. * @param {Object} obj * @returns {Boolean} * @example * cmp.isComponent(editor.getSelected()); // true * cmp.isComponent({}); // false */ isComponent(obj?: ObjectAny): obj is Component { return isComponent(obj); } /** * Add a new symbol from a component. * If the passed component is not a symbol, it will be converted to an instance and will return the main symbol. * If the passed component is already an instance, a new instance will be created and returned. * If the passed component is the main symbol, a new instance will be created and returned. * @param {[Component]} component Component from which create a symbol. * @returns {[Component]} * @example * const symbol = cmp.addSymbol(editor.getSelected()); * // cmp.getSymbolInfo(symbol).isSymbol === true; */ addSymbol(component: Component) { if (isSymbol(component) && !isSymbolRoot(component)) { return; } const symbol = component.clone({ symbol: true }); isSymbolMain(symbol) && this.symbols.add(symbol); this.em.trigger('component:toggled'); return symbol; } /** * Get the array of main symbols. * @returns {Array<[Component]>} * @example * const symbols = cmp.getSymbols(); * // [Component, Component, ...] * // Removing the main symbol will detach all the relative instances. * symbols[0].remove(); */ getSymbols() { return [...this.symbols.models]; } /** * Detach symbol instance from the main one. * The passed symbol instance will become a regular component. * @param {[Component]} component The component symbol to detach. * @example * const cmpInstance = editor.getSelected(); * // cmp.getSymbolInfo(cmpInstance).isInstance === true; * cmp.detachSymbol(cmpInstance); * // cmp.getSymbolInfo(cmpInstance).isInstance === false; */ detachSymbol(component: Component) { if (isSymbolInstance(component)) { detachSymbolInstance(component); } } /** * Get info about the symbol. * @param {[Component]} component Component symbol from which to get the info. * @returns {Object} Object containing symbol info. * @example * cmp.getSymbolInfo(editor.getSelected()); * // > { isSymbol: true, isMain: false, isInstance: true, ... } */ getSymbolInfo(component: Component, opts: { withChanges?: string } = {}): SymbolInfo { const isMain = isSymbolMain(component); const mainRef = getSymbolMain(component); const isInstance = !!mainRef; const instances = (isMain ? getSymbolInstances(component) : getSymbolInstances(mainRef)) || []; const main = mainRef || (isMain ? component : undefined); const relatives = getSymbolsToUpdate(component, { changed: opts.withChanges }); const isSymbol = isMain || isInstance; const isRoot = isSymbol && isSymbolRoot(component); return { isSymbol, isMain, isInstance, isRoot, main, instances: instances, relatives: relatives || [], }; } /** * Check if a component can be moved inside another one. * @param {[Component]} target The target component is the one that is supposed to receive the source one. * @param {[Component]|String} source The source can be another component, a component definition or an HTML string. * @param {Number} [index] Index position, if not specified, the check will be performed against appending the source to the target. * @returns {Object} Object containing the `result` (Boolean), `source`, `target` (as Components), and a `reason` (Number) with these meanings: * * `0` - Invalid source. This is a default value and should be ignored in case the `result` is true. * * `1` - Source doesn't accept target as destination. * * `2` - Target doesn't accept source. * @example * const rootComponent = editor.getWrapper(); * const someComponent = editor.getSelected(); * * // Check with two components * editor.Components.canMove(rootComponent, someComponent); * * // Check with component definition * editor.Components.canMove(rootComponent, { tagName: 'a', draggable: false }); * * // Check with HTML string * editor.Components.canMove(rootComponent, '<form>...</form>'); */ canMove(target: Component, source?: Component | ComponentDefinition | string, index?: number): CanMoveResult { const result: CanMoveResult = { result: false, reason: CanMoveReason.InvalidSource, target, source: null, }; if (!source || !target) return result; let srcModel = isComponent(source) ? source : null; if (!srcModel) { const wrapper = this.getShallowWrapper(); srcModel = wrapper?.append(source)[0] || null; } result.source = srcModel; if (!srcModel) return result; // Check if the source is draggable in the target let draggable = srcModel.get('draggable'); if (isFunction(draggable)) { draggable = !!draggable(srcModel, target, index); } else { const el = target.getEl(); draggable = isArray(draggable) ? draggable.join(',') : draggable; draggable = isString(draggable) ? el?.matches(draggable) : draggable; } if (!draggable) return { ...result, reason: CanMoveReason.SourceReject }; // Check if the target accepts the source let droppable = target.get('droppable'); if (isFunction(droppable)) { droppable = !!droppable(srcModel, target, index); } else { if (droppable === false && target.isInstanceOf('text') && srcModel.get('textable')) { droppable = true; } else { const el = srcModel.getEl(); droppable = isArray(droppable) ? droppable.join(',') : droppable; droppable = isString(droppable) ? el?.matches(droppable) : droppable; } } // Ensure the target is not inside the source const isTargetInside = [target].concat(target.parents()).indexOf(srcModel) > -1; if (!droppable || isTargetInside) return { ...result, reason: CanMoveReason.TargetReject }; return { ...result, result: true }; } allById() { return this.componentsById; } getById(id: string) { return this.componentsById[id] || null; } destroy() { const all = this.allById(); Object.keys(all).forEach((id) => all[id] && all[id].remove()); this.componentView?.remove(); [this.em, this.componentsById, this.componentView].forEach((i) => (i = {})); } } ```
/content/code_sandbox/src/dom_components/index.ts
xml
2016-01-22T00:23:19
2024-08-16T11:20:59
grapesjs
GrapesJS/grapesjs
21,687
7,081
```xml import { IContext } from "../../connectionResolver"; import { IActivityLogDocument } from "../../db/models/definitions/activityLogs"; import { getContentTypeDetail } from "../../messageBroker"; export default { async createdUser(activityLog: IActivityLogDocument) { return ( activityLog.createdBy && { __typename: "User", _id: activityLog.createdBy } ); }, async contentTypeDetail( activityLog: IActivityLogDocument, _, { subdomain }: IContext ) { return getContentTypeDetail(subdomain, activityLog); } }; ```
/content/code_sandbox/packages/core/src/data/resolvers/activityLogByAction.ts
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
128
```xml <?xml version="1.0" encoding="UTF-8"?><!-- or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file path_to_url Unless required by applicable law or agreed to in writing, "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY specific language governing permissions and limitations --> <!DOCTYPE concept PUBLIC "-//OASIS//DTD DITA Concept//EN" "concept.dtd"> <concept rev="2.3.0" id="truncate_table"> <title>TRUNCATE TABLE Statement (<keyword keyref="impala23"/> or higher only)</title> <titlealts audience="PDF"><navtitle>TRUNCATE TABLE</navtitle></titlealts> <prolog> <metadata> <data name="Category" value="Impala"/> <data name="Category" value="SQL"/> <data name="Category" value="DDL"/> <data name="Category" value="S3"/> <data name="Category" value="Tables"/> <data name="Category" value="Disk Storage"/> <data name="Category" value="Developers"/> <data name="Category" value="Data Analysts"/> </metadata> </prolog> <conbody> <p rev="2.3.0"> <indexterm audience="hidden">TRUNCATE TABLE statement</indexterm> Removes the data from an Impala table while leaving the table itself. </p> <p conref="../shared/impala_common.xml#common/syntax_blurb"/> <codeblock>TRUNCATE [TABLE] <ph rev="2.5.0 IMPALA-2641">[IF EXISTS]</ph> [<varname>db_name</varname>.]<varname>table_name</varname></codeblock> <p conref="../shared/impala_common.xml#common/ddl_blurb"/> <p conref="../shared/impala_common.xml#common/usage_notes_blurb"/> <p> Often used to empty tables that are used during ETL cycles, after the data has been copied to another table for the next stage of processing. This statement is a low-overhead alternative to dropping and recreating the table, or using <codeph>INSERT OVERWRITE</codeph> to replace the data during the next ETL cycle. </p> <p> This statement removes all the data and associated data files in the table. It can remove data files from internal tables, external tables, partitioned tables, and tables mapped to HBase or the Amazon Simple Storage Service (S3). The data removal applies to the entire table, including all partitions of a partitioned table. </p> <p> Any statistics produced by the <codeph>COMPUTE STATS</codeph> statement are reset when the data is removed. </p> <p> Make sure that you are in the correct database before truncating a table, either by issuing a <codeph>USE</codeph> statement first or by using a fully qualified name <codeph><varname>db_name</varname>.<varname>table_name</varname></codeph>. </p> <p>The optional <codeph>TABLE</codeph> keyword does not affect the behavior of the statement.</p> <p rev="2.5.0 IMPALA-2641"> The optional <codeph>IF EXISTS</codeph> clause makes the statement succeed whether or not the table exists. If the table does exist, it is truncated; if it does not exist, the statement has no effect. This capability is useful in standardized setup scripts that are might be run both before and after some of the tables exist. This clause is available in <keyword keyref="impala25_full"/> and higher. </p> <p conref="../shared/impala_common.xml#common/disk_space_blurb"/> <p conref="../shared/impala_common.xml#common/s3_blurb"/> <p rev="2.2.0"> Although Impala cannot write new data to a table stored in the Amazon S3 filesystem, the <codeph>TRUNCATE TABLE</codeph> statement can remove data files from S3. See <xref href="impala_s3.xml#s3"/> for details about working with S3 tables. </p> <p conref="../shared/impala_common.xml#common/cancel_blurb_no"/> <p conref="../shared/impala_common.xml#common/permissions_blurb"/> <p rev=""> The user ID that the <cmdname>impalad</cmdname> daemon runs under, typically the <codeph>impala</codeph> user, must have write permission for all the files and directories that make up the table. </p> <p conref="../shared/impala_common.xml#common/kudu_blurb"/> <p conref="../shared/impala_common.xml#common/kudu_no_truncate_table"/> <p conref="../shared/impala_common.xml#common/example_blurb"/> <p> The following example shows a table containing some data and with table and column statistics. After the <codeph>TRUNCATE TABLE</codeph> statement, the data is removed and the statistics are reset. </p> <codeblock>CREATE TABLE truncate_demo (x INT); INSERT INTO truncate_demo VALUES (1), (2), (4), (8); SELECT COUNT(*) FROM truncate_demo; +----------+ | count(*) | +----------+ | 4 | +----------+ COMPUTE STATS truncate_demo; +-----------------------------------------+ | summary | +-----------------------------------------+ | Updated 1 partition(s) and 1 column(s). | +-----------------------------------------+ SHOW TABLE STATS truncate_demo; +-------+--------+------+--------------+-------------------+--------+-------------------+ | #Rows | #Files | Size | Bytes Cached | Cache Replication | Format | Incremental stats | +-------+--------+------+--------------+-------------------+--------+-------------------+ | 4 | 1 | 8B | NOT CACHED | NOT CACHED | TEXT | false | +-------+--------+------+--------------+-------------------+--------+-------------------+ SHOW COLUMN STATS truncate_demo; +--------+------+------------------+--------+----------+----------+ | Column | Type | #Distinct Values | #Nulls | Max Size | Avg Size | +--------+------+------------------+--------+----------+----------+ | x | INT | 4 | -1 | 4 | 4 | +--------+------+------------------+--------+----------+----------+ -- After this statement, the data and the table/column stats will be gone. TRUNCATE TABLE truncate_demo; SELECT COUNT(*) FROM truncate_demo; +----------+ | count(*) | +----------+ | 0 | +----------+ SHOW TABLE STATS truncate_demo; +-------+--------+------+--------------+-------------------+--------+-------------------+ | #Rows | #Files | Size | Bytes Cached | Cache Replication | Format | Incremental stats | +-------+--------+------+--------------+-------------------+--------+-------------------+ | -1 | 0 | 0B | NOT CACHED | NOT CACHED | TEXT | false | +-------+--------+------+--------------+-------------------+--------+-------------------+ SHOW COLUMN STATS truncate_demo; +--------+------+------------------+--------+----------+----------+ | Column | Type | #Distinct Values | #Nulls | Max Size | Avg Size | +--------+------+------------------+--------+----------+----------+ | x | INT | -1 | -1 | 4 | 4 | +--------+------+------------------+--------+----------+----------+ </codeblock> <p> The following example shows how the <codeph>IF EXISTS</codeph> clause allows the <codeph>TRUNCATE TABLE</codeph> statement to be run without error whether or not the table exists: </p> <codeblock rev="2.5.0 IMPALA-2641">CREATE TABLE staging_table1 (x INT, s STRING); Fetched 0 row(s) in 0.33s SHOW TABLES LIKE 'staging*'; +----------------+ | name | +----------------+ | staging_table1 | +----------------+ Fetched 1 row(s) in 0.25s -- Our ETL process involves removing all data from several staging tables -- even though some might be already dropped, or not created yet. TRUNCATE TABLE IF EXISTS staging_table1; Fetched 0 row(s) in 5.04s TRUNCATE TABLE IF EXISTS staging_table2; Fetched 0 row(s) in 0.25s TRUNCATE TABLE IF EXISTS staging_table3; Fetched 0 row(s) in 0.25s </codeblock> <p conref="../shared/impala_common.xml#common/related_info"/> <p> <xref href="impala_tables.xml#tables"/>, <xref href="impala_alter_table.xml#alter_table"/>, <xref href="impala_create_table.xml#create_table"/>, <xref href="impala_partitioning.xml#partitioning"/>, <xref href="impala_tables.xml#internal_tables"/>, <xref href="impala_tables.xml#external_tables"/> </p> </conbody> </concept> ```
/content/code_sandbox/docs/topics/impala_truncate_table.xml
xml
2016-04-13T07:00:08
2024-08-16T10:10:44
impala
apache/impala
1,115
2,092
```xml import { graphql, FragmentType, useFragment } from './gql'; export const FilmFragment = graphql(/* GraphQL */ ` fragment FilmItem on Film { id title releaseDate producers } `); const Film = (props: { /* tweet property has the correct type */ film: FragmentType<typeof FilmFragment>; }) => { const film = useFragment(FilmFragment, props.film); return ( <div> <h3>{film.title}</h3> <p>{film.releaseDate}</p> </div> ); }; export default Film; ```
/content/code_sandbox/examples/react/tanstack-react-query/src/Film.tsx
xml
2016-12-05T19:15:11
2024-08-15T14:56:08
graphql-code-generator
dotansimha/graphql-code-generator
10,759
131
```xml import { ILabShell } from '@jupyterlab/application'; import { DocumentWidget } from '@jupyterlab/docregistry'; import { IRunningSessionManagers, IRunningSessions } from '@jupyterlab/running'; import { ITranslator } from '@jupyterlab/translation'; import { fileIcon, LabIcon } from '@jupyterlab/ui-components'; import { ISignal, Signal } from '@lumino/signaling'; import { Widget } from '@lumino/widgets'; /** * A class used to consolidate the signals used to rerender the open tabs section. */ class OpenTabsSignaler { constructor(labShell: ILabShell) { this._labShell = labShell; this._labShell.layoutModified.connect(this._emitTabsChanged, this); } /** * A signal that fires when the open tabs section should be rerendered. */ get tabsChanged(): ISignal<this, void> { return this._tabsChanged; } /** * Add a widget to watch for title changing. * * @param widget A widget whose title may change. */ addWidget(widget: Widget): void { widget.title.changed.connect(this._emitTabsChanged, this); this._widgets.push(widget); } /** * Emit the main signal that indicates the open tabs should be rerendered. */ private _emitTabsChanged(): void { this._widgets.forEach(widget => { widget.title.changed.disconnect(this._emitTabsChanged, this); }); this._widgets = []; this._tabsChanged.emit(void 0); } private _tabsChanged = new Signal<this, void>(this); private _labShell: ILabShell; private _widgets: Widget[] = []; } /** * Add the open tabs section to the running panel. * * @param managers - The IRunningSessionManagers used to register this section. * @param translator - The translator to use. * @param labShell - The ILabShell. */ export function addOpenTabsSessionManager( managers: IRunningSessionManagers, translator: ITranslator, labShell: ILabShell ): void { const signaler = new OpenTabsSignaler(labShell); const trans = translator.load('jupyterlab'); managers.add({ name: trans.__('Open Tabs'), supportsMultipleViews: false, running: () => { return Array.from(labShell.widgets('main')).map((widget: Widget) => { signaler.addWidget(widget); return new OpenTab(widget); }); }, shutdownAll: () => { for (const widget of labShell.widgets('main')) { widget.close(); } }, refreshRunning: () => { return void 0; }, runningChanged: signaler.tabsChanged, shutdownLabel: trans.__('Close'), shutdownAllLabel: trans.__('Close All'), shutdownAllConfirmationText: trans.__( 'Are you sure you want to close all open tabs?' ) }); class OpenTab implements IRunningSessions.IRunningItem { constructor(widget: Widget) { this._widget = widget; } open() { labShell.activateById(this._widget.id); } shutdown() { this._widget.close(); } icon() { const widgetIcon = this._widget.title.icon; return widgetIcon instanceof LabIcon ? widgetIcon : fileIcon; } label() { return this._widget.title.label; } labelTitle() { let labelTitle: string; if (this._widget instanceof DocumentWidget) { labelTitle = this._widget.context.path; } else { labelTitle = this._widget.title.label; } return labelTitle; } private _widget: Widget; } } ```
/content/code_sandbox/packages/running-extension/src/opentabs.ts
xml
2016-06-03T20:09:17
2024-08-16T19:12:44
jupyterlab
jupyterlab/jupyterlab
14,019
810
```xml import {Context, Inject, Middleware} from "@tsed/common"; import {getValue} from "@tsed/core"; import {Unauthorized} from "@tsed/exceptions"; import {promisify} from "util"; import {FormioService} from "../services/FormioService.js"; /** * @middleware * @formio */ @Middleware() export class FormioAuthMiddleware { @Inject() protected formio: FormioService; get tokenHandler(): any { return promisify(this.formio.middleware.tokenHandler); } async use(@Context() ctx: Context) { const req = ctx.getRequest(); const res = ctx.getResponse(); await this.tokenHandler(req, res); if (!getValue(req, "token.user._id")) { throw new Unauthorized("User unauthorized"); } } } ```
/content/code_sandbox/packages/third-parties/formio/src/middlewares/FormioAuthMiddleware.ts
xml
2016-02-21T18:38:47
2024-08-14T21:19:48
tsed
tsedio/tsed
2,817
173
```xml import { useEffect, useMemo, useState } from 'react'; import { useLoading } from '@proton/hooks'; import { getIsCalendarUrlEventManagerCreate, getIsCalendarUrlEventManagerDelete, getIsCalendarUrlEventManagerUpdate, transformLinkFromAPI, transformLinksFromAPI, } from '@proton/shared/lib/calendar/sharing/shareUrl/shareUrl'; import { getIsCalendarEventManagerDelete } from '@proton/shared/lib/eventManager/calendar/helpers'; import type { SimpleMap } from '@proton/shared/lib/interfaces'; import type { CalendarLink, CalendarUrl, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import type { CalendarEventManager, CalendarUrlEventManager, CalendarUrlEventManagerDelete, } from '@proton/shared/lib/interfaces/calendar/EventManager'; import { splitKeys } from '@proton/shared/lib/keys'; import updateItem from '@proton/utils/updateItem'; import { useEventManager, useGetCalendarInfo, useNotifications } from '../../../hooks'; import { useGetCalendarPublicLinks } from '../../../hooks/useGetCalendarPublicLinks'; import { useCalendarModelEventManager } from '../../eventManager/calendar'; const useCalendarShareUrls = (calendars: VisualCalendar[]) => { const { createNotification } = useNotifications(); const getCalendarInfo = useGetCalendarInfo(); const getPublicLinks = useGetCalendarPublicLinks(); const { subscribe: coreSubscribe } = useEventManager(); const { subscribe: calendarSubscribe } = useCalendarModelEventManager(); const [linksMap, setLinksMap] = useState<SimpleMap<CalendarLink[]>>({}); const [loading, withLoading] = useLoading(true); const calendarIDs = useMemo(() => calendars.map(({ ID }) => ID), [calendars]); const handleError = ({ message }: Error) => createNotification({ type: 'error', text: message }); const handleDeleteCalendar = (calendarID: string) => { setLinksMap((linksMap) => { const newMap = { ...linksMap }; delete newMap[calendarID]; return newMap; }); }; const handleDeleteLink = ({ ID }: CalendarUrlEventManagerDelete) => { setLinksMap((linksMap) => { return Object.fromEntries( Object.entries(linksMap).map(([calendarID, links]) => { const newLinks = links?.filter(({ CalendarUrlID }) => CalendarUrlID !== ID); return [calendarID, newLinks]; }) ); }); }; const handleAddOrUpdateLink = async (calendarUrl: CalendarUrl) => { const { CalendarID } = calendarUrl; const calendar = calendars.find(({ ID }) => ID === CalendarID); if (!calendar) { return; } const { calendarKeys, passphrase } = await getCalendarInfo(CalendarID); const { privateKeys } = splitKeys(calendarKeys); const link = await transformLinkFromAPI({ calendarUrl, privateKeys, calendarPassphrase: passphrase, onError: handleError, }); setLinksMap((linksMap) => { const previousLinks = linksMap[CalendarID] || []; const linkIndex = previousLinks.findIndex( ({ CalendarUrlID }) => CalendarUrlID === calendarUrl.CalendarUrlID ); const newLinks = linkIndex === -1 ? [...previousLinks, link] : updateItem(previousLinks, linkIndex, link); return { ...linksMap, [CalendarID]: newLinks, }; }); }; // load links useEffect(() => { const getAllLinks = async () => { const map: SimpleMap<CalendarLink[]> = {}; await Promise.all( calendars.map(async (calendar) => { const calendarID = calendar.ID; const { calendarKeys, passphrase } = await getCalendarInfo(calendarID); const { privateKeys } = splitKeys(calendarKeys); try { const { CalendarUrls } = await getPublicLinks(calendarID); map[calendarID] = await transformLinksFromAPI({ calendarUrls: CalendarUrls, privateKeys, calendarPassphrase: passphrase, onError: handleError, }); } catch (e: any) { handleError(e); } }) ); setLinksMap(map); }; void withLoading(getAllLinks()); }, []); // subscribe to general event loop useEffect(() => { return coreSubscribe(({ Calendars = [] }: { Calendars?: CalendarEventManager[] }) => { Calendars.forEach((event) => { if (getIsCalendarEventManagerDelete(event)) { handleDeleteCalendar(event.ID); } }); }); }, []); // subscribe to calendar event loop useEffect(() => { return calendarSubscribe( calendarIDs, ({ CalendarURL: CalendarURLEvents = [] }: { CalendarURL?: CalendarUrlEventManager[] }) => { CalendarURLEvents.forEach((event) => { if (getIsCalendarUrlEventManagerDelete(event)) { handleDeleteLink(event); } if (getIsCalendarUrlEventManagerCreate(event) || getIsCalendarUrlEventManagerUpdate(event)) { // TODO: The code below is prone to race conditions. Namely if a new event manager update // comes before this promise is resolved. void handleAddOrUpdateLink(event.CalendarUrl); } }); } ); }, [calendarIDs]); return { linksMap, isLoadingLinks: loading, }; }; export default useCalendarShareUrls; ```
/content/code_sandbox/packages/components/containers/calendar/shareURL/useCalendarShareUrls.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
1,151
```xml import { Alert, Button, ButtonMutate, Step, Steps, Wrapper, __ } from "@erxes/ui/src"; import Appearance from "./step/Appearance"; import { Content, LeftContent } from "../../styles"; import { ControlWrapper, Indicator, StepWrapper } from "@erxes/ui/src/components/step/styles"; import { IPos, IProductGroup, ISlot } from "../../types"; import CardsConfig from "./step/CardsConfig"; import ConfigStep from "./step/ConfigStep"; import DeliveryConfig from "./step/DeliveryConfig"; import EbarimtConfig from "./step/EbarimtConfig"; import ErkhetConfig from "./step/ErkhetConfig"; import GeneralStep from "./step/GeneralStep"; import { Link } from "react-router-dom"; import React, { useState } from "react"; import PermissionStep from "./step/Permission"; import PaymentsStep from "./step/PaymentsStep"; import { ALLOW_TYPES } from "../../constants"; import ScreensConfig from "./step/Screens"; type Props = { pos?: IPos; loading?: boolean; isActionLoading: boolean; groups: IProductGroup[]; save: (params: any) => void; slots: ISlot[]; envs: any; }; const Pos = (props: Props) => { const { pos = {} as IPos, loading, isActionLoading, groups, save, slots, envs } = props; const [state, setState] = useState({ pos, carousel: "pos", groups: groups || [], uiOptions: pos.uiOptions || { colors: { bodyColor: "#FFFFFF", headerColor: "#6569DF", footerColor: "#3CCC38" }, logo: "", bgImage: "", favIcon: "", receiptIcon: "", kioskHeaderImage: "", mobileAppImage: "", qrCodeImage: "" }, isSkip: false, ebarimtConfig: pos.ebarimtConfig, erkhetConfig: pos.erkhetConfig, deliveryConfig: pos.deliveryConfig, cardsConfig: pos.cardsConfig, slots: slots || [], checkRemainder: pos.checkRemainder || false, allowTypes: pos.allowTypes || ALLOW_TYPES.filter(at => at.kind === "sale").map(at => at.value) }); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!state.pos.name) { return Alert.error("Enter POS name"); } if (!state.pos.adminIds || !state.pos.adminIds.length) { return Alert.error("Choose admin users"); } if (!state.pos.cashierIds || !state.pos.cashierIds.length) { return Alert.error("Choose cashier users"); } const saveTypes = state.allowTypes.filter(at => at); if (!saveTypes.length) { return Alert.error("Toggle at least one type"); } const cleanMappings = (state.pos.catProdMappings || []).map(m => ({ _id: m._id, categoryId: m.categoryId, productId: m.productId, code: m.code || "", name: m.name || "" })); const cleanSlot = (state.slots || []).map(m => ({ _id: m._id, code: m.code, name: m.name, posId: m.posId, option: m.option })); let doc: any = { name: state.pos.name, description: state.pos.description, pdomain: state.pos.pdomain, erxesAppToken: state.pos.erxesAppToken, productDetails: state.pos.productDetails || [], groups: state.groups, adminIds: state.pos.adminIds, cashierIds: state.pos.cashierIds, paymentIds: state.pos.paymentIds || [], paymentTypes: state.pos.paymentTypes || [], kioskMachine: state.pos.kioskMachine, uiOptions: state.uiOptions, ebarimtConfig: state.ebarimtConfig, erkhetConfig: state.erkhetConfig, catProdMappings: cleanMappings, posSlots: cleanSlot, isOnline: state.pos.isOnline, onServer: state.pos.onServer, waitingScreen: state.pos.waitingScreen, kitchenScreen: state.pos.kitchenScreen, branchId: state.pos.branchId, departmentId: state.pos.departmentId, allowBranchIds: state.pos.allowBranchIds, beginNumber: state.pos.beginNumber, maxSkipNumber: Number(state.pos.maxSkipNumber) || 0, orderPassword: state.pos.orderPassword, scopeBrandIds: pos.scopeBrandIds || [], initialCategoryIds: state.pos.initialCategoryIds || [], kioskExcludeCategoryIds: state.pos.kioskExcludeCategoryIds || [], kioskExcludeProductIds: state.pos.kioskExcludeProductIds || [], deliveryConfig: state.deliveryConfig, cardsConfig: state.cardsConfig, checkRemainder: state.checkRemainder, permissionConfig: state.pos.permissionConfig || {}, allowTypes: saveTypes, isCheckRemainder: state.pos.isCheckRemainder, checkExcludeCategoryIds: state.pos.checkExcludeCategoryIds || [], banFractions: state.pos.banFractions }; if (!pos.isOnline) { doc = { ...doc, beginNumber: "", allowBranchIds: [] }; } save(doc); }; const onChange = (key: string, value: any) => { setState(prevState => ({ ...prevState, [key]: value })); }; const onStepClick = currentStepNumber => { let carousel = "form"; switch (currentStepNumber) { case 1: carousel = state.isSkip ? "form" : "callout"; break; case 2: carousel = state.isSkip ? "form" : "callout"; break; case 7: carousel = "success"; break; default: break; } return setState(prevState => ({ ...prevState, carousel })); }; const renderButtons = () => { const SmallLoader = ButtonMutate.SmallLoader; const cancelButton = ( <Link to={`/pos`}> <Button btnStyle="simple" icon="times-circle"> Cancel </Button> </Link> ); return ( <Button.Group> {cancelButton} <Button disabled={isActionLoading} btnStyle="success" icon={isActionLoading ? undefined : "check-circle"} onClick={handleSubmit} > {isActionLoading && <SmallLoader />} Save </Button> </Button.Group> ); }; const breadcrumb = [{ title: "POS List", link: `/pos` }, { title: "POS" }]; return ( <StepWrapper> <Wrapper.Header title={__("Pos")} breadcrumb={breadcrumb} /> <Content> <LeftContent> <Steps> <Step img="/images/icons/erxes-12.svg" title={`General`} onClick={onStepClick} > <GeneralStep onChange={onChange} pos={state.pos} posSlots={state.slots} allowTypes={state.allowTypes} envs={envs} /> </Step> <Step img="/images/icons/erxes-12.svg" title={`Payments`} onClick={onStepClick} > <PaymentsStep onChange={onChange} pos={state.pos} posSlots={state.slots} envs={envs} /> </Step> <Step img="/images/icons/erxes-02.svg" title={`Permission`} onClick={onStepClick} > <PermissionStep onChange={onChange} pos={state.pos} envs={envs} /> </Step> <Step img="/images/icons/erxes-10.svg" title={`Product & Service`} onClick={onStepClick} > <ConfigStep onChange={onChange} pos={state.pos} groups={state.groups} catProdMappings={state.pos.catProdMappings || []} /> </Step> <Step img="/images/icons/erxes-04.svg" title={"Appearance"} onClick={onStepClick} noButton={true} > <Appearance onChange={onChange} uiOptions={state.uiOptions} logoPreviewUrl={state.uiOptions.logo} /> </Step> <Step img="/images/icons/erxes-14.svg" title={"Screens Config"} onClick={onStepClick} noButton={true} > <ScreensConfig onChange={onChange} pos={state.pos} checkRemainder={state.checkRemainder} /> </Step> <Step img="/images/icons/erxes-05.svg" title={"ebarimt Config"} onClick={onStepClick} noButton={true} > <EbarimtConfig onChange={onChange} pos={pos} /> </Step> <Step img="/images/icons/erxes-07.svg" title={"finance Config"} onClick={onStepClick} noButton={true} > <ErkhetConfig onChange={onChange} pos={state.pos} checkRemainder={state.checkRemainder} /> </Step> <Step img="/images/icons/erxes-09.svg" title={"Delivery Config"} onClick={onStepClick} noButton={true} > <DeliveryConfig onChange={onChange} pos={state.pos} /> </Step> <Step img="/images/icons/erxes-07.svg" title={"Sync Cards"} onClick={onStepClick} noButton={true} > <CardsConfig onChange={onChange} pos={state.pos} /> </Step> </Steps> <ControlWrapper> <Indicator> {__("You are")} {state.pos ? "editing" : "creating"}{" "} <strong>{state.pos.name || ""}</strong> {__("pos")} </Indicator> {renderButtons()} </ControlWrapper> </LeftContent> </Content> </StepWrapper> ); }; export default Pos; ```
/content/code_sandbox/packages/plugin-pos-ui/src/pos/components/Pos.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
2,261
```xml <?xml version="1.0" encoding="UTF-8"?> <!-- -/-/- Dockerfile Maven Plugin %% %% path_to_url Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -\-\- --> <project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <groupId>com.spotify.it</groupId> <artifactId>multi-module</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <description>This project has two modules that depend on each other.</description> <modules> <module>a</module> <module>b</module> </modules> <build> <extensions> <extension> <groupId>@project.groupId@</groupId> <artifactId>dockerfile-maven-extension</artifactId> <version>@project.version@</version> </extension> </extensions> </build> </project> ```
/content/code_sandbox/plugin/src/it/multi-module/pom.xml
xml
2016-03-16T12:42:37
2024-08-14T21:23:10
dockerfile-maven
spotify/dockerfile-maven
2,747
259
```xml /** * @license Apache-2.0 * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ import { TestBed } from "@angular/core/testing"; import { hasProperty, isArray, isArrayBufferView, isBoolean, isNumber, isNumberArray, isRecord, isString, isStringArray } from "."; describe("Typing utility functions", () => { beforeEach(() => TestBed.configureTestingModule({})); it("should check for property existence correctly", () => { let test = {}; expect(hasProperty(test, "anything")).toBeFalse(); expect(hasProperty(test, 0)).toBeFalse(); test = {anything: "something"}; expect(hasProperty(test, "anything")).toBeTrue(); expect(hasProperty(test, 0)).toBeFalse(); // eslint-disable-next-line @typescript-eslint/naming-convention test = {0: "something"}; expect(hasProperty(test, "anything")).toBeFalse(); expect(hasProperty(test, 0)).toBeTrue(); }); it("should check property types correctly", () => { const wrong = {wrong: "type"}; const isNum = (x: unknown): x is number => typeof x === "number"; expect(hasProperty(wrong, "wrong", isNum)).toBeFalse(); const right = {right: 0}; expect(hasProperty(right, "right", isNum)).toBeTrue(); }); it("should check for string types correctly", () => { let test: string | number = ""; expect(isString(test)).toBeTrue(); test = 5; expect(isString(test)).toBeFalse(); }); it("should check for numeric types correctly", () => { let test: string | number = "0"; expect(isNumber(test)).toBeFalse(); test = 5; expect(isNumber(test)).toBeTrue(); }); it("should check for boolean types correctly", () => { let test: string | boolean = "true"; expect(isBoolean(test)).toBeFalse(); test = true; expect(isBoolean(test)).toBeTrue(); }); it("should check ambiguous record types correctly", () => { expect(isRecord(null)).toBeFalse(); expect(isRecord({})).toBeTrue(); }); it("should check homogenous record types correctly", () => { const passes = { all: "properties", are: "strings" }; expect(isRecord(passes, "string")).toBeTrue(); const numbers = { numeric: 1, only: 5.23e7, properties: 0x2e, }; expect(isRecord(numbers, "number")).toBeTrue(); const fails = { not: "all", properties: "are", strings: 0 }; expect(isRecord(fails, "string")).toBeFalse(); const isZero = (x: unknown): x is 0 => x === 0; expect(isRecord(fails, isZero)).toBeFalse(); const customPasses = { everything: 0, is: 0, zero: 0 }; expect(isRecord(customPasses, isZero)).toBeTrue(); }); it("should check homogenous array types correctly", () => { const a = {}; expect(isArray(a)).toBeFalse(); const b = new Array(); expect(isArray(b)).toBeTrue(); b.push(5); expect(isArray(b)).toBeTrue(); expect(isArray(b, "number")).toBeTrue(); expect(isArray(b, "string")).toBeFalse(); b.push("test"); expect(isArray(b)).toBeTrue(); expect(isArray(b, "number")).toBeFalse(); expect(isArray(b, "string")).toBeFalse(); expect(isArray(b, (x): x is Array<number | string> => typeof x === "number" || typeof x === "string")).toBeTrue(); }); it("should verify that only objects can be records", ()=>{ expect(isRecord(0, (_): _ is unknown => true)).toBeFalse(); }); it("should be able to verify existence and type of array properties", () => { const a = { test: new Array<number|string>() }; expect(hasProperty(a, "test", isArray)).toBeTrue(); a.test.push("test"); expect(hasProperty(a, "test", isStringArray)).toBeTrue(); expect(hasProperty(a, "test", isNumberArray)).toBeFalse(); a.test.push(5); expect(hasProperty(a, "test", isArray)).toBeTrue(); expect(hasProperty(a, "test", isStringArray)).toBeFalse(); expect(hasProperty(a, "test", isNumberArray)).toBeFalse(); }); it("knows if an object is an ArrayBufferView", () => { expect(isArrayBufferView(undefined)).toBeFalse(); expect(isArrayBufferView(undefined)).toBeFalse(); expect(isArrayBufferView(undefined)).toBeFalse(); expect(isArrayBufferView(new Int8Array())).toBeTrue(); expect(isArrayBufferView(new Uint8Array())).toBeTrue(); expect(isArrayBufferView(new Uint8ClampedArray())).toBeTrue(); expect(isArrayBufferView(new Int16Array())).toBeTrue(); expect(isArrayBufferView(new Uint16Array())).toBeTrue(); expect(isArrayBufferView(new Int32Array())).toBeTrue(); expect(isArrayBufferView(new Uint32Array())).toBeTrue(); expect(isArrayBufferView(new DataView(new ArrayBuffer(0)))).toBeTrue(); expect(isArrayBufferView([1, 2, 3])).toBeFalse(); expect(isArrayBufferView([0x01n, 2n, 3n])).toBeFalse(); }); }); ```
/content/code_sandbox/experimental/traffic-portal/src/app/utils/index.spec.ts
xml
2016-09-02T07:00:06
2024-08-16T03:50:21
trafficcontrol
apache/trafficcontrol
1,043
1,247
```xml import { IExperimentRunInfo } from 'shared/models/ModelRecord'; import { IBlob } from 'shared/models/Versioning/Blob/Blob'; import { IFolder } from 'shared/models/Versioning/RepositoryData'; export type IBlobView = IBlob & { experimentRuns: IExperimentRunInfo[] }; export type ICommitComponentView = IBlobView | IFolder; ```
/content/code_sandbox/webapp/client/src/features/versioning/repositoryData/store/types.ts
xml
2016-10-19T01:07:26
2024-08-14T03:53:55
modeldb
VertaAI/modeldb
1,689
82
```xml import type { Product } from 'src/misc/custom-types' import { getClient } from '../client' import type { IntegrationProps } from '../misc/types' export const listProductPrices: IntegrationProps['actions']['listProductPrices'] = async ({ ctx, logger }) => { const StripeClient = getClient(ctx.configuration) let response try { const prices = await StripeClient.listAllPricesBasic(undefined, true) prices.map((price) => { return { productName: (price.product as any).name, } }) const products: Record<string, Product> = {} for (const price of prices) { if (typeof price.product !== 'string' && 'id' in price.product) { const product = products[price.product.id] if (product) { product.prices.push({ unit_amount: price.unit_amount, currency: price.currency, recurring: price.recurring, }) } else { products[price.product.id] = { name: (price.product as any).name, prices: [ { unit_amount: price.unit_amount, currency: price.currency, recurring: price.recurring, }, ], } } } } response = { products, } logger.forBot().info('Successful - List Product Prices') } catch (error) { response = {} logger.forBot().debug(`'List Product Prices' exception ${JSON.stringify(error)}`) } return response } ```
/content/code_sandbox/integrations/stripe/src/actions/list-product-prices.ts
xml
2016-11-16T21:57:59
2024-08-16T18:45:35
botpress
botpress/botpress
12,401
319
```xml export function assertUnreachableAndThrow(uncheckedCase: never): never { throw Error('Unchecked case ' + uncheckedCase) } export function assertUnreachableAndLog(uncheckedCase: never): void { console.error('Unchecked case', uncheckedCase) } ```
/content/code_sandbox/packages/docs-shared/lib/AssertUnreachable.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
54
```xml import isEqual from "lodash/isEqual"; import { observable, action, computed } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; import { withTranslation, WithTranslation } from "react-i18next"; import { Waypoint } from "react-waypoint"; import { Pagination } from "@shared/constants"; import RootStore from "~/stores/RootStore"; import ArrowKeyNavigation from "~/components/ArrowKeyNavigation"; import DelayedMount from "~/components/DelayedMount"; import PlaceholderList from "~/components/List/Placeholder"; import withStores from "~/components/withStores"; import { dateToHeading } from "~/utils/date"; export interface PaginatedItem { id: string; createdAt?: string; updatedAt?: string; } type Props<T> = WithTranslation & RootStore & { fetch?: ( options: Record<string, any> | undefined ) => Promise<T[] | undefined> | undefined; options?: Record<string, any>; heading?: React.ReactNode; empty?: React.ReactNode; loading?: React.ReactElement; items?: T[]; className?: string; renderItem: (item: T, index: number) => React.ReactNode; renderError?: (options: { error: Error; retry: () => void; }) => React.ReactNode; renderHeading?: (name: React.ReactElement<any> | string) => React.ReactNode; onEscape?: (ev: React.KeyboardEvent<HTMLDivElement>) => void; }; @observer class PaginatedList<T extends PaginatedItem> extends React.PureComponent< Props<T> > { @observable error?: Error; @observable isFetchingMore = false; @observable isFetching = false; @observable isFetchingInitial = !this.props.items?.length; @observable fetchCounter = 0; @observable renderCount = 15; @observable offset = 0; @observable allowLoadMore = true; componentDidMount() { void this.fetchResults(); } componentDidUpdate(prevProps: Props<T>) { if ( prevProps.fetch !== this.props.fetch || !isEqual(prevProps.options, this.props.options) ) { this.reset(); void this.fetchResults(); } } reset = () => { this.offset = 0; this.allowLoadMore = true; this.renderCount = Pagination.defaultLimit; this.isFetching = false; this.isFetchingInitial = false; this.isFetchingMore = false; }; @action fetchResults = async () => { if (!this.props.fetch) { return; } this.isFetching = true; const counter = ++this.fetchCounter; const limit = this.props.options?.limit ?? Pagination.defaultLimit; this.error = undefined; try { const results = await this.props.fetch({ limit, offset: this.offset, ...this.props.options, }); if (results && (results.length === 0 || results.length < limit)) { this.allowLoadMore = false; } else { this.offset += limit; } this.renderCount += limit; this.isFetchingInitial = false; } catch (err) { this.error = err; } finally { // only the most recent fetch should end the loading state if (counter >= this.fetchCounter) { this.isFetching = false; this.isFetchingMore = false; } } }; @action loadMoreResults = async () => { // Don't paginate if there aren't more results or were currently fetching if (!this.allowLoadMore || this.isFetching) { return; } // If there are already cached results that we haven't yet rendered because // of lazy rendering then show another page. const leftToRender = (this.props.items?.length ?? 0) - this.renderCount; if (leftToRender > 0) { this.renderCount += Pagination.defaultLimit; } // If there are less than a pages results in the cache go ahead and fetch // another page from the server if (leftToRender <= Pagination.defaultLimit) { this.isFetchingMore = true; await this.fetchResults(); } }; @computed get itemsToRender() { return this.props.items?.slice(0, this.renderCount) ?? []; } render() { const { items = [], heading, auth, empty = null, renderHeading, renderError, onEscape, } = this.props; const showLoading = this.isFetching && !this.isFetchingMore && (!items?.length || (this.fetchCounter <= 1 && this.isFetchingInitial)); if (showLoading) { return ( this.props.loading || ( <DelayedMount> <div className={this.props.className}> <PlaceholderList count={5} /> </div> </DelayedMount> ) ); } if (items?.length === 0) { if (this.error && renderError) { return renderError({ error: this.error, retry: this.fetchResults }); } return empty; } return ( <> {heading} <ArrowKeyNavigation aria-label={this.props["aria-label"]} onEscape={onEscape} className={this.props.className} items={this.itemsToRender} > {() => { let previousHeading = ""; return this.itemsToRender.map((item, index) => { const children = this.props.renderItem(item, index); // If there is no renderHeading method passed then no date // headings are rendered if (!renderHeading) { return children; } // Our models have standard date fields, updatedAt > createdAt. // Get what a heading would look like for this item const currentDate = item.updatedAt || item.createdAt || previousHeading; const currentHeading = dateToHeading( currentDate, this.props.t, auth.user?.language ); // If the heading is different to any previous heading then we // should render it, otherwise the item can go under the previous // heading if ( children && (!previousHeading || currentHeading !== previousHeading) ) { previousHeading = currentHeading; return ( <React.Fragment key={item.id}> {renderHeading(currentHeading)} {children} </React.Fragment> ); } return children; }); }} </ArrowKeyNavigation> {this.allowLoadMore && ( <Waypoint key={this.renderCount} onEnter={this.loadMoreResults} /> )} </> ); } } export const Component = PaginatedList; export default withTranslation()(withStores(PaginatedList)); ```
/content/code_sandbox/app/components/PaginatedList.tsx
xml
2016-05-22T21:31:47
2024-08-16T19:57:22
outline
outline/outline
26,751
1,473
```xml /* tslint:disable:no-console */ import 'dotenv/config'; import { IgApiClient, IgCheckpointError } from '../src'; import Bluebird = require('bluebird'); import inquirer = require('inquirer'); /** * This method won't catch all checkpoint errors * There's currently a new checkpoint used by instagram which requires 'web-support' */ (async () => { const ig = new IgApiClient(); ig.state.generateDevice(process.env.IG_USERNAME); ig.state.proxyUrl = process.env.IG_PROXY; Bluebird.try(async () => { const auth = await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD); console.log(auth); }).catch(IgCheckpointError, async () => { console.log(ig.state.checkpoint); // Checkpoint info here await ig.challenge.auto(true); // Requesting sms-code or click "It was me" button console.log(ig.state.checkpoint); // Challenge info here const { code } = await inquirer.prompt([ { type: 'input', name: 'code', message: 'Enter code', }, ]); console.log(await ig.challenge.sendSecurityCode(code)); }).catch(e => console.log('Could not resolve checkpoint:', e, e.stack)); })(); ```
/content/code_sandbox/examples/checkpoint.example.ts
xml
2016-06-09T12:14:48
2024-08-16T10:07:22
instagram-private-api
dilame/instagram-private-api
5,877
269
```xml import React, {Component, ChangeEvent} from 'react' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' import {InjectedRouter} from 'react-router' import {Page} from 'src/reusable_ui' import NameSection from 'src/kapacitor/components/NameSection' import ValuesSection from 'src/kapacitor/components/ValuesSection' import RuleHandlers from 'src/kapacitor/components/RuleHandlers' import RuleHeaderSave from 'src/kapacitor/components/alert_rules/RuleHeaderSave' import RuleMessage from 'src/kapacitor/components/alert_rules/RuleMessage' import isValidMessage from 'src/kapacitor/utils/alertMessageValidation' import {createRule, editRule} from 'src/kapacitor/apis' import buildInfluxQLQuery from 'src/utils/influxql' import {timeRanges} from 'src/shared/data/timeRanges' import {DEFAULT_RULE_ID} from 'src/kapacitor/constants' import {notify as notifyAction} from 'src/shared/actions/notifications' import { notifyAlertRuleCreated, notifyAlertRuleCreateFailed, notifyAlertRuleUpdated, notifyAlertRuleUpdateFailed, notifyAlertRuleRequiresQuery, notifyAlertRuleRequiresConditionValue, notifyAlertRuleDeadmanInvalid, notifyTestAlertSent, notifyTestAlertFailed, } from 'src/shared/copy/notifications' import {ErrorHandling} from 'src/shared/decorators/errors' import { Source, AlertRule, Notification, Kapacitor, QueryConfig, TimeRange, } from 'src/types' import {Handler} from 'src/types/kapacitor' import { KapacitorQueryConfigActions, KapacitorRuleActions, } from 'src/types/actions' import {testAlertOutput} from 'src/shared/apis' interface Props { source: Source rule: AlertRule query: QueryConfig queryConfigs: QueryConfig[] queryConfigActions: KapacitorQueryConfigActions ruleActions: KapacitorRuleActions notify: (message: Notification) => void ruleID: string handlersFromConfig: Handler[] router: InjectedRouter kapacitor: Kapacitor configLink: string } interface Item { text: string } interface TypeItem extends Item { type: string } interface State { timeRange: TimeRange } class KapacitorRule extends Component<Props, State> { constructor(props) { super(props) this.state = { timeRange: timeRanges.find(tr => tr.lower === 'now() - 15m'), } } public render() { const { rule, source, ruleActions, queryConfigs, handlersFromConfig, queryConfigActions, } = this.props const {chooseTrigger, updateRuleValues} = ruleActions const {timeRange} = this.state return ( <Page> <Page.Header> <Page.Header.Left> <Page.Title title="Alert Rule Builder" /> </Page.Header.Left> <Page.Header.Right showSourceIndicator={true}> <RuleHeaderSave onSave={this.handleSave} validationError={this.validationError} /> </Page.Header.Right> </Page.Header> <Page.Contents> <div className="rule-builder"> <NameSection rule={rule} defaultName={rule.name} onRuleRename={ruleActions.updateRuleName} /> <ValuesSection rule={rule} source={source} timeRange={timeRange} onChooseTrigger={chooseTrigger} onAddEvery={this.handleAddEvery} onUpdateValues={updateRuleValues} query={queryConfigs[rule.queryID]} onRemoveEvery={this.handleRemoveEvery} queryConfigActions={queryConfigActions} onDeadmanChange={this.handleDeadmanChange} onRuleTypeInputChange={this.handleRuleTypeInputChange} onRuleTypeDropdownChange={this.handleRuleTypeDropdownChange} onChooseTimeRange={this.handleChooseTimeRange} /> <RuleHandlers rule={rule} ruleActions={ruleActions} handlersFromConfig={handlersFromConfig} onGoToConfig={this.handleSaveToConfig} onTestHandler={this.handleTestHandler} validationError={this.validationError} /> <RuleMessage rule={rule} ruleActions={ruleActions} /> </div> </Page.Contents> </Page> ) } private handleChooseTimeRange = ({lower}: TimeRange) => { const timeRange = timeRanges.find(range => range.lower === lower) this.setState({timeRange}) } private applyRuleWorkarounds(updatedRule: any): void { // defect #5768 - naming issue if (updatedRule.alertNodes?.teams?.length) { const teams = (updatedRule.alertNodes.teams[0] as unknown) as Record< string, unknown > if (teams['channel-url']) { teams.channel_url = teams['channel-url'] } } } private handleCreate = (pathname?: string) => { const {notify, queryConfigs, rule, kapacitor} = this.props const newRule = Object.assign({}, rule, { query: queryConfigs[rule.queryID], }) delete newRule.queryID this.applyRuleWorkarounds(newRule) createRule(kapacitor, newRule) .then(() => { this.exitPage(pathname) notify(notifyAlertRuleCreated(newRule.name)) }) .catch(e => { notify(notifyAlertRuleCreateFailed(newRule.name, e.data.message)) }) } private handleEdit = (pathname?: string) => { const {notify, queryConfigs, rule} = this.props const updatedRule = Object.assign({}, rule, { query: queryConfigs[rule.queryID], }) this.applyRuleWorkarounds(updatedRule) editRule(updatedRule) .then(() => { this.exitPage(pathname) notify(notifyAlertRuleUpdated(rule.name)) }) .catch(e => { notify( notifyAlertRuleUpdateFailed(rule.name, e?.data?.message || String(e)) ) }) } private exitPage(pathname?: string) { const {source, router} = this.props if (pathname) { return router.push(pathname) } const location = (router as any).location if (location?.query?.l === 't') { return router.push( `/sources/${source.id}/tickscripts${location?.search || ''}` ) } router.push(`/sources/${source.id}/alert-rules`) } private handleSave = () => { const {rule} = this.props if (rule.id === DEFAULT_RULE_ID) { this.handleCreate() } else { this.handleEdit() } } private handleSaveToConfig = (configName: string) => () => { const {rule, configLink, router} = this.props const pathname = `${configLink}#${configName}` if (this.validationError) { router.push({ pathname, }) return } if (rule.id === DEFAULT_RULE_ID) { this.handleCreate(pathname) } else { this.handleEdit(pathname) } } private handleTestHandler = (configName: string) => async ( handler: Record<string, unknown>, toTestProperty: Record<string, string> = {} ) => { const testData = Object.keys(handler).reduce<Record<string, unknown>>( (acc, key) => { // ignore: 'type' is created by UI, 'enabled' is not used by testing if (key === 'enabled' || key === 'type') { return acc } if (key === '_type') { acc.type = handler._type return acc } if (toTestProperty[key]) { acc[toTestProperty[key]] = handler[key] return acc } // common property acc[key] = handler[key] // there are naming problems in kapacitor, - and _ are used inconsistently in tickscript and testing options acc[key.replace('-', '_')] = acc[key] acc[key.replace('_', '-')] = acc[key] return acc }, {} ) try { const {data} = await testAlertOutput( this.props.kapacitor, configName, testData, testData ) if (data.success) { this.props.notify(notifyTestAlertSent(configName)) } else { this.props.notify(notifyTestAlertFailed(configName, data.message)) } } catch (error) { this.props.notify(notifyTestAlertFailed(configName)) } } private handleAddEvery = (frequency: string) => { const { rule: {id: ruleID}, ruleActions: {addEvery}, } = this.props addEvery(ruleID, frequency) } private handleRemoveEvery = () => { const { rule: {id: ruleID}, ruleActions: {removeEvery}, } = this.props removeEvery(ruleID) } private get validationError(): string { const {rule, query} = this.props if (rule.trigger === 'deadman') { return this.deadmanValidation() } if (!buildInfluxQLQuery({lower: ''}, query)) { return notifyAlertRuleRequiresQuery() } if (!rule.values.value) { return notifyAlertRuleRequiresConditionValue() } if (rule.message && !isValidMessage(rule.message)) { return 'Please correct template values in the alert message.' } return '' } private deadmanValidation = () => { const {query} = this.props if (query && (!query.database || !query.measurement)) { return notifyAlertRuleDeadmanInvalid() } return '' } private handleRuleTypeDropdownChange = ({type, text}: TypeItem) => { const {ruleActions, rule} = this.props ruleActions.updateRuleValues(rule.id, rule.trigger, { ...this.props.rule.values, [type]: text, }) } private handleRuleTypeInputChange = (e: ChangeEvent<HTMLInputElement>) => { const {ruleActions, rule} = this.props const {lower, upper} = e.target.form ruleActions.updateRuleValues(rule.id, rule.trigger, { ...this.props.rule.values, value: lower.value, rangeValue: upper ? upper.value : '', }) } private handleDeadmanChange = ({text}: Item) => { const {ruleActions, rule} = this.props ruleActions.updateRuleValues(rule.id, rule.trigger, {period: text}) } } const mapDispatchToProps = dispatch => ({ notify: bindActionCreators(notifyAction, dispatch), }) export default connect(null, mapDispatchToProps)(ErrorHandling(KapacitorRule)) ```
/content/code_sandbox/ui/src/kapacitor/components/KapacitorRule.tsx
xml
2016-08-24T23:28:56
2024-08-13T19:50:03
chronograf
influxdata/chronograf
1,494
2,399
```xml import { StackScreenProps } from '@react-navigation/stack'; import * as React from 'react'; import { BranchList } from './BranchList'; import { HomeStackRoutes } from '../../navigation/Navigation.types'; export function BranchListScreen({ route }: StackScreenProps<HomeStackRoutes, 'Branches'>) { const { appId } = route.params ?? {}; return <BranchList appId={appId} />; } ```
/content/code_sandbox/apps/expo-go/src/screens/BranchListScreen/index.tsx
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
88
```xml import { Button, CopyButton } from '@@/buttons'; import { FormSectionTitle } from '@@/form-components/FormSectionTitle'; import { TextTip } from '@@/Tip/TextTip'; import { Link } from '@@/Link'; export function DisplayUserAccessToken({ apikey }: { apikey: string }) { return ( <> <FormSectionTitle>New access token</FormSectionTitle> <TextTip> Please copy the new access token. You won&#39;t be able to view the token again. </TextTip> <div className="pt-5"> <div className="inline-flex"> <div className="">{apikey}</div> <div> <CopyButton copyText={apikey} color="link" data-cy="create-access-token-copy-button" /> </div> </div> <hr /> </div> <Button as={Link} props={{ to: 'portainer.account', }} data-cy="create-access-token-done-button" > Done </Button> </> ); } ```
/content/code_sandbox/app/react/portainer/account/CreateAccessTokenView/DisplayUserAccessToken.tsx
xml
2016-05-19T20:15:28
2024-08-16T19:15:14
portainer
portainer/portainer
30,083
244
```xml /* * * See the LICENSE file at the top-level directory of this distribution * for licensing information. * * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation, * no part of this software, including this file, may be copied, modified, * propagated, or distributed except according to the terms contained in the * LICENSE file. * * Removal or modification of this copyright notice is prohibited. */ import { utils, address as cryptoAddress } from '@liskhq/lisk-cryptography'; import { Chain, Transaction, Event, TransactionAttrs } from '@liskhq/lisk-chain'; import { TransactionPool } from '@liskhq/lisk-transaction-pool'; import { LiskValidationError } from '@liskhq/lisk-validator'; import { ABI, TransactionExecutionResult, TransactionVerifyResult } from '../../../../src/abi'; import { Logger } from '../../../../src/logger'; import { Broadcaster } from '../../../../src/engine/generator/broadcaster'; import { InvalidTransactionError } from '../../../../src/engine/generator/errors'; import { fakeLogger } from '../../../utils/mocks'; import { TxpoolEndpoint } from '../../../../src/engine/endpoint/txpool'; import { StateMachine } from '../../../../src'; import { ED25519_PUBLIC_KEY_LENGTH } from '../../../../src/engine/bft/constants'; const ED25519_SIGNATURE_LENGTH = 64; describe('txpool endpoint', () => { const logger: Logger = fakeLogger; const tx = new Transaction({ module: 'token', command: 'transfer', params: Buffer.alloc(20), fee: BigInt(100000), nonce: BigInt(0), senderPublicKey: Buffer.alloc(ED25519_PUBLIC_KEY_LENGTH), signatures: [Buffer.alloc(ED25519_SIGNATURE_LENGTH)], }); const chainID = Buffer.alloc(0); const events = [ { data: utils.getRandomBytes(32), index: 0, module: 'token', topics: [Buffer.from([0])], name: 'Token Event Name', height: 12, }, ]; const eventsJson = events.map(e => new Event(e).toJSON()); let endpoint: TxpoolEndpoint; let broadcaster: Broadcaster; let pool: TransactionPool; let abi: ABI; let chain: Chain; const senderPublicKey = utils.getRandomBytes(ED25519_PUBLIC_KEY_LENGTH); const senderLisk32Address = cryptoAddress.getLisk32AddressFromPublicKey(senderPublicKey); const transactionAttributes: TransactionAttrs[] = [ { module: 'module0', command: 'command0', senderPublicKey: utils.getRandomBytes(ED25519_PUBLIC_KEY_LENGTH), nonce: BigInt(88), fee: BigInt(23), params: Buffer.from('params0'), signatures: [utils.getRandomBytes(ED25519_SIGNATURE_LENGTH)], }, { module: 'module1', command: 'command1', senderPublicKey, nonce: BigInt(12), fee: BigInt(34), params: Buffer.from('params1'), signatures: [utils.getRandomBytes(ED25519_SIGNATURE_LENGTH)], }, { module: 'module2', command: 'command2', senderPublicKey: utils.getRandomBytes(ED25519_PUBLIC_KEY_LENGTH), nonce: BigInt(12), fee: BigInt(34), params: Buffer.from('params2'), signatures: [utils.getRandomBytes(ED25519_SIGNATURE_LENGTH)], }, ]; const transactionsFromPool = transactionAttributes.map( transaction => new Transaction(transaction), ); beforeEach(() => { broadcaster = { enqueueTransactionId: jest.fn() } as never; pool = { contains: jest.fn().mockReturnValue(false), add: jest.fn().mockResolvedValue({}), getAll: jest.fn().mockReturnValue(transactionsFromPool), } as never; abi = { verifyTransaction: jest.fn().mockResolvedValue({ result: TransactionVerifyResult.OK }), executeTransaction: jest.fn(), } as never; chain = { lastBlock: { header: { toObject: jest.fn(), }, transactions: [], assets: { getAll: jest.fn(), }, }, } as never; endpoint = new TxpoolEndpoint({ abi, broadcaster, pool, chain, }); }); describe('postTransaction', () => { describe('when request data is invalid', () => { it('should reject with validation error', async () => { await expect( endpoint.postTransaction({ logger, params: { invalid: 'schema', }, chainID, }), ).rejects.toThrow(LiskValidationError); }); it('should reject with error when transaction bytes is invalid', async () => { await expect( endpoint.postTransaction({ logger, params: { transaction: 'xxxx', }, chainID, }), ).rejects.toThrow(); }); }); describe('when verify transaction fails', () => { it('should throw when transaction is invalid', async () => { (abi.verifyTransaction as jest.Mock).mockResolvedValue({ result: TransactionVerifyResult.INVALID, }); await expect( endpoint.postTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), }, chainID, }), ).rejects.toThrow(InvalidTransactionError); }); }); describe('when transaction pool already contains the transaction', () => { it('should return the transaction id', async () => { (pool.contains as jest.Mock).mockReturnValue(true); await expect( endpoint.postTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), }, chainID, }), ).resolves.toEqual({ transactionId: tx.id.toString('hex'), }); }); }); describe('when failed to add to the transaction', () => { it('should throw when transaction is invalid', async () => { (pool.add as jest.Mock).mockResolvedValue({ error: new Error('invalid tx'), }); await expect( endpoint.postTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), }, chainID, }), ).rejects.toThrow(InvalidTransactionError); }); }); describe('when successfully to add to the transaction pool', () => { it('should return the transaction id', async () => { await expect( endpoint.postTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), }, chainID, }), ).resolves.toEqual({ transactionId: tx.id.toString('hex'), }); expect(broadcaster.enqueueTransactionId).toHaveBeenCalledWith(tx.id); }); }); }); describe('getTransactionsFromPool', () => { it('should return all transactions in the pool in JSON format, when no address is provided', async () => { const transactions = await endpoint.getTransactionsFromPool({ logger, params: {}, chainID, }); expect(transactions).toHaveLength(transactionsFromPool.length); expect(transactions[0].id).toBe(transactionsFromPool[0].id.toString('hex')); }); it('should return only transactions sent from the provided address, when address is provided', async () => { const transactions = await endpoint.getTransactionsFromPool({ logger, params: { address: senderLisk32Address }, chainID, }); expect(transactions).toHaveLength(1); expect(transactions[0].id).toBe(transactionsFromPool[1].id.toString('hex')); }); it('should return no transactions, when provided address does not correspond to any transaction in the pool', async () => { const transactions = await endpoint.getTransactionsFromPool({ logger, params: { address: 'lskw95gtvf3fpjm5y49hrc4fuhoy4n7dtp75adgx5' }, chainID, }); expect(transactions).toHaveLength(0); }); }); describe('dryRunTransaction', () => { describe('when request data is invalid', () => { it('should reject with validation error', async () => { await expect( endpoint.dryRunTransaction({ logger, params: { invalid: 'schema', }, chainID, }), ).rejects.toThrow("must have required property 'transaction'"); }); it('should reject with error when transaction bytes is invalid', async () => { await expect( endpoint.dryRunTransaction({ logger, params: { transaction: 'xxxx', }, chainID, }), ).rejects.toThrow(); }); it('should reject with error when skipVerify is not boolean', async () => { await expect( endpoint.dryRunTransaction({ logger, params: { transaction: 'xxxx', skipVerify: 'test', }, chainID, }), ).rejects.toThrow("'.skipVerify' should be of type 'boolean'"); }); }); describe('when verify transaction fails', () => { it('should return false with empty events array', async () => { (abi.verifyTransaction as jest.Mock).mockResolvedValue({ result: TransactionVerifyResult.INVALID, }); await expect( endpoint.dryRunTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), }, chainID, }), ).resolves.toEqual({ result: TransactionVerifyResult.INVALID, events: [], errorMessage: undefined, }); }); }); describe('when execute transaction returns INVALID', () => { it('should return false with corresponding events', async () => { (abi.executeTransaction as jest.Mock).mockResolvedValue({ result: TransactionExecutionResult.INVALID, events, }); await expect( endpoint.dryRunTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), }, chainID, }), ).resolves.toEqual({ result: TransactionVerifyResult.INVALID, events: eventsJson, }); }); }); describe('when execute transaction returns FAIL', () => { it('should return false with corresponding events', async () => { (abi.executeTransaction as jest.Mock).mockResolvedValue({ result: TransactionExecutionResult.FAIL, events, }); await expect( endpoint.dryRunTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), }, chainID, }), ).resolves.toEqual({ result: TransactionExecutionResult.FAIL, events: eventsJson, }); }); }); describe('when strict is false', () => { it('should call verifyTransaction with onlyCommand true', async () => { (abi.executeTransaction as jest.Mock).mockResolvedValue({ result: TransactionExecutionResult.OK, events, }); await endpoint.dryRunTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), }, chainID, }); expect(abi.verifyTransaction).toHaveBeenCalledWith({ contextID: expect.anything(), transaction: expect.anything(), onlyCommand: true, }); }); }); describe('when strict is true', () => { it('should call verifyTransaction with onlyCommand false', async () => { (abi.executeTransaction as jest.Mock).mockResolvedValue({ result: TransactionExecutionResult.OK, events, }); await endpoint.dryRunTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), strict: true, }, chainID, }); expect(abi.verifyTransaction).toHaveBeenCalledWith({ contextID: expect.anything(), transaction: expect.anything(), onlyCommand: false, }); }); }); it('should not verify transaction when skipVerify', async () => { (abi.verifyTransaction as jest.Mock).mockResolvedValue({ result: TransactionVerifyResult.OK, }); (abi.executeTransaction as jest.Mock).mockResolvedValue({ result: TransactionExecutionResult.OK, events, }); await expect( endpoint.dryRunTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), skipVerify: true, }, chainID, }), ).toResolve(); expect(abi.verifyTransaction).toHaveBeenCalledTimes(0); }); describe('when both verification is success & execution returns OK', () => { it('should return true with corresponding events', async () => { (abi.executeTransaction as jest.Mock).mockResolvedValue({ result: TransactionExecutionResult.OK, events, }); await expect( endpoint.dryRunTransaction({ logger, params: { transaction: tx.getBytes().toString('hex'), }, chainID, }), ).resolves.toEqual({ result: StateMachine.VerifyStatus.OK, events: eventsJson, }); }); }); }); }); ```
/content/code_sandbox/framework/test/unit/engine/endpoint/txpool.spec.ts
xml
2016-02-01T21:45:35
2024-08-15T19:16:48
lisk-sdk
LiskArchive/lisk-sdk
2,721
2,973
```xml import { makeResetStyles, mergeClasses } from '@griffel/react'; import { tokens } from '@fluentui/react-theme'; import type { SlotClassNames } from '@fluentui/react-utilities'; import { createCustomFocusIndicatorStyle } from '@fluentui/react-tabster'; import type { ToastContainerSlots, ToastContainerState } from './ToastContainer.types'; export const toastContainerClassNames: SlotClassNames<ToastContainerSlots> = { root: 'fui-ToastContainer', timer: 'fui-ToastContainer__timer', }; const useRootBaseClassName = makeResetStyles({ boxSizing: 'border-box', marginTop: '16px', pointerEvents: 'all', borderRadius: tokens.borderRadiusMedium, ...createCustomFocusIndicatorStyle({ outline: `${tokens.strokeWidthThick} solid ${tokens.colorStrokeFocus2}`, }), }); /** * Apply styling to the ToastContainer slots based on the state */ export const useToastContainerStyles_unstable = (state: ToastContainerState): ToastContainerState => { 'use no memo'; const rootBaseClassName = useRootBaseClassName(); state.root.className = mergeClasses(toastContainerClassNames.root, rootBaseClassName, state.root.className); return state; }; ```
/content/code_sandbox/packages/react-components/react-toast/library/src/components/ToastContainer/useToastContainerStyles.styles.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
269
```xml import React from 'react'; import { Icon } from '@rsuite/icons'; import { useCustom, useClassNames } from '../hooks'; import InputGroup from '../../InputGroup'; import CloseButton from '../CloseButton'; import Loader from '../../Loader'; interface PickerIndicatorProps { loading?: boolean; caretAs?: React.ElementType | null; onClose?: (event: React.MouseEvent<HTMLElement>) => void; showCleanButton?: boolean; disabled?: boolean; as?: React.ElementType; } const PickerIndicator = ({ loading, caretAs, onClose, showCleanButton, as: Component = InputGroup.Addon, disabled }: PickerIndicatorProps) => { const { locale } = useCustom(); const { prefix } = useClassNames('picker'); const addon = () => { if (loading) { return <Loader className={prefix('loader')} data-testid="spinner" />; } if (showCleanButton && !disabled) { return ( <CloseButton className={prefix('clean')} tabIndex={-1} locale={{ closeLabel: locale?.clear }} onClick={onClose} /> ); } return caretAs && <Icon as={caretAs} className={prefix('caret-icon')} />; }; const props = Component === InputGroup.Addon ? { disabled } : undefined; return <Component {...props}>{addon()}</Component>; }; export default PickerIndicator; ```
/content/code_sandbox/src/internals/Picker/PickerIndicator.tsx
xml
2016-06-06T02:27:46
2024-08-16T16:41:54
rsuite
rsuite/rsuite
8,263
305
```xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="path_to_url" package="co.mobiwise.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ToolbarMenuItemActivity" /> </application> </manifest> ```
/content/code_sandbox/sample/src/main/AndroidManifest.xml
xml
2016-01-30T13:08:17
2024-07-10T06:26:08
MaterialIntroView
iammert/MaterialIntroView
2,433
172
```xml import { buildSchema, GraphQLFieldResolver, GraphQLList, GraphQLObjectType, GraphQLSchema, GraphQLString, parse, } from 'graphql'; import { expectJSON } from '../../__testUtils__/expectJSON.js'; import { execute, executeSync } from '../execute.js'; describe('Execute: Accepts any iterable as list value', () => { function complete(rootValue: unknown) { return executeSync({ schema: buildSchema('type Query { listField: [String] }'), document: parse('{ listField }'), rootValue, }); } it('Accepts a Set as a List value', () => { const listField = new Set(['apple', 'banana', 'apple', 'coconut']); expect(complete({ listField })).toEqual({ data: { listField: ['apple', 'banana', 'coconut'] }, }); }); it('Accepts an Generator function as a List value', () => { function* listField() { yield 'one'; yield 2; yield true; } expect(complete({ listField })).toEqual({ data: { listField: ['one', '2', 'true'] }, }); }); it('Accepts function arguments as a List value', () => { function getArgs(..._args: ReadonlyArray<string>) { return arguments; } const listField = getArgs('one', 'two'); expect(complete({ listField })).toEqual({ data: { listField: ['one', 'two'] }, }); }); it('Does not accept (Iterable) String-literal as a List value', () => { const listField = 'Singular'; expectJSON(complete({ listField })).toDeepEqual({ data: { listField: null }, errors: [ { message: 'Expected Iterable, but did not find one for field "Query.listField".', locations: [{ line: 1, column: 3 }], path: ['listField'], }, ], }); }); }); describe('Execute: Accepts async iterables as list value', () => { function complete(rootValue: unknown, as: string = '[String]') { return execute({ schema: buildSchema(`type Query { listField: ${as} }`), document: parse('{ listField }'), rootValue, }); } function completeObjectList(resolve: GraphQLFieldResolver<{ index: number }, unknown>) { const schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { listField: { resolve: async function* listField() { yield await Promise.resolve({ index: 0 }); yield await Promise.resolve({ index: 1 }); yield await Promise.resolve({ index: 2 }); }, type: new GraphQLList( new GraphQLObjectType({ name: 'ObjectWrapper', fields: { index: { type: GraphQLString, resolve, }, }, }), ), }, }, }), }); return execute({ schema, document: parse('{ listField { index } }'), }); } it('Accepts an AsyncGenerator function as a List value', async () => { async function* listField() { yield await Promise.resolve('two'); yield await Promise.resolve(4); yield await Promise.resolve(false); } expectJSON(await complete({ listField })).toDeepEqual({ data: { listField: ['two', '4', 'false'] }, }); }); it('Handles an AsyncGenerator function that throws', async () => { async function* listField() { yield await Promise.resolve('two'); yield await Promise.resolve(4); throw new Error('bad'); } expectJSON(await complete({ listField })).toDeepEqual({ data: { listField: ['two', '4', null] }, errors: [ { message: 'bad', locations: [{ line: 1, column: 3 }], path: ['listField', 2], }, ], }); }); it('Handles an AsyncGenerator function where an intermediate value triggers an error', async () => { async function* listField() { yield await Promise.resolve('two'); yield await Promise.resolve({}); yield await Promise.resolve(4); } expectJSON(await complete({ listField })).toDeepEqual({ data: { listField: ['two', null, '4'] }, errors: [ { message: 'String cannot represent value: {}', locations: [{ line: 1, column: 3 }], path: ['listField', 1], }, ], }); }); it('Handles errors from `completeValue` in AsyncIterables', async () => { async function* listField() { yield await Promise.resolve('two'); yield await Promise.resolve({}); } expectJSON(await complete({ listField })).toDeepEqual({ data: { listField: ['two', null] }, errors: [ { message: 'String cannot represent value: {}', locations: [{ line: 1, column: 3 }], path: ['listField', 1], }, ], }); }); it('Handles promises from `completeValue` in AsyncIterables', async () => { expectJSON(await completeObjectList(({ index }) => Promise.resolve(index))).toDeepEqual({ data: { listField: [{ index: '0' }, { index: '1' }, { index: '2' }] }, }); }); it('Handles rejected promises from `completeValue` in AsyncIterables', async () => { expectJSON( await completeObjectList(({ index }) => { if (index === 2) { return Promise.reject(new Error('bad')); } return Promise.resolve(index); }), ).toDeepEqual({ data: { listField: [{ index: '0' }, { index: '1' }, { index: null }] }, errors: [ { message: 'bad', locations: [{ line: 1, column: 15 }], path: ['listField', 2, 'index'], }, ], }); }); it('Handles nulls yielded by async generator', async () => { async function* listField() { yield await Promise.resolve(1); yield await Promise.resolve(null); yield await Promise.resolve(2); } const errors = [ { message: 'Cannot return null for non-nullable field Query.listField.', locations: [{ line: 1, column: 3 }], path: ['listField', 1], }, ]; expect(await complete({ listField }, '[Int]')).toEqual({ data: { listField: [1, null, 2] }, }); expect(await complete({ listField }, '[Int]!')).toEqual({ data: { listField: [1, null, 2] }, }); expectJSON(await complete({ listField }, '[Int!]')).toDeepEqual({ data: { listField: null }, errors, }); expectJSON(await complete({ listField }, '[Int!]!')).toDeepEqual({ data: null, errors, }); }); }); describe('Execute: Handles list nullability', () => { async function complete(args: { listField: unknown; as: string }) { const { listField, as } = args; const schema = buildSchema(`type Query { listField: ${as} }`); const document = parse('{ listField }'); const result = await executeQuery(listField); // Promise<Array<T>> === Array<T> expectJSON(await executeQuery(promisify(listField))).toDeepEqual(result); if (Array.isArray(listField)) { const listOfPromises = listField.map(promisify); // Array<Promise<T>> === Array<T> expectJSON(await executeQuery(listOfPromises)).toDeepEqual(result); // Promise<Array<Promise<T>>> === Array<T> expectJSON(await executeQuery(promisify(listOfPromises))).toDeepEqual(result); } return result; function executeQuery(listValue: unknown) { return execute({ schema, document, rootValue: { listField: listValue } }); } function promisify(value: unknown): Promise<unknown> { return value instanceof Error ? Promise.reject(value) : Promise.resolve(value); } } it('Contains values', async () => { const listField = [1, 2]; expect(await complete({ listField, as: '[Int]' })).toEqual({ data: { listField: [1, 2] }, }); expect(await complete({ listField, as: '[Int]!' })).toEqual({ data: { listField: [1, 2] }, }); expect(await complete({ listField, as: '[Int!]' })).toEqual({ data: { listField: [1, 2] }, }); expect(await complete({ listField, as: '[Int!]!' })).toEqual({ data: { listField: [1, 2] }, }); }); it('Contains null', async () => { const listField = [1, null, 2]; const errors = [ { message: 'Cannot return null for non-nullable field Query.listField.', locations: [{ line: 1, column: 3 }], path: ['listField', 1], }, ]; expect(await complete({ listField, as: '[Int]' })).toEqual({ data: { listField: [1, null, 2] }, }); expect(await complete({ listField, as: '[Int]!' })).toEqual({ data: { listField: [1, null, 2] }, }); expectJSON(await complete({ listField, as: '[Int!]' })).toDeepEqual({ data: { listField: null }, errors, }); expectJSON(await complete({ listField, as: '[Int!]!' })).toDeepEqual({ data: null, errors, }); }); it('Returns null', async () => { const listField = null; const errors = [ { message: 'Cannot return null for non-nullable field Query.listField.', locations: [{ line: 1, column: 3 }], path: ['listField'], }, ]; expect(await complete({ listField, as: '[Int]' })).toEqual({ data: { listField: null }, }); expectJSON(await complete({ listField, as: '[Int]!' })).toDeepEqual({ data: null, errors, }); expect(await complete({ listField, as: '[Int!]' })).toEqual({ data: { listField: null }, }); expectJSON(await complete({ listField, as: '[Int!]!' })).toDeepEqual({ data: null, errors, }); }); it('Contains error', async () => { const listField = [1, new Error('bad'), 2]; const errors = [ { message: 'bad', locations: [{ line: 1, column: 3 }], path: ['listField', 1], }, ]; expectJSON(await complete({ listField, as: '[Int]' })).toDeepEqual({ data: { listField: [1, null, 2] }, errors, }); expectJSON(await complete({ listField, as: '[Int]!' })).toDeepEqual({ data: { listField: [1, null, 2] }, errors, }); expectJSON(await complete({ listField, as: '[Int!]' })).toDeepEqual({ data: { listField: null }, errors, }); expectJSON(await complete({ listField, as: '[Int!]!' })).toDeepEqual({ data: null, errors, }); }); it('Results in error', async () => { const listField = new Error('bad'); const errors = [ { message: 'bad', locations: [{ line: 1, column: 3 }], path: ['listField'], }, ]; expectJSON(await complete({ listField, as: '[Int]' })).toDeepEqual({ data: { listField: null }, errors, }); expectJSON(await complete({ listField, as: '[Int]!' })).toDeepEqual({ data: null, errors, }); expectJSON(await complete({ listField, as: '[Int!]' })).toDeepEqual({ data: { listField: null }, errors, }); expectJSON(await complete({ listField, as: '[Int!]!' })).toDeepEqual({ data: null, errors, }); }); }); ```
/content/code_sandbox/packages/executor/src/execution/__tests__/lists-test.ts
xml
2016-03-22T00:14:38
2024-08-16T02:02:06
graphql-tools
ardatan/graphql-tools
5,331
2,776
```xml <Project> <Import Project="..\Directory.Build.props" /> <PropertyGroup> <SkipMicrosoftCodeAnalysisCSharpPinning>true</SkipMicrosoftCodeAnalysisCSharpPinning> </PropertyGroup> </Project> ```
/content/code_sandbox/src/Compatibility/GenAPI/Directory.Build.props
xml
2016-07-22T21:26:02
2024-08-16T17:23:58
sdk
dotnet/sdk
2,627
48
```xml import cn from "classnames"; import React, { FunctionComponent } from "react"; import { withStyles } from "coral-ui/hocs"; import styles from "./BrandMark.css"; interface Props { className?: string; classes: typeof styles; size?: "md" | "lg"; fill?: string; } const BrandMark: FunctionComponent<Props> = ({ className, classes, size, fill, ...rest }) => ( <svg {...rest} className={cn(classes.base, className, { [classes.md]: size === "md", [classes.lg]: size === "lg", })} id="Layer_1" data-name="Layer 1" xmlns="path_to_url" viewBox="0 0 520.96 540.83" > <path fill={fill} d="M510.27,352.74a17.5,17.5,0,0,0-22.93,9.3A235.18,235.18,0,0,1,287.92,505.19V463a66.65,66.65,0,0,1,3.22-6.65c10.93-19.65,31.34-30.85,55-43.83,26.9-14.77,57.38-31.51,76-64.65a17.5,17.5,0,1,0-30.51-17.14c-13.72,24.41-37.33,37.38-62.33,51.11-14.16,7.78-28.59,15.71-41.34,25.91V382.59c0-36,23.82-56.49,54-82.46,18.33-15.79,37.29-32.11,52.27-53.74C411.77,221,420.32,193,420.32,160.7a17.5,17.5,0,0,0-35,0c0,35.62-13.1,59.79-31.43,80.24-17.9-24.71-30.34-56.66-30.34-80.24a17.5,17.5,0,0,0-35,0c0,32.53,15.93,73.46,39.93,104.75-3.11,2.72-6.26,5.43-9.43,8.16-17.77,15.31-35.87,30.91-48.63,50.41-12.77-19.5-30.86-35.1-48.64-50.41-3.17-2.73-6.32-5.44-9.42-8.16,24-31.29,39.92-72.22,39.92-104.75a17.5,17.5,0,0,0-35,0c0,23.58-12.44,55.54-30.34,80.24-18.33-20.45-31.43-44.62-31.43-80.24a17.5,17.5,0,0,0-35,0c0,32.26,8.56,60.29,26.16,85.69,15,21.63,33.94,37.95,52.27,53.74,30.16,26,54,46.48,54,82.46v25.19c-12.77-10.22-27.21-18.16-41.38-25.94-25-13.73-48.62-26.7-62.33-51.11a17.5,17.5,0,1,0-30.51,17.14c18.61,33.14,49.09,49.88,76,64.65,23.63,13,44,24.18,55,43.83a70.43,70.43,0,0,1,3.26,6.72v42.12A235.34,235.34,0,0,1,104,104a235.56,235.56,0,0,1,383.39,74.84,17.5,17.5,0,1,0,32.23-13.64,270.22,270.22,0,1,0,0,210.53A17.5,17.5,0,0,0,510.27,352.74Z" /> </svg> ); BrandMark.defaultProps = { size: "md", fill: "#f77160", }; export default withStyles(styles)(BrandMark); ```
/content/code_sandbox/client/src/core/client/ui/components/v2/Brand/BrandMark.tsx
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
1,092
```xml import onetime from 'onetime'; import features from '../feature-manager.js'; import {linkifiedURLClass, shortenLink} from '../github-helpers/dom-formatters.js'; import observe from '../helpers/selector-observer.js'; /* This feature is currently so broad that it's not de-inited via signal, it's just run once for all pageloads #5889 */ function init(): void { observe(`.comment-body a[href]:not(.${linkifiedURLClass})`, shortenLink); } void features.add(import.meta.url, { init: onetime(init), }); /* ## Test URLs path_to_url path_to_url */ ```
/content/code_sandbox/source/features/shorten-links.tsx
xml
2016-02-15T16:45:02
2024-08-16T18:39:26
refined-github
refined-github/refined-github
24,013
135
```xml // luma.gl // utils import './utils/fill-array.spec'; // Note that we do two test runs on luma.gl, with and without headless-gl // This file imports tests that should run *with* headless-gl included import './adapter/helpers/parse-shader-compiler-log.spec'; import './adapter/helpers/get-shader-layout.spec'; import './adapter/helpers/webgl-topology-utils.spec'; // Device pixels // import './context/device-pixels.spec'; // state-tracker import './context/state-tracker/deep-array-equal.spec'; import './context/state-tracker/set-parameters.spec'; import './context/state-tracker/webgl-state-tracker.spec'; import './context/state-tracker/context-state.spec'; // ADAPTER import './adapter/webgl-device.spec'; import './adapter/webgl-canvas-context.spec'; // Resources, WebGL-specific APIs import './adapter/resources/webgl-buffer.spec'; import './adapter/resources/webgl-vertex-array.spec'; import './adapter/resources/webgl-transform-feedback.spec'; ```
/content/code_sandbox/modules/webgl/test/index.ts
xml
2016-01-25T09:41:59
2024-08-16T10:03:05
luma.gl
visgl/luma.gl
2,280
211
```xml import addItem from './addItem'; describe('addItem()', () => { it('adds item to empty array', () => { const item = 'item to add'; const result = addItem([], item); expect(result).toStrictEqual([item]); }); it('appends item to ends of array', () => { const array = ['item 1', 'item 2', 'item 3']; const item = 'item to add'; const result = addItem(array, item); expect(result).toStrictEqual([...array, item]); }); }); ```
/content/code_sandbox/packages/utils/addItem.test.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
119
```xml /* * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. */ import {t} from 'translation'; import operationsMonitoring from './images/operationsMonitoring.png'; export function operationsMonitoringDashboardTemplate() { return { name: 'operationsMonitoring', img: operationsMonitoring, disabled: (definitions: unknown[]) => definitions.length < 2, config: [ { position: {x: 0, y: 0}, dimensions: {height: 3, width: 4}, report: { name: t('dashboard.templates.completedProcesses'), data: { view: {entity: 'processInstance', properties: ['frequency']}, groupBy: {type: 'none', value: null}, visualization: 'number', filter: [ { appliedTo: ['all'], data: null, filterLevel: 'instance', type: 'completedInstancesOnly', }, ], }, }, type: 'optimize_report', }, { position: {x: 4, y: 0}, dimensions: {height: 3, width: 5}, report: { name: t('dashboard.templates.longRunningProcesses'), data: { view: {entity: 'processInstance', properties: ['frequency']}, groupBy: {type: 'none', value: null}, distributedBy: {type: 'none', value: null}, visualization: 'number', filter: [ { appliedTo: ['all'], data: null, filterLevel: 'instance', type: 'runningInstancesOnly', }, { appliedTo: ['all'], data: {value: 1, unit: 'days', operator: '>', includeNull: false}, filterLevel: 'instance', type: 'processInstanceDuration', }, ], }, }, type: 'optimize_report', }, { position: {x: 9, y: 0}, dimensions: {height: 3, width: 4}, report: { name: t('dashboard.templates.activeIncidents'), data: { view: {entity: 'incident', properties: ['frequency']}, groupBy: {type: 'none', value: null}, visualization: 'number', filter: [ { appliedTo: ['all'], data: null, filterLevel: 'instance', type: 'includesOpenIncident', }, ], }, }, type: 'optimize_report', }, { position: {x: 13, y: 0}, dimensions: {height: 3, width: 5}, report: { name: t('dashboard.templates.activeIncidentsByProcess'), data: { view: {entity: 'processInstance', properties: ['frequency']}, groupBy: {type: 'none', value: null}, distributedBy: {type: 'process', value: null}, visualization: 'pie', filter: [ { appliedTo: ['all'], data: null, filterLevel: 'instance', type: 'includesOpenIncident', }, ], }, }, type: 'optimize_report', }, { position: {x: 0, y: 3}, dimensions: {height: 5, width: 9}, report: { name: t('dashboard.templates.processSnapshot'), data: { view: {entity: 'flowNode', properties: ['frequency', 'duration']}, groupBy: {type: 'flowNodes', value: null}, distributedBy: {type: 'none', value: null}, visualization: 'barLine', filter: [ { appliedTo: ['all'], data: null, filterLevel: 'view', type: 'runningFlowNodesOnly', }, ], configuration: { measureVisualizations: {frequency: 'bar', duration: 'line'}, showInstanceCount: true, stackedBar: true, }, }, }, type: 'optimize_report', }, { position: {x: 9, y: 3}, dimensions: {height: 5, width: 9}, report: { name: t('dashboard.templates.incidentSnapshot'), data: { view: {entity: 'incident', properties: ['frequency', 'duration']}, groupBy: {type: 'flowNodes', value: null}, distributedBy: {type: 'none', value: null}, visualization: 'barLine', filter: [ { appliedTo: ['all'], data: null, filterLevel: 'instance', type: 'includesOpenIncident', }, { appliedTo: ['all'], data: null, filterLevel: 'view', type: 'includesOpenIncident', }, ], configuration: { measureVisualizations: {frequency: 'bar', duration: 'line'}, showInstanceCount: true, }, }, }, type: 'optimize_report', }, { position: {x: 0, y: 8}, dimensions: {height: 5, width: 9}, report: { name: t('dashboard.templates.processHistory'), data: { view: {entity: 'processInstance', properties: ['frequency', 'duration']}, groupBy: {type: 'startDate', value: {unit: 'week'}}, distributedBy: {type: 'process', value: null}, visualization: 'barLine', filter: [ { appliedTo: ['all'], data: null, filterLevel: 'instance', type: 'completedInstancesOnly', }, ], configuration: { measureVisualizations: {frequency: 'bar', duration: 'line'}, stackedBar: true, }, }, }, type: 'optimize_report', }, { position: {x: 9, y: 8}, dimensions: {height: 5, width: 9}, report: { name: t('dashboard.templates.incidentHistory'), data: { view: {entity: 'processInstance', properties: ['frequency', 'duration']}, groupBy: {type: 'startDate', value: {unit: 'week'}}, distributedBy: {type: 'process', value: null}, visualization: 'barLine', filter: [ { appliedTo: ['all'], data: null, filterLevel: 'instance', type: 'includesResolvedIncident', }, ], configuration: { measureVisualizations: {frequency: 'bar', duration: 'line'}, stackedBar: true, aggregationTypes: [ {type: 'avg', value: null}, {type: 'max', value: null}, ], }, }, }, type: 'optimize_report', }, { position: {x: 0, y: 13}, dimensions: {height: 5, width: 18}, report: { name: t('dashboard.templates.durationSLI'), data: { view: {entity: 'processInstance', properties: ['duration']}, groupBy: {type: 'startDate', value: {unit: 'week'}}, distributedBy: {type: 'process', value: null}, visualization: 'line', configuration: { aggregationTypes: [{type: 'max', value: null}], targetValue: { active: true, isKpi: true, durationChart: {unit: 'hours', isBelow: true, value: '4'}, }, }, }, }, type: 'optimize_report', }, ], }; } ```
/content/code_sandbox/optimize/client/src/modules/components/TemplateModal/templates/dashboard/operationsMonitoringDashboardTemplate.ts
xml
2016-03-20T03:38:04
2024-08-16T19:59:58
camunda
camunda/camunda
3,172
1,686
```xml <?xml version="1.0" encoding="UTF-8"?> <definitions xmlns="path_to_url" xmlns:xsi="path_to_url" xmlns:xsd="path_to_url" xmlns:activiti="path_to_url" xmlns:bpmndi="path_to_url" xmlns:omgdc="path_to_url" xmlns:omgdi="path_to_url" typeLanguage="path_to_url" expressionLanguage="path_to_url" targetNamespace="path_to_url"> <process id="childProcess" name="Child Process" isExecutable="true"> <startEvent id="startevent1" name="Start"></startEvent> <userTask id="usertask1" name="User Task"></userTask> <endEvent id="endevent1" name="End"></endEvent> <sequenceFlow id="flow2" sourceRef="usertask1" targetRef="endevent1"></sequenceFlow> <sequenceFlow id="flow3" sourceRef="startevent1" targetRef="usertask1"></sequenceFlow> </process> </definitions> ```
/content/code_sandbox/modules/flowable-engine/src/test/resources/org/flowable/engine/test/bpmn/subprocess/SubProcessTest.testSameDeploymentCallActivity_childProcess.bpmn20.xml
xml
2016-10-13T07:21:43
2024-08-16T15:23:14
flowable-engine
flowable/flowable-engine
7,715
231
```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;netstandard1.0</TargetFrameworks> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netstandard2.0|AnyCPU'"> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|netstandard2.0|AnyCPU'"> </PropertyGroup> </Project> ```
/content/code_sandbox/Xamarin.Forms.Platform/Xamarin.Forms.Platform.csproj
xml
2016-03-18T15:52:03
2024-08-16T16:25:43
Xamarin.Forms
xamarin/Xamarin.Forms
5,637
110
```xml import { getGlobalClassNames, FontWeights } from '../../Styling'; import { CONTEXTUAL_MENU_ITEM_HEIGHT } from './ContextualMenu.cnstyles'; import type { IContextualMenuStyleProps, IContextualMenuStyles } from './ContextualMenu.types'; const GlobalClassNames = { root: 'ms-ContextualMenu', container: 'ms-ContextualMenu-container', list: 'ms-ContextualMenu-list', header: 'ms-ContextualMenu-header', title: 'ms-ContextualMenu-title', isopen: 'is-open', }; export const getStyles = (props: IContextualMenuStyleProps): IContextualMenuStyles => { const { className, theme } = props; const classNames = getGlobalClassNames(GlobalClassNames, theme); const { fonts, semanticColors, effects } = theme; return { root: [ theme.fonts.medium, classNames.root, classNames.isopen, { backgroundColor: semanticColors.menuBackground, minWidth: '180px', }, className, ], container: [ classNames.container, { selectors: { ':focus': { outline: 0 }, }, }, ], list: [ classNames.list, classNames.isopen, { listStyleType: 'none', margin: '0', padding: '0', }, ], header: [ classNames.header, fonts.small, { fontWeight: FontWeights.semibold, color: semanticColors.menuHeader, background: 'none', backgroundColor: 'transparent', border: 'none', height: CONTEXTUAL_MENU_ITEM_HEIGHT, lineHeight: CONTEXTUAL_MENU_ITEM_HEIGHT, cursor: 'default', padding: '0px 6px', userSelect: 'none', textAlign: 'left', }, ], title: [ classNames.title, { fontSize: fonts.mediumPlus.fontSize, paddingRight: '14px', paddingLeft: '14px', paddingBottom: '5px', paddingTop: '5px', backgroundColor: semanticColors.menuItemBackgroundPressed, }, ], subComponentStyles: { callout: { root: { boxShadow: effects.elevation8, }, }, menuItem: {}, }, }; }; ```
/content/code_sandbox/packages/react/src/components/ContextualMenu/ContextualMenu.styles.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
493
```xml <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="path_to_url"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>10.0.20506</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{4A456D45-712E-360E-F403-0A700166B831}</ProjectGuid> <OutputType>Library</OutputType> <AssemblyName>Assembly-CSharp-Editor</AssemblyName> <FileAlignment>512</FileAlignment> <ProjectTypeGuids>{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkProfile>Unity Full v3.5</TargetFrameworkProfile> <CompilerResponseFile></CompilerResponseFile> <UnityProjectType>Editor:5</UnityProjectType> <UnityBuildTarget>StandaloneWindows64:19</UnityBuildTarget> <UnityVersion>2017.3.0f3</UnityVersion> <RootNamespace></RootNamespace> <LangVersion>4</LangVersion> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>false</Optimize> <OutputPath>Temp\UnityVS_bin\Debug\</OutputPath> <IntermediateOutputPath>Temp\UnityVS_obj\Debug\</IntermediateOutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <DefineConstants>DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_2_OR_NEWER;UNITY_2017_3_OR_NEWER;UNITY_2017_3_0;UNITY_2017_3;UNITY_2017;PLATFORM_ARCH_64;UNITY_64;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_GENERICS;ENABLE_PVR_GI;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_GRID;ENABLE_TILEMAP;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_HUB;ENABLE_EDITOR_HUB_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_DIRECTOR_TEXTURE;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_NATIVE_ARRAY;ENABLE_SPRITE_MASKING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_VIDEO;ENABLE_RMGUI;ENABLE_PACKMAN;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_STYLE_SHEETS;ENABLE_LOCALIZATION;PLATFORM_STANDALONE_WIN;PLATFORM_STANDALONE;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_VR;ENABLE_AR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_2_0_SUBSET;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_NATIVE_ARRAY_CHECKS;UNITY_TEAM_LICENSE;ENABLE_VSTU;UNITY_PRO_LICENSE</DefineConstants> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>false</Optimize> <OutputPath>Temp\UnityVS_bin\Release\</OutputPath> <IntermediateOutputPath>Temp\UnityVS_obj\Release\</IntermediateOutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <DefineConstants>TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_2_OR_NEWER;UNITY_2017_3_OR_NEWER;UNITY_2017_3_0;UNITY_2017_3;UNITY_2017;PLATFORM_ARCH_64;UNITY_64;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_GENERICS;ENABLE_PVR_GI;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_SPRITERENDERER_FLIPPING;ENABLE_SPRITES;ENABLE_GRID;ENABLE_TILEMAP;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_HUB;ENABLE_EDITOR_HUB_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_DIRECTOR_TEXTURE;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_NATIVE_ARRAY;ENABLE_SPRITE_MASKING;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_PLAYMODE_TESTS_RUNNER;ENABLE_VIDEO;ENABLE_RMGUI;ENABLE_PACKMAN;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_STYLE_SHEETS;ENABLE_LOCALIZATION;PLATFORM_STANDALONE_WIN;PLATFORM_STANDALONE;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_EVENT_QUEUE;ENABLE_CLUSTERINPUT;ENABLE_VR;ENABLE_AR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_2_0_SUBSET;ENABLE_PROFILER;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN;ENABLE_NATIVE_ARRAY_CHECKS;UNITY_TEAM_LICENSE;ENABLE_VSTU;UNITY_PRO_LICENSE</DefineConstants> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> <Reference Include="mscorlib" /> <Reference Include="System" /> <Reference Include="System.XML" /> <Reference Include="System.Core" /> <Reference Include="Boo.Lang" /> <Reference Include="UnityScript.Lang" /> <Reference Include="System.Runtime.Serialization" /> <Reference Include="System.Xml.Linq" /> <Reference Include="UnityEditor"> <HintPath>Library\UnityAssemblies\UnityEditor.dll</HintPath> </Reference> <Reference Include="UnityEngine"> <HintPath>Library\UnityAssemblies\UnityEngine.dll</HintPath> </Reference> <Reference Include="UnityEngine.CoreModule"> <HintPath>Library\UnityAssemblies\UnityEngine.CoreModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.AccessibilityModule"> <HintPath>Library\UnityAssemblies\UnityEngine.AccessibilityModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.ParticleSystemModule"> <HintPath>Library\UnityAssemblies\UnityEngine.ParticleSystemModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.PhysicsModule"> <HintPath>Library\UnityAssemblies\UnityEngine.PhysicsModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.VehiclesModule"> <HintPath>Library\UnityAssemblies\UnityEngine.VehiclesModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.ClothModule"> <HintPath>Library\UnityAssemblies\UnityEngine.ClothModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.AIModule"> <HintPath>Library\UnityAssemblies\UnityEngine.AIModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.AnimationModule"> <HintPath>Library\UnityAssemblies\UnityEngine.AnimationModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.TextRenderingModule"> <HintPath>Library\UnityAssemblies\UnityEngine.TextRenderingModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UIModule"> <HintPath>Library\UnityAssemblies\UnityEngine.UIModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.TerrainPhysicsModule"> <HintPath>Library\UnityAssemblies\UnityEngine.TerrainPhysicsModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.IMGUIModule"> <HintPath>Library\UnityAssemblies\UnityEngine.IMGUIModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.ClusterInputModule"> <HintPath>Library\UnityAssemblies\UnityEngine.ClusterInputModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.ClusterRendererModule"> <HintPath>Library\UnityAssemblies\UnityEngine.ClusterRendererModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UNETModule"> <HintPath>Library\UnityAssemblies\UnityEngine.UNETModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.DirectorModule"> <HintPath>Library\UnityAssemblies\UnityEngine.DirectorModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UnityAnalyticsModule"> <HintPath>Library\UnityAssemblies\UnityEngine.UnityAnalyticsModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.PerformanceReportingModule"> <HintPath>Library\UnityAssemblies\UnityEngine.PerformanceReportingModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UnityConnectModule"> <HintPath>Library\UnityAssemblies\UnityEngine.UnityConnectModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.WebModule"> <HintPath>Library\UnityAssemblies\UnityEngine.WebModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.ARModule"> <HintPath>Library\UnityAssemblies\UnityEngine.ARModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.VRModule"> <HintPath>Library\UnityAssemblies\UnityEngine.VRModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UIElementsModule"> <HintPath>Library\UnityAssemblies\UnityEngine.UIElementsModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.StyleSheetsModule"> <HintPath>Library\UnityAssemblies\UnityEngine.StyleSheetsModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.AssetBundleModule"> <HintPath>Library\UnityAssemblies\UnityEngine.AssetBundleModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.AudioModule"> <HintPath>Library\UnityAssemblies\UnityEngine.AudioModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.CrashReportingModule"> <HintPath>Library\UnityAssemblies\UnityEngine.CrashReportingModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.GameCenterModule"> <HintPath>Library\UnityAssemblies\UnityEngine.GameCenterModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.GridModule"> <HintPath>Library\UnityAssemblies\UnityEngine.GridModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.ImageConversionModule"> <HintPath>Library\UnityAssemblies\UnityEngine.ImageConversionModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.InputModule"> <HintPath>Library\UnityAssemblies\UnityEngine.InputModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.JSONSerializeModule"> <HintPath>Library\UnityAssemblies\UnityEngine.JSONSerializeModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.ParticlesLegacyModule"> <HintPath>Library\UnityAssemblies\UnityEngine.ParticlesLegacyModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.Physics2DModule"> <HintPath>Library\UnityAssemblies\UnityEngine.Physics2DModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.ScreenCaptureModule"> <HintPath>Library\UnityAssemblies\UnityEngine.ScreenCaptureModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.SharedInternalsModule"> <HintPath>Library\UnityAssemblies\UnityEngine.SharedInternalsModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.SpriteMaskModule"> <HintPath>Library\UnityAssemblies\UnityEngine.SpriteMaskModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.SpriteShapeModule"> <HintPath>Library\UnityAssemblies\UnityEngine.SpriteShapeModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.TerrainModule"> <HintPath>Library\UnityAssemblies\UnityEngine.TerrainModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.TilemapModule"> <HintPath>Library\UnityAssemblies\UnityEngine.TilemapModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UnityWebRequestModule"> <HintPath>Library\UnityAssemblies\UnityEngine.UnityWebRequestModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UnityWebRequestAudioModule"> <HintPath>Library\UnityAssemblies\UnityEngine.UnityWebRequestAudioModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UnityWebRequestTextureModule"> <HintPath>Library\UnityAssemblies\UnityEngine.UnityWebRequestTextureModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UnityWebRequestWWWModule"> <HintPath>Library\UnityAssemblies\UnityEngine.UnityWebRequestWWWModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.VideoModule"> <HintPath>Library\UnityAssemblies\UnityEngine.VideoModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.WindModule"> <HintPath>Library\UnityAssemblies\UnityEngine.WindModule.dll</HintPath> </Reference> <Reference Include="UnityEngine.UI"> <HintPath>Library\UnityAssemblies\UnityEngine.UI.dll</HintPath> </Reference> <Reference Include="UnityEditor.UI"> <HintPath>Library\UnityAssemblies\UnityEditor.UI.dll</HintPath> </Reference> <Reference Include="UnityEngine.Networking"> <HintPath>Library\UnityAssemblies\UnityEngine.Networking.dll</HintPath> </Reference> <Reference Include="UnityEditor.Networking"> <HintPath>Library\UnityAssemblies\UnityEditor.Networking.dll</HintPath> </Reference> <Reference Include="UnityEditor.TestRunner"> <HintPath>Library\UnityAssemblies\UnityEditor.TestRunner.dll</HintPath> </Reference> <Reference Include="UnityEngine.TestRunner"> <HintPath>Library\UnityAssemblies\UnityEngine.TestRunner.dll</HintPath> </Reference> <Reference Include="nunit.framework"> <HintPath>Library\UnityAssemblies\nunit.framework.dll</HintPath> </Reference> <Reference Include="UnityEngine.Timeline"> <HintPath>Library\UnityAssemblies\UnityEngine.Timeline.dll</HintPath> </Reference> <Reference Include="UnityEditor.Timeline"> <HintPath>Library\UnityAssemblies\UnityEditor.Timeline.dll</HintPath> </Reference> <Reference Include="UnityEditor.TreeEditor"> <HintPath>Library\UnityAssemblies\UnityEditor.TreeEditor.dll</HintPath> </Reference> <Reference Include="UnityEngine.UIAutomation"> <HintPath>Library\UnityAssemblies\UnityEngine.UIAutomation.dll</HintPath> </Reference> <Reference Include="UnityEditor.UIAutomation"> <HintPath>Library\UnityAssemblies\UnityEditor.UIAutomation.dll</HintPath> </Reference> <Reference Include="UnityEditor.GoogleAudioSpatializer"> <HintPath>Library\UnityAssemblies\UnityEditor.GoogleAudioSpatializer.dll</HintPath> </Reference> <Reference Include="UnityEngine.GoogleAudioSpatializer"> <HintPath>Library\UnityAssemblies\UnityEngine.GoogleAudioSpatializer.dll</HintPath> </Reference> <Reference Include="UnityEditor.HoloLens"> <HintPath>Library\UnityAssemblies\UnityEditor.HoloLens.dll</HintPath> </Reference> <Reference Include="UnityEngine.HoloLens"> <HintPath>Library\UnityAssemblies\UnityEngine.HoloLens.dll</HintPath> </Reference> <Reference Include="UnityEditor.SpatialTracking"> <HintPath>Library\UnityAssemblies\UnityEditor.SpatialTracking.dll</HintPath> </Reference> <Reference Include="UnityEngine.SpatialTracking"> <HintPath>Library\UnityAssemblies\UnityEngine.SpatialTracking.dll</HintPath> </Reference> <Reference Include="UnityEditor.VR"> <HintPath>Library\UnityAssemblies\UnityEditor.VR.dll</HintPath> </Reference> <Reference Include="UnityEditor.Graphs"> <HintPath>Library\UnityAssemblies\UnityEditor.Graphs.dll</HintPath> </Reference> <Reference Include="UnityEditor.Android.Extensions"> <HintPath>Library\UnityAssemblies\UnityEditor.Android.Extensions.dll</HintPath> </Reference> <Reference Include="UnityEditor.WindowsStandalone.Extensions"> <HintPath>Library\UnityAssemblies\UnityEditor.WindowsStandalone.Extensions.dll</HintPath> </Reference> <Reference Include="SyntaxTree.VisualStudio.Unity.Bridge"> <HintPath>Library\UnityAssemblies\SyntaxTree.VisualStudio.Unity.Bridge.dll</HintPath> </Reference> <Reference Include="UnityEngine.Advertisements"> <HintPath>Library\UnityAssemblies\UnityEngine.Advertisements.dll</HintPath> </Reference> <Reference Include="UnityEditor.Advertisements"> <HintPath>Library\UnityAssemblies\UnityEditor.Advertisements.dll</HintPath> </Reference> <Reference Include="UnityEngine.Analytics"> <HintPath>Library\UnityAssemblies\UnityEngine.Analytics.dll</HintPath> </Reference> <Reference Include="UnityEditor.Analytics"> <HintPath>Library\UnityAssemblies\UnityEditor.Analytics.dll</HintPath> </Reference> <Reference Include="UnityEngine.Purchasing"> <HintPath>Library\UnityAssemblies\UnityEngine.Purchasing.dll</HintPath> </Reference> <Reference Include="UnityEditor.Purchasing"> <HintPath>Library\UnityAssemblies\UnityEditor.Purchasing.dll</HintPath> </Reference> <Reference Include="UnityEngine.StandardEvents"> <HintPath>Library\UnityAssemblies\UnityEngine.StandardEvents.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> <ProjectReference Include="demo.csproj"> <Project>{2B763333-372A-EE8E-6012-0757A5E05DD9}</Project> <Name>demo</Name> </ProjectReference> </ItemGroup> <ItemGroup> <Compile Include="Assets\AssetBundleManager\Editor\AssetbundlesMenuItems.cs" /> <Compile Include="Assets\AssetBundleManager\Editor\BuildScript.cs" /> <Compile Include="Assets\AssetBundleManager\Editor\ExecuteInternalMono.cs" /> <Compile Include="Assets\AssetBundleManager\Editor\LaunchAssetBundleServer.cs" /> <Compile Include="Assets\AssetBundleSample\Scripts\Editor\BuildResources.cs" /> </ItemGroup> <ItemGroup> <None Include="Assets\link.xml" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Target Name="GenerateTargetFrameworkMonikerAttribute" /> </Project> ```
/content/code_sandbox/HotUpdate/UnityTechnologiesAssetbundleDemo/demo/demo.Editor.csproj
xml
2016-04-25T14:37:08
2024-08-16T09:19:37
Unity3DTraining
XINCGer/Unity3DTraining
7,368
4,662
```xml import * as React from 'react'; import type { ForwardRefComponent } from '@fluentui/react-utilities'; import { useInteractionTagPrimary_unstable } from './useInteractionTagPrimary'; import { renderInteractionTagPrimary_unstable } from './renderInteractionTagPrimary'; import { useInteractionTagPrimaryStyles_unstable } from './useInteractionTagPrimaryStyles.styles'; import type { InteractionTagPrimaryProps } from './InteractionTagPrimary.types'; import { useTagAvatarContextValues_unstable } from '../../utils'; import { useCustomStyleHook_unstable } from '@fluentui/react-shared-contexts'; /** * InteractionTagPrimary component - used as the first child of the `InteractionTag` component. * Provides visual attributes such as media, icon, primary and secondary text, as well as the ability to attach a primary action. */ export const InteractionTagPrimary: ForwardRefComponent<InteractionTagPrimaryProps> = React.forwardRef((props, ref) => { const state = useInteractionTagPrimary_unstable(props, ref); useInteractionTagPrimaryStyles_unstable(state); useCustomStyleHook_unstable('useInteractionTagPrimaryStyles_unstable')(state); return renderInteractionTagPrimary_unstable(state, useTagAvatarContextValues_unstable(state)); }); InteractionTagPrimary.displayName = 'InteractionTagPrimary'; ```
/content/code_sandbox/packages/react-components/react-tags/library/src/components/InteractionTagPrimary/InteractionTagPrimary.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
269
```xml import { assert } from "chai"; import * as L from "../src/index"; import * as Lf from "../src/fantasy-land"; import { just, nothing, isJust, Maybe } from "./utils"; describe("Fantasy Land", () => { it("has all functions", () => { for (const key of Object.keys(L)) { const elm = (L as any)[key]; // Check all non-anonymous functions if (typeof elm === "function" && elm.name === key) { assert.isTrue(key in Lf); } } }); describe("setoid", () => { it("has Fantasy Land method", () => { assert.isTrue( L.list(0, 1, 2, 3, 4)["fantasy-land/equals"](L.list(0, 1, 2, 3, 4)) ); }); }); describe("monoid", () => { it("has fantasy land empty", () => { L.list(0, 1, 2)["fantasy-land/empty"](); }); it("has fantasy land concat", () => { L.list(0, 1, 2)["fantasy-land/concat"](L.list(3, 4)); }); }); describe("monad", () => { it("has map method", () => { const n = 50; const l = L.range(0, n); const mapped = l["fantasy-land/map"](m => m * m); for (let i = 0; i < n; ++i) { assert.strictEqual(L.nth(i, mapped), i * i); } }); it("has ap method", () => { const l = L.list(1, 2, 3)["fantasy-land/ap"]( L.list((n: number) => n + 2, (n: number) => 2 * n, (n: number) => n * n) ); assert.isTrue(L.equals(l, L.list(3, 4, 5, 2, 4, 6, 1, 4, 9))); }); it("has chain method", () => { const l = L.list(1, 2, 3); const l2 = l["fantasy-land/chain"](n => L.list(n, 2 * n, n * n)); assert.isTrue(L.equals(l2, L.list(1, 2, 1, 2, 4, 4, 3, 6, 9))); }); }); describe("traversable", () => { it("has reduce method", () => { const l = L.list(0, 1, 2, 3, 4, 5); const result = l["fantasy-land/reduce"]((arr, i) => (arr.push(i), arr), < number[] >[]); assert.deepEqual(result, [0, 1, 2, 3, 4, 5]); }); it("has traverse method", () => { const safeDiv = (n: number) => (d: number) => d === 0 ? nothing : just(n / d); const r = L.list(2, 4, 5)["fantasy-land/traverse"](Maybe, safeDiv(10)); assert.isTrue(isJust(r) && L.equals(r.val, L.list(5, 2.5, 2))); }); }); describe("filterable", () => { it("has Fantasy Land method", () => { assert.strictEqual( L.list(0, 1, 2, 3, 4, 5)["fantasy-land/filter"](n => n % 2 === 0) .length, 3 ); }); }); }); ```
/content/code_sandbox/test/fantasy-land.ts
xml
2016-09-14T07:41:40
2024-08-03T07:00:49
list
funkia/list
1,647
850
```xml import cn from "classnames"; import React, { FunctionComponent } from "react"; import { withStyles } from "coral-ui/hocs"; import styles from "./Divider.css"; interface Props { className?: string; classes: typeof styles; } const Divider: FunctionComponent<Props> = ({ className, classes, ...rest }) => ( <hr {...rest} className={cn(classes.root, className)} /> ); export default withStyles(styles)(Divider); ```
/content/code_sandbox/client/src/core/client/ui/components/v2/Dropdown/Divider.tsx
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
93
```xml import { Component } from '@angular/core'; import { ITreeOptions } from 'angular-tree-component'; @Component({ selector: 'app-templates-demo', templateUrl: './templates-demo.component.html', styleUrls: ['./templates-demo.component.scss'] }) export class TemplatesDemoComponent { nodes1 = [ { title: 'root1', className: 'root1Class' }, { title: 'root2', className: 'root2Class', hasChildren: true } ]; nodes2 = [ { title: 'root1', className: 'root1Class' }, { title: 'root2', className: 'root2Class', children: [ { title: 'child1', className: 'child1Class' } ] } ]; options1: ITreeOptions = { getChildren: () => new Promise((resolve, reject) => { }) }; options0: ITreeOptions = { displayField: 'title', nodeClass: (node) => `${node.data.title}Class` }; } ```
/content/code_sandbox/projects/docs-app/src/app/fundamentals/templates/templates-demo/templates-demo.component.ts
xml
2016-03-10T21:29:15
2024-08-15T07:07:30
angular-tree-component
CirclonGroup/angular-tree-component
1,093
237
```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType Condition="'$(Configuration)'=='Release'">WinExe</OutputType> <OutputType Condition="'$(Configuration)'=='Debug'">Exe</OutputType> <TargetFramework>net6.0</TargetFramework> </PropertyGroup> <ItemGroup Condition="exists('..\SkiaSharpSample.UWP')"> <EmbeddedResource Include="..\SkiaSharpSample.UWP\Package.appxmanifest" LogicalName="Package.appxmanifest" /> <Content Include="..\SkiaSharpSample.UWP\Assets\StoreLogo.scale-400.png" Link="Assets\StoreLogo.png" /> <Content Include="Assets\Fonts\uno-fluentui-assets.ttf" /> </ItemGroup> <ItemGroup> <UpToDateCheckInput Include="..\SkiaSharpSample.Shared\**\*.xaml" /> </ItemGroup> <ItemGroup> <!-- Note that for WebAssembly version 1.1.1 of the console logger required --> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" /> <PackageReference Include="Microsoft.Extensions.Logging.Filter" Version="1.1.1" /> <PackageReference Include="Uno.UI.Adapter.Microsoft.Extensions.Logging" Version="4.0.8" /> <PackageReference Include="Uno.Core.Extensions.Logging.Singleton" Version="4.0.1" /> <PackageReference Include="Uno.Core.Extensions.Logging" Version="4.0.1" /> <PackageReference Include="Uno.UI.Skia.Gtk" Version="4.0.8" /> <PackageReference Include="Uno.UI.RemoteControl" Version="4.0.8" Condition="'$(Configuration)'=='Debug'" /> </ItemGroup> <Import Project="..\SkiaSharpSample.Shared\SkiaSharpSample.Shared.projitems" Label="Shared" /> <ItemGroup> <ProjectReference Include="..\..\..\..\binding\SkiaSharp\SkiaSharp.csproj" /> <ProjectReference Include="..\..\..\..\binding\HarfBuzzSharp\HarfBuzzSharp.csproj" /> <ProjectReference Include="..\..\..\..\binding\SkiaSharp.SceneGraph\SkiaSharp.SceneGraph.csproj" /> <ProjectReference Include="..\..\..\..\binding\SkiaSharp.Skottie\SkiaSharp.Skottie.csproj" /> <ProjectReference Include="..\..\..\..\source\SkiaSharp.Views.Uno\SkiaSharp.Views.Uno.Skia\SkiaSharp.Views.Uno.Skia.csproj" /> <ProjectReference Include="..\..\..\..\source\SkiaSharp.HarfBuzz\SkiaSharp.HarfBuzz\SkiaSharp.HarfBuzz.csproj" /> </ItemGroup> <ItemGroup> <Content Include="..\..\..\..\output\native\windows\x64\*.dll" Visible="False" /> <Content Include="..\..\..\..\output\native\linux\x64\*.so" Visible="False" /> <Content Include="..\..\..\..\output\native\osx\*.dylib" Visible="False" /> <Content Include="..\..\Shared\Media\content-font.ttf"> <Link>Assets\Media\content-font.ttf</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup> <Import Project="..\..\..\..\output\SkiaSharp.Views.Uno\nuget\build\netstandard2.0\SkiaSharp.Views.Uno.targets" Condition="Exists('..\..\..\..\output\SkiaSharp.Views.Uno\nuget\build\netstandard2.0\SkiaSharp.Views.Uno.targets')" /> </Project> ```
/content/code_sandbox/samples/Gallery/Uno/SkiaSharpSample.Gtk/SkiaSharpSample.Gtk.csproj
xml
2016-02-22T17:54:43
2024-08-16T17:53:42
SkiaSharp
mono/SkiaSharp
4,347
814
```xml export * from './components/RadioGroup/index'; ```
/content/code_sandbox/packages/react-components/react-radio/library/src/RadioGroup.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
11
```xml import { parseValue } from 'graphql'; import { extractVariables } from '../src/extractVariables.js'; describe('can extract variables', () => { test('return unmodified input value if no variables present', () => { const str = `{ outer: [{ inner: [1, 2]}, {inner: [3, 4] }] }`; const inputValue = parseValue(str, { noLocation: true }); const { inputValue: newInputValue, variablePaths } = extractVariables(inputValue); const expectedInputValue = parseValue(`{ outer: [{ inner: [1, 2]}, { inner: [3, 4] }] }`, { noLocation: true, }); expect(newInputValue).toEqual(expectedInputValue); expect(variablePaths).toEqual({}); }); test('return replaced input value and record with variable names and values', () => { const str = `{ outer: [{ inner: [$test1, 2]}, {inner: [3, $test4] }] }`; const inputValue = parseValue(str, { noLocation: true }); const { inputValue: newInputValue, variablePaths } = extractVariables(inputValue); const expectedInputValue = parseValue( `{ outer: [{ inner: [null, 2]}, { inner: [3, null] }] }`, { noLocation: true, }, ); expect(newInputValue).toEqual(expectedInputValue); expect(variablePaths).toEqual({ test1: ['outer', 0, 'inner', 0], test4: ['outer', 1, 'inner', 1], }); }); }); ```
/content/code_sandbox/packages/stitching-directives/tests/extractVariables.test.ts
xml
2016-03-22T00:14:38
2024-08-16T02:02:06
graphql-tools
ardatan/graphql-tools
5,331
350
```xml export { partitionBreadcrumbItems } from './partitionBreadcrumbItems'; export type { PartitionBreadcrumbItems, PartitionBreadcrumbItemsOptions } from './partitionBreadcrumbItems'; export { truncateBreadcrumbLongName, truncateBreadcrumLongTooltip, isTruncatableBreadcrumbContent, } from './truncateBreadcrumb'; ```
/content/code_sandbox/packages/react-components/react-breadcrumb/library/src/utils/index.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
61
```xml /* * @license Apache-2.0 * * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ // TypeScript Version: 4.1 /** * Evaluates the probability mass function (PMF) for a negative binomial distribution. * * @param x - input value * @returns evaluated PMF */ type Unary = ( x: number ) => number; /** * Interface for the probability mass function (PMF) of a negative binomial distribution. */ interface PMF { /** * Evaluates the probability mass function (PMF) for a negative binomial distribution with number of successes until experiment is stopped `r` and success probability `p`. * * ## Notes * * - If provided a `r` which is not a positive number, the function returns `NaN`. * - If `p < 0` or `p > 1`, the function returns `NaN`. * * @param x - input value * @param r - number of successes until experiment is stopped * @param p - success probability * @returns evaluated PMF * * @example * var y = pmf( 5.0, 20.0, 0.8 ); * // returns ~0.157 * * @example * var y = pmf( 21.0, 20.0, 0.5 ); * // returns ~0.06 * * @example * var y = pmf( 5.0, 10.0, 0.4 ); * // returns ~0.016 * * @example * var y = pmf( 0.0, 10.0, 0.9 ); * // returns ~0.349 * * @example * var y = pmf( 21.0, 15.5, 0.5 ); * // returns ~0.037 * * @example * var y = pmf( 5.0, 7.4, 0.4 ); * // returns ~0.051 * * @example * var y = pmf( 2.0, 0.0, 0.5 ); * // returns NaN * * @example * var y = pmf( 2.0, -2.0, 0.5 ); * // returns NaN * * @example * var y = pmf( 2.0, 20, -1.0 ); * // returns NaN * * @example * var y = pmf( 2.0, 20, 1.5 ); * // returns NaN * * @example * var y = pmf( NaN, 20.0, 0.5 ); * // returns NaN * * @example * var y = pmf( 0.0, NaN, 0.5 ); * // returns NaN * * @example * var y = pmf( 0.0, 20.0, NaN ); * // returns NaN */ ( x: number, r: number, p: number ): number; /** * Returns a function for evaluating the probability mass function (PMF) for a negative binomial distribution with number of successes until experiment is stopped `r` and success probability `p`. * * @param r - number of successes until experiment is stopped * @param p - success probability * @returns PMF * * @example * var mypmf = pmf.factory( 10, 0.5 ); * var y = mypmf( 3.0 ); * // returns ~0.027 * * y = mypmf( 5.0 ); * // returns ~0.061 */ factory( r: number, p: number ): Unary; } /** * Negative binomial distribution probability mass function (PMF). * * @param x - input value * @param r - number of successes until experiment is stopped * @param p - success probability * @returns evaluated PMF * * @example * var y = pmf( 5.0, 20.0, 0.8 ); * // returns ~0.157 * * y = pmf( 21.0, 20.0, 0.5 ); * // returns ~0.06 * * y = pmf( 5.0, 10.0, 0.4 ); * // returns ~0.016 * * y = pmf( 0.0, 10.0, 0.9 ); * // returns ~0.349 * * y = pmf( 21.0, 15.5, 0.5 ); * // returns ~0.037 * * y = pmf( 5.0, 7.4, 0.4 ); * // returns ~0.051 * * var mypmf = pmf.factory( 10, 0.5 ); * y = mypmf( 3.0 ); * // returns ~0.027 * * y = mypmf( 5.0 ); * // returns ~0.061 */ declare var pmf: PMF; // EXPORTS // export = pmf; ```
/content/code_sandbox/lib/node_modules/@stdlib/stats/base/dists/negative-binomial/pmf/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
1,230
```xml <?xml version="1.0" encoding="utf-8"?> <!-- ~ ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <resources> <string name="icon_content_description">Dialogikon</string> </resources> ```
/content/code_sandbox/lib/java/com/google/android/material/dialog/res/values-sv/strings.xml
xml
2016-12-05T16:11:29
2024-08-16T17:51:42
material-components-android
material-components/material-components-android
16,176
83
```xml <?xml version="1.0" encoding="UTF-8"?> <module external.linked.project.id="BannerExample" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4"> <component name="FacetManager"> <facet type="java-gradle" name="Java-Gradle"> <configuration> <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" /> <option name="BUILDABLE" value="false" /> </configuration> </facet> </component> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://$MODULE_DIR$"> <excludeFolder url="file://$MODULE_DIR$/.gradle" /> <excludeFolder url="file://$MODULE_DIR$/build" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> </component> </module> ```
/content/code_sandbox/BannerExample.iml
xml
2016-04-22T05:50:25
2024-08-15T03:35:23
banner
youth5201314/banner
12,833
249
```xml <!-- *********************************************************************************************** Xamarin.Android.Bindings.JavaDependencyVerification.targets This file contains MSBuild targets used to enable features using POM files to ensure that Java binding dependencies are satisfied. *********************************************************************************************** --> <Project xmlns="path_to_url"> <UsingTask TaskName="Xamarin.Android.Tasks.GetMicrosoftNuGetPackagesMap" AssemblyFile="Xamarin.Android.Build.Tasks.dll" /> <UsingTask TaskName="Xamarin.Android.Tasks.JavaDependencyVerification" AssemblyFile="Xamarin.Android.Build.Tasks.dll" /> <Target Name="_VerifyJavaDependencies" Condition=" '@(AndroidLibrary->Count())' != '0' " BeforeTargets="_CategorizeAndroidLibraries" DependsOnTargets="_MavenRestore"> <!-- Find the microsoft-package.json file for NuGet package hints. --> <GetMicrosoftNuGetPackagesMap MavenCacheDirectory="$(MavenCacheDirectory)"> <Output TaskParameter="ResolvedPackageMap" PropertyName="_ResolvedPackageMap" /> </GetMicrosoftNuGetPackagesMap> <!-- Use downloaded POM files to ensure all Java dependencies are met. --> <JavaDependencyVerification AndroidLibraries="@(AndroidLibrary)" AdditionalManifests="@(AndroidAdditionalJavaManifest)" PackageReferences="@(PackageReference)" ProjectReferences="@(ProjectReference)" IgnoredDependencies="@(AndroidIgnoredJavaDependency)" MicrosoftPackagesFile="$(_ResolvedPackageMap)" ProjectAssetsLockFile="$(ProjectAssetsFile)" /> </Target> </Project> ```
/content/code_sandbox/src/Xamarin.Android.Build.Tasks/MSBuild/Xamarin/Android/Xamarin.Android.Bindings.JavaDependencyVerification.targets
xml
2016-03-30T15:37:14
2024-08-16T19:22:13
android
dotnet/android
1,905
310
```xml import { useEffect, useRef } from 'react'; import { useLoading } from '@proton/hooks'; import { Api } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import { AmountAndCurrency, ChargeablePaymentParameters, ChargebeeIframeEvents, ChargebeeIframeHandles, ExistingPaymentMethod, PaymentVerificatorV5, SavedPaymentMethod, SavedPaymentMethodExternal, SavedPaymentMethodInternal, } from '../core'; import { SavedChargebeePaymentProcessor } from '../core/payment-processors/savedChargebeePayment'; import { PaymentProcessorHook, PaymentProcessorType } from './interface'; export interface Props { amountAndCurrency: AmountAndCurrency; savedMethod?: SavedPaymentMethodExternal | SavedPaymentMethodInternal | SavedPaymentMethod; onChargeable: (data: ChargeablePaymentParameters, paymentMethodId: ExistingPaymentMethod) => Promise<unknown>; onProcessPaymentToken?: (paymentMethodType: PaymentProcessorType) => void; onProcessPaymentTokenFailed?: (paymentMethodType: PaymentProcessorType) => void; } export interface Dependencies { verifyPayment: PaymentVerificatorV5; api: Api; handles: ChargebeeIframeHandles; events: ChargebeeIframeEvents; } export interface SavedChargebeeMethodProcessorHook extends PaymentProcessorHook { paymentProcessor?: SavedChargebeePaymentProcessor; } export const useSavedChargebeeMethod = ( { amountAndCurrency, savedMethod, onChargeable, onProcessPaymentToken, onProcessPaymentTokenFailed }: Props, { verifyPayment, api, handles, events }: Dependencies ): SavedChargebeeMethodProcessorHook => { const paymentProcessorRef = useRef<SavedChargebeePaymentProcessor>(); if (!paymentProcessorRef.current && savedMethod) { paymentProcessorRef.current = new SavedChargebeePaymentProcessor( verifyPayment, api, handles, events, amountAndCurrency, savedMethod, (chargeablePaymentParameters: ChargeablePaymentParameters) => onChargeable(chargeablePaymentParameters, savedMethod.ID) ); } const paymentProcessor = paymentProcessorRef.current; const [fetchingToken, withFetchingToken] = useLoading(); const [verifyingToken, withVerifyingToken] = useLoading(); const processingToken = fetchingToken || verifyingToken; useEffect(() => { return () => paymentProcessor?.destroy(); }, []); useEffect(() => { if (paymentProcessor) { paymentProcessor.amountAndCurrency = amountAndCurrency; paymentProcessor.reset(); } }, [amountAndCurrency]); useEffect(() => { if (paymentProcessor && savedMethod) { paymentProcessor.onTokenIsChargeable = (chargeablePaymentParameters: ChargeablePaymentParameters) => onChargeable(chargeablePaymentParameters, savedMethod.ID); paymentProcessor.updateSavedMethod(savedMethod); } }, [savedMethod, onChargeable]); const reset = () => paymentProcessor?.reset(); const fetchPaymentToken = async () => withFetchingToken(paymentProcessor?.fetchPaymentToken()); const verifyPaymentToken = async () => { const tokenPromise = paymentProcessor?.verifyPaymentToken(); if (!tokenPromise) { throw new Error('There is no saved method to verify'); } withVerifyingToken(tokenPromise).catch(noop); return tokenPromise; }; const processPaymentToken = async () => { onProcessPaymentToken?.('saved-chargebee'); if (!paymentProcessor?.fetchedPaymentToken) { await fetchPaymentToken(); } try { return await verifyPaymentToken(); } catch (error) { onProcessPaymentTokenFailed?.('saved-chargebee'); reset(); throw error; } }; return { fetchPaymentToken, fetchingToken, verifyPaymentToken, verifyingToken, processPaymentToken, processingToken, paymentProcessor, meta: { type: 'saved-chargebee', data: savedMethod, }, }; }; ```
/content/code_sandbox/packages/components/payments/react-extensions/useSavedChargebeeMethod.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
858
```xml <?xml version="1.0" encoding="UTF-8"?> <!-- path_to_url Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <ehcache xmlns:xsi="path_to_url" xsi:noNamespaceSchemaLocation="path_to_url" updateCheck="true" monitoring="autodetect" dynamicConfig="true" maxBytesLocalHeap="${assignment.metadata.cache.maxBytesLocalHeap}" > <defaultCache maxEntriesLocalHeap="0" eternal="true" /> </ehcache> ```
/content/code_sandbox/modules/assignment/src/main/resources/ehcache.xml
xml
2016-06-21T21:21:06
2024-08-06T13:29:36
wasabi
intuit/wasabi
1,133
127
```xml import { BaseEntity, Column, Entity, OneToMany, PrimaryColumn, } from "../../../../../../src" import { Setting } from "./Setting" @Entity() export class User extends BaseEntity { @PrimaryColumn() id: number @Column() name: string @OneToMany("Setting", "asset", { cascade: true }) settings: Setting[] constructor(id: number, name: string) { super() this.id = id this.name = name } } ```
/content/code_sandbox/test/functional/relations/multiple-primary-keys/multiple-primary-keys-one-to-many/entity/User.ts
xml
2016-02-29T07:41:14
2024-08-16T18:28:52
typeorm
typeorm/typeorm
33,875
110
```xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "path_to_url"> <mapper namespace="org.flowable.task.service.impl.persistence.entity.HistoricTaskLogEntryEntityImpl"> <!-- INSERT --> <insert id="insertHistoricTaskLogEntry" parameterType="org.flowable.task.service.impl.persistence.entity.HistoricTaskLogEntryEntityImpl"> insert into ${prefix}ACT_HI_TSK_LOG(TYPE_, TASK_ID_, EXECUTION_ID_, PROC_INST_ID_, PROC_DEF_ID_, SCOPE_ID_, SCOPE_DEFINITION_ID_, SUB_SCOPE_ID_, SCOPE_TYPE_, TENANT_ID_, TIME_STAMP_, USER_ID_, DATA_) values ( #{type, jdbcType=NVARCHAR}, #{taskId, jdbcType=NVARCHAR}, #{executionId, jdbcType=NVARCHAR}, #{processInstanceId, jdbcType=NVARCHAR}, #{processDefinitionId, jdbcType=NVARCHAR}, #{scopeId, jdbcType=NVARCHAR}, #{scopeDefinitionId, jdbcType=NVARCHAR}, #{subScopeId, jdbcType=NVARCHAR}, #{scopeType, jdbcType=NVARCHAR}, #{tenantId, jdbcType=NVARCHAR}, #{timeStamp, jdbcType=TIMESTAMP}, #{userId, jdbcType=NVARCHAR}, #{data, jdbcType=NVARCHAR} ) </insert> <insert id="bulkInsertHistoricTaskLogEntry" parameterType="java.util.List"> insert into ${prefix}ACT_HI_TSK_LOG(TYPE_, TASK_ID_, EXECUTION_ID_, PROC_INST_ID_, PROC_DEF_ID_, SCOPE_ID_, SCOPE_DEFINITION_ID_, SUB_SCOPE_ID_, SCOPE_TYPE_, TENANT_ID_, TIME_STAMP_, USER_ID_, DATA_) values <foreach collection="list" item="historicTaskLogEntry" index="index" separator=","> (#{historicTaskLogEntry.type, jdbcType=NVARCHAR}, #{historicTaskLogEntry.taskId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.executionId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.processInstanceId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.processDefinitionId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.scopeId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.scopeDefinitionId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.subScopeId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.scopeType, jdbcType=NVARCHAR}, #{historicTaskLogEntry.tenantId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.timeStamp, jdbcType=TIMESTAMP}, #{historicTaskLogEntry.userId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.data, jdbcType=NVARCHAR}) </foreach> </insert> <insert id="insertHistoricTaskLogEntry" databaseId="oracle" parameterType="org.flowable.task.service.impl.persistence.entity.HistoricTaskLogEntryEntityImpl"> insert into ${prefix}ACT_HI_TSK_LOG(ID_, TYPE_, TASK_ID_, EXECUTION_ID_, PROC_INST_ID_, PROC_DEF_ID_, SCOPE_ID_, SCOPE_DEFINITION_ID_, SUB_SCOPE_ID_, SCOPE_TYPE_, TENANT_ID_, TIME_STAMP_, USER_ID_, DATA_) values ( ${prefix}ACT_HI_TASK_EVT_LOG_SEQ.nextVal, #{type, jdbcType=NVARCHAR}, #{taskId, jdbcType=NVARCHAR}, #{executionId, jdbcType=NVARCHAR}, #{processInstanceId, jdbcType=NVARCHAR}, #{processDefinitionId, jdbcType=NVARCHAR}, #{scopeId, jdbcType=NVARCHAR}, #{scopeDefinitionId, jdbcType=NVARCHAR}, #{subScopeId, jdbcType=NVARCHAR}, #{scopeType, jdbcType=NVARCHAR}, #{tenantId, jdbcType=NVARCHAR}, #{timeStamp, jdbcType=TIMESTAMP}, #{userId, jdbcType=NVARCHAR}, #{data, jdbcType=NVARCHAR} ) </insert> <insert id="bulkInsertHistoricTaskLogEntry" databaseId="oracle" parameterType="java.util.List"> INSERT ALL <foreach collection="list" item="historicTaskLogEntry" index="index"> into ${prefix}ACT_HI_TSK_LOG(ID_, TYPE_, TASK_ID_, EXECUTION_ID_, PROC_INST_ID_, PROC_DEF_ID_, SCOPE_ID_, SCOPE_DEFINITION_ID_, SUB_SCOPE_ID_, SCOPE_TYPE_, TENANT_ID_, TIME_STAMP_, USER_ID_, DATA_) VALUES (${prefix}ACT_HI_TASK_EVT_LOG_SEQ.nextVal, #{historicTaskLogEntry.type, jdbcType=NVARCHAR}, #{historicTaskLogEntry.taskId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.executionId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.processInstanceId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.processDefinitionId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.scopeId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.scopeDefinitionId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.subScopeId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.scopeType, jdbcType=NVARCHAR}, #{historicTaskLogEntry.tenantId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.timeStamp, jdbcType=TIMESTAMP}, #{historicTaskLogEntry.userId, jdbcType=NVARCHAR}, #{historicTaskLogEntry.data, jdbcType=NVARCHAR}) </foreach> SELECT * FROM dual </insert> <!-- RESULTMAP --> <resultMap id="HistoricTaskLogEntryResultMap" type="org.flowable.task.service.impl.persistence.entity.HistoricTaskLogEntryEntityImpl"> <id property="logNumber" column="ID_" jdbcType="BIGINT" /> <result property="id" column="ID_" jdbcType="BIGINT" /> <result property="type" column="TYPE_" jdbcType="NVARCHAR"/> <result property="taskId" column="TASK_ID_" jdbcType="NVARCHAR"/> <result property="executionId" column="EXECUTION_ID_" jdbcType="NVARCHAR"/> <result property="processInstanceId" column="PROC_INST_ID_" jdbcType="NVARCHAR"/> <result property="processDefinitionId" column="PROC_DEF_ID_" jdbcType="NVARCHAR"/> <result property="scopeId" column="SCOPE_ID_" jdbcType="NVARCHAR"/> <result property="scopeDefinitionId" column="SCOPE_DEFINITION_ID_" jdbcType="NVARCHAR"/> <result property="subScopeId" column="SUB_SCOPE_ID_" jdbcType="NVARCHAR"/> <result property="scopeType" column="SCOPE_TYPE_" jdbcType="NVARCHAR"/> <result property="tenantId" column="TENANT_ID_" jdbcType="NVARCHAR"/> <result property="timeStamp" column="TIME_STAMP_" jdbcType="TIMESTAMP"/> <result property="userId" column="USER_ID_" jdbcType="NVARCHAR" /> <result property="data" column="DATA_" jdbcType="NVARCHAR"/> </resultMap> <!-- SELECTS --> <select id="selectHistoricTaskLogEntriesByQueryCriteria" parameterType="org.flowable.task.service.impl.HistoricTaskLogEntryQueryImpl" resultMap="HistoricTaskLogEntryResultMap"> <if test="needsPaging">${limitBefore}</if> SELECT RES.* <if test="needsPaging">${limitBetween}</if> <include refid="selectHistoricTaskLogEntriesByQueryCriteriaSql"/> ${orderBy} <if test="needsPaging">${limitAfter}</if> </select> <select id="selectHistoricTaskLogEntriesCountByQueryCriteria" parameterType="org.flowable.task.service.impl.HistoricTaskLogEntryQueryImpl" resultType="long"> select count(RES.ID_) <include refid="selectHistoricTaskLogEntriesByQueryCriteriaSql"/> </select> <select id="selectHistoricTaskLogEntriesByNativeQueryCriteria" parameterType="java.util.Map" resultMap="HistoricTaskLogEntryResultMap"> <include refid="org.flowable.common.engine.db.selectByNativeQuery"/> </select> <select id="selectHistoricTaskLogEntriesCountByNativeQueryCriteria" parameterType="java.util.Map" resultType="long"> ${sql} </select> <sql id="selectHistoricTaskLogEntriesByQueryCriteriaSql"> from ${prefix}ACT_HI_TSK_LOG RES <include refid="commonSelectHistoricTaskLogEntriesByQueryCriteriaSql"/> </sql> <sql id="commonSelectHistoricTaskLogEntriesByQueryCriteriaSql"> <where> <if test="taskId != null"> RES.TASK_ID_ = #{taskId, jdbcType=NVARCHAR} </if> <if test="type != null"> and RES.TYPE_ = #{type, jdbcType=NVARCHAR} </if> <if test="userId != null"> and RES.USER_ID_ = #{userId, jdbcType=NVARCHAR} </if> <if test="processInstanceId != null"> and RES.PROC_INST_ID_ = #{processInstanceId, jdbcType=NVARCHAR} </if> <if test="processDefinitionId != null"> and RES.PROC_DEF_ID_ = #{processDefinitionId, jdbcType=NVARCHAR} </if> <if test="scopeId != null"> and RES.SCOPE_ID_ = #{scopeId, jdbcType=NVARCHAR} </if> <if test="scopeDefinitionId != null"> and RES.SCOPE_DEFINITION_ID_ = #{scopeDefinitionId, jdbcType=NVARCHAR} </if> <if test="subScopeId != null"> and RES.SUB_SCOPE_ID_ = #{subScopeId, jdbcType=NVARCHAR} </if> <if test="scopeType != null"> and RES.SCOPE_TYPE_ = #{scopeType, jdbcType=NVARCHAR} </if> <if test="fromDate != null"> and RES.TIME_STAMP_ &gt;= #{fromDate, jdbcType=TIMESTAMP} </if> <if test="toDate != null"> and RES.TIME_STAMP_ &lt;= #{toDate, jdbcType=TIMESTAMP} </if> <if test="tenantId != null"> and RES.TENANT_ID_ = #{tenantId, jdbcType=NVARCHAR} </if> <if test="fromLogNumber != -1"> and RES.ID_ &gt;= #{fromLogNumber, jdbcType=BIGINT} </if> <if test="toLogNumber != -1"> and RES.ID_ &lt;= #{toLogNumber, jdbcType=BIGINT} </if> </where> </sql> <!-- DELETE --> <delete id="deleteHistoricTaskLogEntryByLogNumber" parameterType="long"> delete from ${prefix}ACT_HI_TSK_LOG where ID_ = #{logNumber, jdbcType=BIGINT} </delete> <delete id="deleteHistoricTaskLogEntriesByProcessDefinitionId" parameterType="string"> delete from ${prefix}ACT_HI_TSK_LOG where PROC_DEF_ID_ = #{processDefinitionId, jdbcType=NVARCHAR} </delete> <delete id="deleteHistoricTaskLogEntriesByScopeDefinitionId" parameterType="map"> delete from ${prefix}ACT_HI_TSK_LOG where SCOPE_DEFINITION_ID_ = #{scopeDefinitionId, jdbcType=NVARCHAR} AND SCOPE_TYPE_ = #{scopeType, jdbcType=NVARCHAR} </delete> <delete id="deleteHistoricTaskLogEntriesByTaskId" parameterType="string"> delete from ${prefix}ACT_HI_TSK_LOG where TASK_ID_ = #{taskId, jdbcType=NVARCHAR} </delete> <delete id="bulkDeleteHistoricTaskLogEntriesForTaskIds" parameterType="string"> delete from ${prefix}ACT_HI_TSK_LOG where <foreach item="listItem" index="listIndex" collection="collection"> <if test="listIndex &gt; 0"> or </if> TASK_ID_ in <foreach item="taskId" index="index" collection="listItem" open="(" separator="," close=")"> #{taskId, jdbcType=NVARCHAR} </foreach> </foreach> </delete> <delete id="bulkDeleteHistoricTaskLogEntriesForNonExistingProcessInstances" parameterType="java.util.Map"> delete <if test="_databaseId != 'postgres' and _databaseId != 'cockroachdb' and _databaseId != 'db2'" > TSKLOG </if> from ${prefix}ACT_HI_TSK_LOG TSKLOG where TSKLOG.PROC_INST_ID_ is not null and TSKLOG.PROC_INST_ID_ != '' and NOT EXISTS (select PROCINST.ID_ from ${prefix}ACT_HI_PROCINST PROCINST where TSKLOG.PROC_INST_ID_ = PROCINST.ID_) </delete> <delete id="bulkDeleteHistoricTaskLogEntriesForNonExistingProcessInstances" parameterType="java.util.Map" databaseId="oracle"> delete from ${prefix}ACT_HI_TSK_LOG TSKLOG where TSKLOG.PROC_INST_ID_ is not null and NOT EXISTS (select PROCINST.ID_ from ${prefix}ACT_HI_PROCINST PROCINST where TSKLOG.PROC_INST_ID_ = PROCINST.ID_) </delete> <delete id="bulkDeleteHistoricTaskLogEntriesForNonExistingProcessInstances" databaseId="h2" parameterType="java.util.Map"> delete from ${prefix}ACT_HI_TSK_LOG where PROC_INST_ID_ is not null and PROC_INST_ID_ != '' and PROC_INST_ID_ NOT IN (select PROCINST.ID_ from ${prefix}ACT_HI_PROCINST PROCINST) </delete> <delete id="bulkDeleteHistoricTaskLogEntriesForNonExistingCaseInstances" parameterType="java.util.Map"> delete <if test="_databaseId != 'postgres' and _databaseId != 'cockroachdb' and _databaseId != 'db2'"> TSKLOG </if> from ${prefix}ACT_HI_TSK_LOG TSKLOG where TSKLOG.SCOPE_ID_ is not null and TSKLOG.SCOPE_ID_ != '' and TSKLOG.SCOPE_TYPE_ = 'cmmn' and NOT EXISTS (select CASEINST.ID_ from ${prefix}ACT_CMMN_RU_CASE_INST CASEINST where TSKLOG.SCOPE_ID_ = CASEINST.ID_) </delete> <delete id="bulkDeleteHistoricTaskLogEntriesForNonExistingCaseInstances" parameterType="java.util.Map" databaseId="oracle"> delete from ${prefix}ACT_HI_TSK_LOG TSKLOG where TSKLOG.SCOPE_ID_ is not null and TSKLOG.SCOPE_TYPE_ = 'cmmn' and NOT EXISTS (select CASEINST.ID_ from ${prefix}ACT_CMMN_RU_CASE_INST CASEINST where TSKLOG.SCOPE_ID_ = CASEINST.ID_) </delete> <delete id="bulkDeleteHistoricTaskLogEntriesForNonExistingCaseInstances" databaseId="h2" parameterType="java.util.Map"> delete from ${prefix}ACT_HI_TSK_LOG where SCOPE_ID_ is not null and SCOPE_ID_ != '' and SCOPE_TYPE_ = 'cmmn' and SCOPE_ID_ NOT IN (select CASEINST.ID_ from ${prefix}ACT_CMMN_RU_CASE_INST CASEINST) </delete> </mapper> ```
/content/code_sandbox/modules/flowable-task-service/src/main/resources/org/flowable/task/service/db/mapping/entity/HistoricTaskLogEntry.xml
xml
2016-10-13T07:21:43
2024-08-16T15:23:14
flowable-engine
flowable/flowable-engine
7,715
3,413
```xml import type { MatcherFunction } from "expect"; import type { DocumentNode } from "graphql"; import type { OperationVariables } from "../../core/index.js"; import { ApolloClient } from "../../core/index.js"; import { canonicalStringify } from "../../cache/index.js"; import { getSuspenseCache } from "../../react/internal/index.js"; import type { CacheKey } from "../../react/internal/index.js"; export const toHaveSuspenseCacheEntryUsing: MatcherFunction< [ query: DocumentNode, options: { variables?: OperationVariables; queryKey?: string | number | any[]; }, ] > = function ( client, query, { variables, queryKey = [] } = Object.create(null) ) { if (!(client instanceof ApolloClient)) { throw new Error("Actual must be an instance of `ApolloClient`"); } const suspenseCache = getSuspenseCache(client); const cacheKey: CacheKey = [ query, canonicalStringify(variables), ...([] as any[]).concat(queryKey), ]; const queryRef = suspenseCache["queryRefs"].lookupArray(cacheKey)?.current; return { pass: !!queryRef, message: () => { return `Expected suspense cache ${ queryRef ? "not " : "" }to have cache entry using key`; }, }; }; ```
/content/code_sandbox/src/testing/matchers/toHaveSuspenseCacheEntryUsing.ts
xml
2016-02-26T20:25:00
2024-08-16T10:56:57
apollo-client
apollographql/apollo-client
19,304
288
```xml import { Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn, } from "../../../../src" import { TestChild } from "./TestChild" @Entity() export class TestParent { @OneToOne("TestChild", { nullable: true, eager: true, cascade: true, }) @JoinColumn() public child: TestChild @PrimaryGeneratedColumn("uuid") public uuid: string } ```
/content/code_sandbox/test/github-issues/5520/entity/TestParent.ts
xml
2016-02-29T07:41:14
2024-08-16T18:28:52
typeorm
typeorm/typeorm
33,875
93
```xml <vector xmlns:android="path_to_url" xmlns:tools="path_to_url" android:width="496dp" android:height="512dp" android:viewportWidth="496.0" android:viewportHeight="512.0" tools:keep="@drawable/fa_mizuni"> <path android:fillColor="#FFFFFFFF" android:pathData="M248,8C111,8 0,119.1 0,256c0,137 111,248 248,248s248,-111 248,-248C496,119.1 385,8 248,8zM168,359.9c-31.4,10.6 -58.8,27.3 -80,48.2L88,136c0,-22.1 17.9,-40 40,-40s40,17.9 40,40v223.9zM288,350c-12.9,-2 -26.2,-3.1 -39.8,-3.1 -13.8,0 -27.2,1.1 -40.2,3.1L208,136c0,-22.1 17.9,-40 40,-40s40,17.9 40,40v214zM408,407.7c-21.2,-20.8 -48.6,-37.4 -80,-48L328,136c0,-22.1 17.9,-40 40,-40s40,17.9 40,40v271.7z"/> </vector> ```
/content/code_sandbox/mobile/src/main/res/drawable/fa_mizuni.xml
xml
2016-10-24T13:23:25
2024-08-16T07:20:37
freeotp-android
freeotp/freeotp-android
1,387
345
```xml <?xml version="1.0" encoding="utf-8"?> <!-- ~ All Rights Reserved. --> <me.zhanghai.android.douya.ui.ForegroundRelativeLayout xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="@dimen/two_line_list_item_height" android:paddingLeft="@dimen/card_content_horizontal_margin" android:paddingRight="@dimen/card_content_horizontal_margin" android:paddingTop="@dimen/card_content_vertical_margin" android:paddingBottom="@dimen/card_content_vertical_margin" android:foreground="?selectableItemBackground"> <ImageView android:id="@+id/image" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginRight="16dp" android:scaleType="centerCrop" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/image" android:layout_alignParentTop="true" android:ellipsize="end" android:maxLines="3" android:textAppearance="@style/TextAppearance.AppCompat.Body1" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/image" android:layout_alignBottom="@id/image" android:layout_below="@id/text" android:layout_marginTop="8dp" android:orientation="horizontal"> <me.zhanghai.android.douya.ui.TimeTextView android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ellipsize="end" android:gravity="bottom" android:maxLines="1" android:textAppearance="@style/TextAppearance.AppCompat.Caption" /> <TextView android:id="@+id/time_action_space" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ellipsize="end" android:gravity="bottom" android:maxLines="1" android:text="@string/space" android:textAppearance="@style/TextAppearance.AppCompat.Caption" /> <TextView android:id="@+id/action" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ellipsize="end" android:gravity="bottom" android:maxLines="1" android:textAppearance="@style/TextAppearance.AppCompat.Caption" /> </LinearLayout> </me.zhanghai.android.douya.ui.ForegroundRelativeLayout> ```
/content/code_sandbox/app/src/main/res/layout/profile_broadcast_item.xml
xml
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
602
```xml import { BrowserWindow } from 'electron'; import checkDiskSpace from 'check-disk-space'; import prettysize from 'prettysize'; import { getDiskSpaceStatusChannel } from '../ipc/get-disk-space-status'; import { logger } from './logging'; import { DISK_SPACE_CHECK_DONT_BOTHER_ME_INTERVAL, DISK_SPACE_CHECK_LONG_INTERVAL, DISK_SPACE_CHECK_MEDIUM_INTERVAL, DISK_SPACE_CHECK_SHORT_INTERVAL, DISK_SPACE_RECOMMENDED_PERCENTAGE, DISK_SPACE_REQUIRED, DISK_SPACE_CHECK_TIMEOUT, DISK_SPACE_REQUIRED_MARGIN_PERCENTAGE, stateDirectoryPath, } from '../config'; import { CardanoNodeStates } from '../../common/types/cardano-node.types'; import { CardanoNode } from '../cardano/CardanoNode'; import type { CheckDiskSpaceResponse } from '../../common/types/no-disk-space.types'; const getDiskCheckReport = async ( path: string, timeout: number = DISK_SPACE_CHECK_TIMEOUT ): Promise<CheckDiskSpaceResponse> => { const initialReport: CheckDiskSpaceResponse = { isNotEnoughDiskSpace: false, diskSpaceRequired: '', diskSpaceMissing: '', diskSpaceRecommended: '', diskSpaceAvailable: '', hadNotEnoughSpaceLeft: false, diskSpaceAvailableRaw: 0, diskTotalSpaceRaw: 0, isError: false, }; // @ts-ignore ts-migrate(2740) FIXME: Type '{}' is missing the following properties from... Remove this comment to see the full error message return Promise.race([ // Disk space check promise new Promise((resolve) => { checkDiskSpace(path) .then(({ free, size }) => { logger.info('[DISK-SPACE-DEBUG] Disk space check completed', { free, size, }); resolve({ ...initialReport, diskSpaceAvailableRaw: free, diskSpaceAvailable: prettysize(free), diskTotalSpace: size, }); }) .catch((error) => { logger.error( '[DISK-SPACE-DEBUG] Error getting diskCheckReport', error ); resolve({ ...initialReport, isError: true }); }); }), // Timeout promise new Promise((resolve) => { setTimeout(() => { resolve({ ...initialReport, isError: true }); }, timeout); }), ]); }; export const handleDiskSpace = ( mainWindow: BrowserWindow, cardanoNode: CardanoNode ): ((...args: Array<any>) => any) => { let diskSpaceCheckInterval; let diskSpaceCheckIntervalLength = DISK_SPACE_CHECK_LONG_INTERVAL; // Default check interval let isNotEnoughDiskSpace = false; // Default check state const handleCheckDiskSpace = async ( hadNotEnoughSpaceLeft: boolean, forceDiskSpaceRequired?: number ): Promise<CheckDiskSpaceResponse> => { const diskSpaceRequired = forceDiskSpaceRequired || DISK_SPACE_REQUIRED; const response = await getDiskCheckReport(stateDirectoryPath); if (response.isError) { // @ts-ignore ts-migrate(2554) FIXME: Expected 2 arguments, but got 1. logger.info( '[DISK-SPACE-DEBUG] We could not check disk space, but we will try to start cardano-node anyway' ); resetInterval(DISK_SPACE_CHECK_DONT_BOTHER_ME_INTERVAL); } else { const diskSpaceMissing = Math.max( diskSpaceRequired - response.diskSpaceAvailableRaw, 0 ); const diskSpaceRecommended = (response.diskTotalSpaceRaw * DISK_SPACE_RECOMMENDED_PERCENTAGE) / 100; const diskSpaceRequiredMargin = diskSpaceRequired - (diskSpaceRequired * DISK_SPACE_REQUIRED_MARGIN_PERCENTAGE) / 100; if (response.diskSpaceAvailableRaw <= diskSpaceRequiredMargin) { if (!isNotEnoughDiskSpace) { // State change: transitioning from enough to not-enough disk space setDiskSpaceIntervalChecking(DISK_SPACE_CHECK_SHORT_INTERVAL); isNotEnoughDiskSpace = true; } } else if (response.diskSpaceAvailableRaw >= diskSpaceRequired) { const newDiskSpaceCheckIntervalLength = response.diskSpaceAvailableRaw >= diskSpaceRequired * 2 ? DISK_SPACE_CHECK_LONG_INTERVAL : DISK_SPACE_CHECK_MEDIUM_INTERVAL; if (isNotEnoughDiskSpace) { // State change: transitioning from not-enough to enough disk space setDiskSpaceIntervalChecking(newDiskSpaceCheckIntervalLength); isNotEnoughDiskSpace = false; } else if ( newDiskSpaceCheckIntervalLength !== diskSpaceCheckIntervalLength ) { // Interval change: transitioning from medium to long interval (or vice versa) // This is a special case in which we adjust the disk space check polling interval: // - more than 2x of available space than required: LONG interval // - less than 2x of available space than required: MEDIUM interval setDiskSpaceIntervalChecking(newDiskSpaceCheckIntervalLength); } } response.isNotEnoughDiskSpace = isNotEnoughDiskSpace; response.diskSpaceRequired = prettysize(diskSpaceRequired); response.diskSpaceMissing = prettysize(diskSpaceMissing); response.diskSpaceRecommended = prettysize(diskSpaceRecommended); response.hadNotEnoughSpaceLeft = hadNotEnoughSpaceLeft; } const NO_SPACE_AND_CARDANO_NODE_CAN_BE_STOPPED = isNotEnoughDiskSpace && cardanoNode.state !== CardanoNodeStates.STOPPING && cardanoNode.state !== CardanoNodeStates.STOPPED; const CARDANO_NODE_CAN_BE_STARTED_FOR_THE_FIRST_TIME = !isNotEnoughDiskSpace && cardanoNode.state === CardanoNodeStates.STOPPED && cardanoNode._startupTries === 0; const CARDANO_NODE_CAN_BE_STARTED_AFTER_FREEING_SPACE = !isNotEnoughDiskSpace && cardanoNode.state !== CardanoNodeStates.STOPPED && cardanoNode.state !== CardanoNodeStates.STOPPING && hadNotEnoughSpaceLeft; try { switch (true) { case NO_SPACE_AND_CARDANO_NODE_CAN_BE_STOPPED: try { // @ts-ignore ts-migrate(2554) FIXME: Expected 2 arguments, but got 1. logger.info('[DISK-SPACE-DEBUG] Stopping cardano node'); await cardanoNode.stop(); } catch (error) { logger.error('[DISK-SPACE-DEBUG] Cannot stop cardano node', error); } break; case CARDANO_NODE_CAN_BE_STARTED_FOR_THE_FIRST_TIME: await cardanoNode.start(); break; case CARDANO_NODE_CAN_BE_STARTED_AFTER_FREEING_SPACE: try { // @ts-ignore ts-migrate(2554) FIXME: Expected 2 arguments, but got 1. logger.info( '[DISK-SPACE-DEBUG] restart cardano node after freeing up disk space' ); if (cardanoNode._startupTries > 0) await cardanoNode.restart(); else await cardanoNode.start(); response.hadNotEnoughSpaceLeft = false; } catch (error) { logger.error( '[DISK-SPACE-DEBUG] Daedalus tried to restart, but failed', error ); } break; default: } } catch (error) { logger.error('[DISK-SPACE-DEBUG] Unknown error', error); resetInterval(DISK_SPACE_CHECK_MEDIUM_INTERVAL); } await getDiskSpaceStatusChannel.send(response, mainWindow.webContents); return response; }; const resetInterval = (interval: number) => { // Remove diskSpaceCheckInterval if set if (diskSpaceCheckInterval) { clearInterval(diskSpaceCheckInterval); // Reset to default check interval diskSpaceCheckIntervalLength = interval; } }; let hadNotEnoughSpaceLeft = false; const setDiskSpaceIntervalChecking = (interval) => { clearInterval(diskSpaceCheckInterval); diskSpaceCheckInterval = setInterval(async () => { const response = await handleCheckDiskSpace(hadNotEnoughSpaceLeft); hadNotEnoughSpaceLeft = response?.hadNotEnoughSpaceLeft; }, interval); diskSpaceCheckIntervalLength = interval; }; // Start default interval setDiskSpaceIntervalChecking(diskSpaceCheckIntervalLength); getDiskSpaceStatusChannel.onReceive(async () => { const diskReport = await getDiskCheckReport(stateDirectoryPath); await getDiskSpaceStatusChannel.send(diskReport, mainWindow.webContents); return diskReport; }); return handleCheckDiskSpace; }; ```
/content/code_sandbox/source/main/utils/handleDiskSpace.ts
xml
2016-10-05T13:48:54
2024-08-13T22:03:19
daedalus
input-output-hk/daedalus
1,230
1,877
```xml let measuringPerf = false let markID = 0 /** Start capturing git performance measurements. */ export function start() { measuringPerf = true } /** Stop capturing git performance measurements. */ export function stop() { measuringPerf = false } /** Measure an async git operation. */ export async function measure<T>( cmd: string, fn: () => Promise<T> ): Promise<T> { const id = ++markID const startTime = performance && performance.now ? performance.now() : null markBegin(id, cmd) try { return await fn() } finally { if (startTime) { const rawTime = performance.now() - startTime if (__DEV__ || rawTime > 1000) { const timeInSeconds = (rawTime / 1000).toFixed(3) log.info(`Executing ${cmd} (took ${timeInSeconds}s)`) } } markEnd(id, cmd) } } /** Mark the beginning of a git operation. */ function markBegin(id: number, cmd: string) { if (!measuringPerf) { return } const markName = `${id}::${cmd}` performance.mark(markName) } /** Mark the end of a git operation. */ function markEnd(id: number, cmd: string) { if (!measuringPerf) { return } const markName = `${id}::${cmd}` const measurementName = cmd performance.measure(measurementName, markName) performance.clearMarks(markName) performance.clearMeasures(measurementName) } ```
/content/code_sandbox/app/src/ui/lib/git-perf.ts
xml
2016-05-11T15:59:00
2024-08-16T17:00:41
desktop
desktop/desktop
19,544
346
```xml /** * Return a sanitized path * @param path * @ignore */ export function buildPath(path: string) { return path.split("/").filter(Boolean).join("/"); } ```
/content/code_sandbox/packages/specs/schema/src/utils/buildPath.ts
xml
2016-02-21T18:38:47
2024-08-14T21:19:48
tsed
tsedio/tsed
2,817
39
```xml export default () => <p>hello world</p> ```
/content/code_sandbox/test/integration/custom-server-types/pages/index.tsx
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
13
```xml import { SerializedTeam } from './team' import { SerializedFolder } from './folder' import { SerializedRevision } from './revision' import type { SerializedTag } from './tag' import { SerializedWorkspace } from './workspace' import { SerializedShareLink } from './shareLink' import { SerializedUser } from './user' import { Props } from './props' export type DocStatus = 'in_progress' | 'completed' | 'archived' | 'paused' export interface SerializedDocAssignee { id: string docId: string doc?: SerializedDoc userId: string user?: SerializedUser } export interface SerializableDocProps { id: string title: string emoji?: string parentFolderId?: string folderPathname: string generated: boolean version: number teamId: string workspaceId: string userId?: string } export interface SerializedUnserializableDocProps { parentFolder?: SerializedFolder team: SerializedTeam tags: SerializedTag[] createdAt: string updatedAt: string archivedAt?: string head?: SerializedRevision workspace?: SerializedWorkspace shareLink?: SerializedShareLink collaborationToken?: string user?: SerializedUser } export type SerializedDoc = SerializedUnserializableDocProps & SerializableDocProps export type SerializedDocWithSupplemental = SerializedDoc & { bookmarked: boolean props: Props contributors?: SerializedUser[] } ```
/content/code_sandbox/src/cloud/interfaces/db/doc.ts
xml
2016-11-19T14:30:34
2024-08-16T03:13:45
BoostNote-App
BoostIO/BoostNote-App
3,745
321
```xml /** * Helper class to track events across various analytics integrations */ export default class Analytics { /** * Send an event to Analytics * * @param event The event name * @param action The action name */ public static track = ( event: string, action: string, metadata?: Record<string, string> ) => { // GA3 if (window.ga) { window.ga("send", "event", event, action); } // GA4 if (window.dataLayer) { window.dataLayer.push({ event, action, ...metadata, }); } }; } ```
/content/code_sandbox/app/utils/Analytics.ts
xml
2016-05-22T21:31:47
2024-08-16T19:57:22
outline
outline/outline
26,751
143
```xml import * as React from 'react'; import type { AccessibilityState, ColorValue, NativeSyntheticEvent, PressableAndroidRippleConfig, TextLayoutEventData, } from 'react-native'; import { Animated, Easing, GestureResponderEvent, I18nManager, Platform, ScrollView, StyleProp, StyleSheet, View, ViewStyle, } from 'react-native'; import color from 'color'; import { getCombinedStyles, getFABColors } from './utils'; import { useInternalTheme } from '../../core/theming'; import type { $Omit, $RemoveChildren, ThemeProp } from '../../types'; import type { IconSource } from '../Icon'; import Icon from '../Icon'; import Surface from '../Surface'; import TouchableRipple from '../TouchableRipple/TouchableRipple'; import AnimatedText from '../Typography/AnimatedText'; export type AnimatedFABIconMode = 'static' | 'dynamic'; export type AnimatedFABAnimateFrom = 'left' | 'right'; export type Props = $Omit<$RemoveChildren<typeof Surface>, 'mode'> & { /** * Icon to display for the `FAB`. */ icon: IconSource; /** * Label for extended `FAB`. */ label: string; /** * Make the label text uppercased. */ uppercase?: boolean; /** * Type of background drawabale to display the feedback (Android). * path_to_url#rippleconfig */ background?: PressableAndroidRippleConfig; /** * Accessibility label for the FAB. This is read by the screen reader when the user taps the FAB. * Uses `label` by default if specified. */ accessibilityLabel?: string; /** * Accessibility state for the FAB. This is read by the screen reader when the user taps the FAB. */ accessibilityState?: AccessibilityState; /** * Custom color for the icon and label of the `FAB`. */ color?: string; /** * Color of the ripple effect. */ rippleColor?: ColorValue; /** * Whether `FAB` is disabled. A disabled button is greyed out and `onPress` is not called on touch. */ disabled?: boolean; /** * Whether `FAB` is currently visible. */ visible?: boolean; /** * Function to execute on press. */ onPress?: (e: GestureResponderEvent) => void; /** * Function to execute on long press. */ onLongPress?: (e: GestureResponderEvent) => void; /** * The number of milliseconds a user must touch the element before executing `onLongPress`. */ delayLongPress?: number; /** * Whether icon should be translated to the end of extended `FAB` or be static and stay in the same place. The default value is `dynamic`. */ iconMode?: AnimatedFABIconMode; /** * Indicates from which direction animation should be performed. The default value is `right`. */ animateFrom?: AnimatedFABAnimateFrom; /** * Whether `FAB` should start animation to extend. */ extended: boolean; /** * Specifies the largest possible scale a label font can reach. */ labelMaxFontSizeMultiplier?: number; /** * @supported Available in v5.x with theme version 3 * * Color mappings variant for combinations of container and icon colors. */ variant?: 'primary' | 'secondary' | 'tertiary' | 'surface'; style?: Animated.WithAnimatedValue<StyleProp<ViewStyle>>; /** * @optional */ theme?: ThemeProp; /** * TestID used for testing purposes */ testID?: string; }; const SIZE = 56; const SCALE = 0.9; /** * An animated, extending horizontally floating action button represents the primary action in an application. * * ## Usage * ```js * import React from 'react'; * import { * StyleProp, * ViewStyle, * Animated, * StyleSheet, * Platform, * ScrollView, * Text, * SafeAreaView, * I18nManager, * } from 'react-native'; * import { AnimatedFAB } from 'react-native-paper'; * * const MyComponent = ({ * animatedValue, * visible, * extended, * label, * animateFrom, * style, * iconMode, * }) => { * const [isExtended, setIsExtended] = React.useState(true); * * const isIOS = Platform.OS === 'ios'; * * const onScroll = ({ nativeEvent }) => { * const currentScrollPosition = * Math.floor(nativeEvent?.contentOffset?.y) ?? 0; * * setIsExtended(currentScrollPosition <= 0); * }; * * const fabStyle = { [animateFrom]: 16 }; * * return ( * <SafeAreaView style={styles.container}> * <ScrollView onScroll={onScroll}> * {[...new Array(100).keys()].map((_, i) => ( * <Text>{i}</Text> * ))} * </ScrollView> * <AnimatedFAB * icon={'plus'} * label={'Label'} * extended={isExtended} * onPress={() => console.log('Pressed')} * visible={visible} * animateFrom={'right'} * iconMode={'static'} * style={[styles.fabStyle, style, fabStyle]} * /> * </SafeAreaView> * ); * }; * * export default MyComponent; * * const styles = StyleSheet.create({ * container: { * flexGrow: 1, * }, * fabStyle: { * bottom: 16, * right: 16, * position: 'absolute', * }, * }); * ``` */ const AnimatedFAB = ({ icon, label, background, accessibilityLabel = label, accessibilityState, color: customColor, rippleColor: customRippleColor, disabled, onPress, onLongPress, delayLongPress, theme: themeOverrides, style, visible = true, uppercase: uppercaseProp, testID = 'animated-fab', animateFrom = 'right', extended = false, iconMode = 'dynamic', variant = 'primary', labelMaxFontSizeMultiplier, ...rest }: Props) => { const theme = useInternalTheme(themeOverrides); const uppercase: boolean = uppercaseProp ?? !theme.isV3; const isIOS = Platform.OS === 'ios'; const isAnimatedFromRight = animateFrom === 'right'; const isIconStatic = iconMode === 'static'; const { isRTL } = I18nManager; const { current: visibility } = React.useRef<Animated.Value>( new Animated.Value(visible ? 1 : 0) ); const { current: animFAB } = React.useRef<Animated.Value>( new Animated.Value(0) ); const { isV3, animation } = theme; const { scale } = animation; const [textWidth, setTextWidth] = React.useState<number>(0); const [textHeight, setTextHeight] = React.useState<number>(0); const borderRadius = SIZE / (isV3 ? 3.5 : 2); React.useEffect(() => { if (visible) { Animated.timing(visibility, { toValue: 1, duration: 200 * scale, useNativeDriver: true, }).start(); } else { Animated.timing(visibility, { toValue: 0, duration: 150 * scale, useNativeDriver: true, }).start(); } }, [visible, scale, visibility]); const { backgroundColor: customBackgroundColor, ...restStyle } = (StyleSheet.flatten(style) || {}) as ViewStyle; const { backgroundColor, foregroundColor } = getFABColors({ theme, variant, disabled, customColor, customBackgroundColor, }); const rippleColor = customRippleColor || color(foregroundColor).alpha(0.12).rgb().string(); const extendedWidth = textWidth + SIZE + borderRadius; const distance = isAnimatedFromRight ? -textWidth - borderRadius : textWidth + borderRadius; React.useEffect(() => { Animated.timing(animFAB, { toValue: !extended ? 0 : distance, duration: 150 * scale, useNativeDriver: true, easing: Easing.linear, }).start(); }, [animFAB, scale, distance, extended]); const onTextLayout = ({ nativeEvent, }: NativeSyntheticEvent<TextLayoutEventData>) => { const currentWidth = Math.ceil(nativeEvent.lines[0].width); const currentHeight = Math.ceil(nativeEvent.lines[0].height); if (currentWidth !== textWidth || currentHeight !== textHeight) { setTextHeight(currentHeight); if (isIOS) { return setTextWidth(currentWidth - 12); } setTextWidth(currentWidth); } }; const propForDirection = <T,>(right: T[]): T[] => { if (isAnimatedFromRight) { return right; } return right.reverse(); }; const combinedStyles = getCombinedStyles({ isAnimatedFromRight, isIconStatic, distance, animFAB, }); const font = isV3 ? theme.fonts.labelLarge : theme.fonts.medium; const textStyle = { color: foregroundColor, ...font, }; const md2Elevation = disabled || !isIOS ? 0 : 6; const md3Elevation = disabled || !isIOS ? 0 : 3; const shadowStyle = isV3 ? styles.v3Shadow : styles.shadow; const baseStyle = [ StyleSheet.absoluteFill, disabled ? styles.disabled : shadowStyle, ]; const newAccessibilityState = { ...accessibilityState, disabled }; return ( <Surface {...rest} testID={`${testID}-container`} style={[ { opacity: visibility, transform: [ { scale: visibility, }, ], borderRadius, }, !isV3 && { elevation: md2Elevation, }, styles.container, restStyle, ]} {...(isV3 && { elevation: md3Elevation })} theme={theme} > <Animated.View style={[ !isV3 && { transform: [ { scaleY: animFAB.interpolate({ inputRange: propForDirection([distance, 0]), outputRange: propForDirection([SCALE, 1]), }), }, ], }, styles.standard, { borderRadius }, ]} > <View style={[StyleSheet.absoluteFill, styles.shadowWrapper]}> <Animated.View pointerEvents="none" style={[ baseStyle, { width: extendedWidth, opacity: animFAB.interpolate({ inputRange: propForDirection([distance, 0.9 * distance, 0]), outputRange: propForDirection([1, 0.15, 0]), }), borderRadius, }, ]} testID={`${testID}-extended-shadow`} /> <Animated.View pointerEvents="none" style={[ baseStyle, { opacity: animFAB.interpolate({ inputRange: propForDirection([distance, 0.9 * distance, 0]), outputRange: propForDirection([0, 0.85, 1]), }), width: SIZE, borderRadius: animFAB.interpolate({ inputRange: propForDirection([distance, 0]), outputRange: propForDirection([ SIZE / (extendedWidth / SIZE), borderRadius, ]), }), }, combinedStyles.absoluteFill, ]} testID={`${testID}-shadow`} /> </View> <Animated.View pointerEvents="box-none" style={[styles.innerWrapper, { borderRadius }]} > <Animated.View style={[ styles.standard, { width: extendedWidth, backgroundColor, borderRadius, }, combinedStyles.innerWrapper, ]} > <TouchableRipple borderless background={background} onPress={onPress} onLongPress={onLongPress} delayLongPress={delayLongPress} rippleColor={rippleColor} disabled={disabled} accessibilityLabel={accessibilityLabel} accessibilityRole="button" accessibilityState={newAccessibilityState} testID={testID} style={{ borderRadius }} theme={theme} > <View style={[ styles.standard, { width: extendedWidth, borderRadius, }, ]} /> </TouchableRipple> </Animated.View> </Animated.View> </Animated.View> <Animated.View style={[styles.iconWrapper, combinedStyles.iconWrapper]} pointerEvents="none" > <Icon source={icon} size={24} color={foregroundColor} theme={theme} /> </Animated.View> <View pointerEvents="none"> <AnimatedText variant="labelLarge" numberOfLines={1} onTextLayout={isIOS ? onTextLayout : undefined} ellipsizeMode={'tail'} style={[ { [isAnimatedFromRight || isRTL ? 'right' : 'left']: isIconStatic ? textWidth - SIZE + borderRadius / (isV3 ? 1 : 2) : borderRadius, }, { minWidth: textWidth, top: -SIZE / 2 - textHeight / 2, opacity: animFAB.interpolate({ inputRange: propForDirection([distance, 0.7 * distance, 0]), outputRange: propForDirection([1, 0, 0]), }) as unknown as number, // TODO: check transform: [ { translateX: animFAB.interpolate({ inputRange: propForDirection([distance, 0]), outputRange: propForDirection([0, SIZE]), }), }, ], }, styles.label, uppercase && styles.uppercaseLabel, textStyle, ]} theme={theme} testID={`${testID}-text`} maxFontSizeMultiplier={labelMaxFontSizeMultiplier} > {label} </AnimatedText> </View> {!isIOS && ( // Method `onTextLayout` on Android returns sizes of text visible on the screen, // however during render the text in `FAB` isn't fully visible. In order to get // proper text measurements there is a need to additionaly render that text, but // wrapped in absolutely positioned `ScrollView` which height is 0. <ScrollView style={styles.textPlaceholderContainer}> <AnimatedText variant="labelLarge" numberOfLines={1} onTextLayout={onTextLayout} ellipsizeMode={'tail'} style={[ styles.label, uppercase && styles.uppercaseLabel, textStyle, ]} theme={theme} > {label} </AnimatedText> </ScrollView> )} </Surface> ); }; const styles = StyleSheet.create({ standard: { height: SIZE, }, disabled: { elevation: 0, }, // eslint-disable-next-line react-native/no-color-literals container: { position: 'absolute', backgroundColor: 'transparent', }, innerWrapper: { flexDirection: 'row', overflow: 'hidden', }, shadowWrapper: { elevation: 0, }, shadow: { elevation: 6, }, v3Shadow: { elevation: 3, }, iconWrapper: { alignItems: 'center', justifyContent: 'center', position: 'absolute', height: SIZE, width: SIZE, }, label: { position: 'absolute', }, uppercaseLabel: { textTransform: 'uppercase', }, textPlaceholderContainer: { height: 0, position: 'absolute', }, }); export default AnimatedFAB; ```
/content/code_sandbox/src/components/FAB/AnimatedFAB.tsx
xml
2016-10-19T05:56:53
2024-08-16T08:48:04
react-native-paper
callstack/react-native-paper
12,646
3,529
```xml import React from 'react'; import styles from './styles.scss'; type SidebarMenuCategoryHeaderProps = { headerText: string; compact?: boolean; } const SidebarMenuCategoryHeader: React.FC<SidebarMenuCategoryHeaderProps> = ({ compact = false, headerText }) => { return ( !compact && <div className={styles.sidebar_menu_category_header}> <span> {headerText} </span> <hr /> </div> ); }; export default SidebarMenuCategoryHeader; ```
/content/code_sandbox/packages/app/app/components/SidebarMenu/SidebarMenuCategoryHeader/index.tsx
xml
2016-09-22T22:58:21
2024-08-16T15:47:39
nuclear
nukeop/nuclear
11,862
111
```xml <?xml version="1.0" encoding="UTF-8"?> <!-- FILE INFORMATION OMA Permanent Document File: OMA-SUP-XML_25-V2_0-20210518-A.xml Path: path_to_url OMNA LwM2M Registry Path: path_to_url Name: 25.xml NORMATIVE INFORMATION Information about this file can be found in the latest revision of OMA-TS-LightweightM2M_Gateway-V1_1 This is available at path_to_url Send comments to path_to_url LEGAL DISCLAIMER Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The above license is used as a license under copyright only. Please reference the OMA IPR Policy for patent licensing terms: path_to_url --> <LWM2M xmlns:xsi="path_to_url" xsi:noNamespaceSchemaLocation="path_to_url"> <Object ObjectType="MODefinition"> <Name>LwM2M Gateway</Name> <Description1><![CDATA[This object is used by a LwM2M Gateway to maintain the IoT Devices connected to the LwM2M Gateway.]]></Description1> <ObjectID>25</ObjectID> <ObjectURN>urn:oma:lwm2m:oma:25:2.0</ObjectURN> <LWM2MVersion>1.1</LWM2MVersion> <ObjectVersion>2.0</ObjectVersion> <MultipleInstances>Multiple</MultipleInstances> <Mandatory>Optional</Mandatory> <Resources> <Item ID="0"> <Name>Device ID</Name> <Operations>R</Operations> <MultipleInstances>Single</MultipleInstances> <Mandatory>Mandatory</Mandatory> <Type>String</Type> <RangeEnumeration></RangeEnumeration> <Units></Units> <Description><![CDATA[This resource identifies the IoT Device connected to the LwM2M Gateway.]]></Description> </Item> <Item ID="1"> <Name>Prefix</Name> <Operations>R</Operations> <MultipleInstances>Single</MultipleInstances> <Mandatory>Mandatory</Mandatory> <Type>String</Type> <RangeEnumeration></RangeEnumeration> <Units></Units> <Description><![CDATA[This resource defines what prefix MUST be used for access to LwM2M Objects of this IoT Device.]]></Description> </Item> <Item ID="3"> <Name>IoT Device Objects</Name> <Operations>R</Operations> <MultipleInstances>Single</MultipleInstances> <Mandatory>Mandatory</Mandatory> <Type>Corelnk</Type> <RangeEnumeration></RangeEnumeration> <Units></Units> <Description><![CDATA[This resource contains the Objects and Object Instances exposed by the LwM2M Gateway on behalf of the IoT Device. It uses the same CoreLnk format as Registration Interface.]]></Description> </Item> </Resources> <Description2 /> </Object> </LWM2M> ```
/content/code_sandbox/application/src/main/data/lwm2m-registry/25.xml
xml
2016-12-01T09:33:30
2024-08-16T19:58:25
thingsboard
thingsboard/thingsboard
16,820
989
```xml /* * This software is released under MIT license. * The full license information can be found in LICENSE in the root directory of this project. */ import './aria-reflect.js'; ```
/content/code_sandbox/packages/core/src/polyfills/index.ts
xml
2016-09-29T17:24:17
2024-08-11T17:06:15
clarity
vmware-archive/clarity
6,431
37
```xml import { gql } from '@apollo/client'; import React from 'react'; import Spinner from '@erxes/ui/src/components/Spinner'; import ReserveRems from '../components/List'; import { Alert, router } from '@erxes/ui/src/utils'; import { Bulk } from '@erxes/ui/src/components'; import { mutations, queries } from '../graphql'; import { IReserveRem } from '../types'; import { ReserveRemsQueryResponse, ReserveRemsRemoveMutationResponse, ReserveRemsCountQueryResponse, ReserveRemsEditMutationResponse, } from '../types'; import { useQuery, useMutation } from '@apollo/client'; type Props = { queryParams: any; type?: string; }; const ReserveRemsContainer: React.FC<Props> = (props) => { const { queryParams } = props; const reserveRemQuery = useQuery<ReserveRemsQueryResponse>( gql(queries.reserveRems), { variables: generateParams({ queryParams }), fetchPolicy: 'network-only', }, ); const reserveRemsCountQuery = useQuery<ReserveRemsCountQueryResponse>( gql(queries.reserveRemsCount), { variables: generateParams({ queryParams }), fetchPolicy: 'network-only', }, ); const [reserveRemEdit] = useMutation<ReserveRemsEditMutationResponse>( gql(mutations.reserveRemEdit), ); const [reserveRemsRemove] = useMutation<ReserveRemsRemoveMutationResponse>( gql(mutations.reserveRemsRemove), { refetchQueries: getRefetchQueries() }, ); if (reserveRemQuery.loading || reserveRemsCountQuery.loading) { return <Spinner />; } // edit row action const edit = (doc: IReserveRem) => { reserveRemEdit({ variables: { ...doc }, }) .then(() => { Alert.success('You successfully updated a labels'); reserveRemQuery.refetch(); }) .catch((e) => { Alert.error(e.message); }); }; // remove action const remove = ({ reserveRemIds }, emptyBulk) => { reserveRemsRemove({ variables: { _ids: reserveRemIds }, }) .then((removeStatus) => { emptyBulk(); if (removeStatus && removeStatus.data) { removeStatus.data.reserveRemsRemove.deletedCount ? Alert.success('You successfully deleted a product') : Alert.warning('Product status deleted'); } }) .catch((e) => { Alert.error(e.message); }); }; const searchValue = props.queryParams.searchValue || ''; const reserveRems = (reserveRemQuery.data && reserveRemQuery.data.reserveRems) || []; const totalCount = (reserveRemsCountQuery.data && reserveRemsCountQuery.data.reserveRemsCount) || 0; const updatedProps = { ...props, searchValue, queryParams, reserveRems, totalCount, edit, remove, }; const reserveRemList = (props) => ( <ReserveRems {...updatedProps} {...props} /> ); const refetch = () => { reserveRemQuery.refetch(); }; return <Bulk content={reserveRemList} refetch={refetch} />; }; const getRefetchQueries = () => { return ['reserveRems', 'reserveRemsCount']; }; const generateParams = ({ queryParams }) => ({ ...router.generatePaginationParams(queryParams || {}), _ids: queryParams._ids, date: queryParams.date, searchValue: queryParams.searchValue, departmentId: queryParams.departmentId, branchId: queryParams.branchId, productId: queryParams.productId, productCategoryId: queryParams.productCategoryId, dateType: queryParams.dateType, startDate: queryParams.startDate, endDate: queryParams.endDate, }); export default ReserveRemsContainer; ```
/content/code_sandbox/packages/plugin-inventories-ui/src/reserveRemainders/containers/List.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
839
```xml import { useCallback, useEffect, useRef, useState } from 'react' import { useApplication } from '../ApplicationProvider' import Icon from '../Icon/Icon' import { confirmDialog } from '@standardnotes/ui-services' import { BlocksEditorComposer } from '../SuperEditor/BlocksEditorComposer' import { BlocksEditor } from '../SuperEditor/BlocksEditor' import { SNNote } from '@standardnotes/snjs' import { NoteSyncController } from '@/Controllers/NoteSyncController' import LinkedItemBubblesContainer from '../LinkedItems/LinkedItemBubblesContainer' import { LinkingController } from '@/Controllers/LinkingController' import Button from '../Button/Button' import Spinner from '../Spinner/Spinner' const ClippedNoteView = ({ note, linkingController, clearClip, isFirefoxPopup, }: { note: SNNote linkingController: LinkingController clearClip: () => void isFirefoxPopup: boolean }) => { const application = useApplication() const syncController = useRef( new NoteSyncController( note, application.items, application.mutator, application.sessions, application.sync, application.alerts, application.isNativeMobileWebUseCase, ), ) useEffect(() => { const currentController = syncController.current return () => { currentController.deinit() } }, []) const [title, setTitle] = useState(() => note.title) useEffect(() => { void syncController.current.saveAndAwaitLocalPropagation({ title, isUserModified: true, dontGeneratePreviews: true, }) }, [application.items, title]) const handleChange = useCallback(async (value: string, preview: string) => { void syncController.current.saveAndAwaitLocalPropagation({ text: value, isUserModified: true, previews: { previewPlain: preview, previewHtml: undefined, }, }) }, []) const [isDiscarding, setIsDiscarding] = useState(false) const discardNote = useCallback(async () => { if ( await confirmDialog({ text: 'Are you sure you want to discard this clip?', confirmButtonText: 'Discard', confirmButtonStyle: 'danger', }) ) { setIsDiscarding(true) application.mutator .deleteItem(note) .then(() => application.sync.sync()) .then(() => { if (isFirefoxPopup) { window.close() } clearClip() }) .catch(console.error) .finally(() => setIsDiscarding(false)) } }, [application.mutator, application.sync, clearClip, isFirefoxPopup, note]) return ( <div className=""> <div className="border-b border-border p-3"> <div className="mb-3 flex w-full items-center gap-3"> {!isFirefoxPopup && ( <Button className="flex items-center justify-center" fullWidth onClick={clearClip} disabled={isDiscarding}> <Icon type="arrow-left" className="mr-2" /> Back </Button> )} <Button className="flex items-center justify-center" fullWidth primary colorStyle="danger" onClick={discardNote} disabled={isDiscarding} > {isDiscarding ? ( <Spinner className="h-6 w-6 text-danger-contrast" /> ) : ( <> <Icon type="trash-filled" className="mr-2" /> Discard </> )} </Button> </div> <input className="w-full text-base font-semibold" type="text" value={title} onChange={(event) => { setTitle(event.target.value) }} /> <LinkedItemBubblesContainer linkingController={linkingController} item={note} hideToggle /> </div> <div className="p-3"> <BlocksEditorComposer initialValue={note.text}> <BlocksEditor onChange={handleChange}></BlocksEditor> </BlocksEditorComposer> </div> </div> ) } export default ClippedNoteView ```
/content/code_sandbox/packages/web/src/javascripts/Components/ClipperView/ClippedNoteView.tsx
xml
2016-12-05T23:31:33
2024-08-16T06:51:19
app
standardnotes/app
5,180
884
```xml <?xml version="1.0" encoding="UTF-8"?> <snippets> <snippet name="Sum_A_B"> <global></global> <equation>$$PLOT_A$$ + $$PLOT_B$$</equation> </snippet> <snippet name="1st_derivative"> <global> var prevX = 0 var prevY = 0 </global> <equation> dx = time - prevX dy = value - prevY prevX = time prevY = value return dy/dx </equation> </snippet> <snippet name="1st_order_low_pass"> <global> var prevY = 0 var alpha = 0.1 </global> <equation> prevY = alpha * value + (1.-alpha) * prevY return prevY </equation> </snippet> <snippet name="quaternion_to_euler"> <global/> <equation> return quaternionToEulerAngle($$x$$, $$y$$, $$z$$, $$w$$)[2]; // yaw in degrees </equation> </snippet> <snippet name="geographic_coordinates_distance"> <global> // see path_to_url var geod = GeographicLib.Geodesic.WGS84; </global> <equation> r = geod.Inverse(-41.32, 174.81, $$lat$$, $$lon$$); return r.s12 // distance in meters </equation> </snippet> </snippets> ```
/content/code_sandbox/datasamples/default.snippets.xml
xml
2016-03-01T21:05:42
2024-08-16T08:37:27
PlotJuggler
facontidavide/PlotJuggler
4,294
347
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE language SYSTEM "language.dtd"> <language name="OPAL" version="2" kateversion="2.3" section="Sources" extensions="*.impl;*.sign" mimetype="" author="Sebastian Pipping (webmaster@hartwork.org)"> <highlighting> <list name="opal_keywords"> <item>ALL</item> <item>AND</item> <item>ANDIF</item> <item>ANY</item> <item>AS</item> <item>ASSERT</item> <item>AXM</item> <item>COMPLETELY</item> <item>DATA</item> <item>DEF</item> <item>DERIVE</item> <item>DFD</item> <item>DISCRIMINATORS</item> <item>ELSE</item> <item>EX</item> <item>EXTERNAL</item> <item>FI</item> <item>FIX</item> <item>FUN</item> <item>IF</item> <item>IMPLEMENTATION</item> <item>IMPLIES</item> <item>IMPORT</item> <item>IN</item> <item>INHERIT</item> <item>INJECTIONS</item> <item>INTERFACE</item> <item>INTERNAL</item> <item>LAW</item> <item>LAZY</item> <item>LEFTASSOC</item> <item>LET</item> <item>MODULE</item> <item>NOT</item> <item>ONLY</item> <item>OR</item> <item>ORIF</item> <item>OTHERWISE</item> <item>POST</item> <item>PRE</item> <item>PRED</item> <item>PRIORITY</item> <item>PROPERTIES</item> <item>REALIZES</item> <item>REQUIRE</item> <item>RIGHTASSOC</item> <item>SELECTORS</item> <item>SIGNATURE</item> <item>SORT</item> <item>SPC</item> <item>SPEC</item> <item>SPECIFICATION</item> <item>STRUCTURE</item> <item>THE</item> <item>THEN</item> <item>THEORY</item> <item>THM</item> <item>TYPE</item> <item>UNIQ</item> <item>WHERE</item> </list> <list name="opal_sorts"> <item>aEntry</item> <item>agent</item> <item>align</item> <item>anchor</item> <item>ans</item> <item>arg</item> <item>arg1</item> <item>arg2</item> <item>array</item> <item>arrowWhere</item> <item>bag</item> <item>bitmap</item> <item>bool</item> <item>bstree</item> <item>byte</item> <item>callback</item> <item>canvasEditor</item> <item>capStyle</item> <item>channel</item> <item>char</item> <item>childstat</item> <item>codom</item> <item>codomFrom</item> <item>codomTo</item> <item>color</item> <item>colorModel</item> <item>com</item> <item>composeOp</item> <item>config</item> <item>configCom</item> <item>cursor</item> <item>dArray</item> <item>data</item> <item>data1</item> <item>data11</item> <item>data2</item> <item>data21</item> <item>data3</item> <item>data31</item> <item>data4</item> <item>data41</item> <item>dataFrom</item> <item>dataTo</item> <item>defaultPrio</item> <item>denotation</item> <item>device</item> <item>dist</item> <item>distOut</item> <item>dom</item> <item>domFrom</item> <item>domTo</item> <item>drawing</item> <item>dyn</item> <item>emitter</item> <item>env</item> <item>event</item> <item>eventInfo</item> <item>file</item> <item>filemode</item> <item>filestat</item> <item>filetype</item> <item>first</item> <item>first1</item> <item>first2</item> <item>first3</item> <item>fission</item> <item>fmt</item> <item>font</item> <item>from</item> <item>from1</item> <item>from2</item> <item>funct</item> <item>group</item> <item>groupid</item> <item>heap</item> <item>iconfig</item> <item>image</item> <item>in</item> <item>inData</item> <item>index</item> <item>inode</item> <item>input</item> <item>int</item> <item>inter</item> <item>interdom</item> <item>interpreter</item> <item>iseq</item> <item>items</item> <item>joinStyle</item> <item>justifyHow</item> <item>long</item> <item>manager</item> <item>managerRequest</item> <item>map</item> <item>mapEntry</item> <item>mark</item> <item>mid</item> <item>modifier</item> <item>nat</item> <item>natMap</item> <item>OBJECT</item> <item>option</item> <item>orient</item> <item>out</item> <item>outData</item> <item>output</item> <item>packOp</item> <item>pair</item> <item>parser</item> <item>permission</item> <item>point</item> <item>positionRequest</item> <item>process</item> <item>procstat</item> <item>quad</item> <item>range</item> <item>real</item> <item>regulator</item> <item>rel</item> <item>relief</item> <item>res</item> <item>res1</item> <item>res2</item> <item>result</item> <item>role</item> <item>sap</item> <item>script</item> <item>scroller</item> <item>scrollView</item> <item>scrollWindow</item> <item>searchOpt</item> <item>second</item> <item>seekMode</item> <item>selector</item> <item>semaphor</item> <item>seq</item> <item>seqEntry</item> <item>set</item> <item>setEntry</item> <item>short</item> <item>sigaction</item> <item>sighandler</item> <item>sigmask</item> <item>signal</item> <item>size</item> <item>sizeRequest</item> <item>some</item> <item>sreal</item> <item>state</item> <item>stateId</item> <item>stateRequest</item> <item>string</item> <item>subrel</item> <item>tag</item> <item>textEditor</item> <item>time</item> <item>to</item> <item>tree</item> <item>triple</item> <item>union</item> <item>user</item> <item>userid</item> <item>version</item> <item>view</item> <item>void</item> <item>wconfig</item> <item>wconfigCom</item> <item>wday</item> <item>widget</item> <item>window</item> <item>wrapStyle</item> </list> <list name="opal_other"> <item>true</item> <item>false</item> <item>0</item> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> <item>6</item> <item>7</item> <item>8</item> <item>9</item> <item>10</item> <item>11</item> <item>12</item> <item>13</item> <item>14</item> <item>15</item> <item>16</item> <item>17</item> <item>18</item> <item>19</item> <item>20</item> <item>21</item> <item>22</item> <item>23</item> <item>24</item> <item>25</item> <item>26</item> <item>27</item> <item>28</item> <item>29</item> <item>30</item> <item>31</item> <item>32</item> <item>64</item> <item>128</item> <item>256</item> <item>512</item> <item>1024</item> <item>10000</item> <item>100000</item> <item>1000000</item> </list> <contexts> <context attribute="Normal Text" lineEndContext="#stay" name="Normal"> <keyword attribute="Keyword" context="#stay" String="opal_keywords"/> <keyword attribute="Sort" context="#stay" String="opal_sorts"/> <keyword attribute="Decimal" context="#stay" String="opal_other"/> <DetectChar attribute="String" context="String" char="&quot;"/> <RegExpr attribute="Comment" context="SingLineCom" String="(?:^--$|^--[^-]|[^-]--[^-]|[^-]--$)"/> <Detect2Chars attribute="Comment" context="MultLineCom" char="/" char1="*"/> </context> <context attribute="String" lineEndContext="#stay" name="String"> <Detect2Chars attribute="String" context="#stay" char="\" char1="&quot;"/> <DetectChar attribute="String" context="#pop" char="&quot;"/> </context> <context attribute="Comment" lineEndContext="#pop" name="SingLineCom"/> <context attribute="Comment" lineEndContext="#stay" name="MultLineCom"> <Detect2Chars attribute="Comment" context="#pop" char="*" char1="/"/> <Detect2Chars attribute="Comment" context="MultLineCom" char="/" char1="*"/> </context> </contexts> <itemDatas> <itemData name="Normal Text" defStyleNum="dsNormal"/> <itemData name="Keyword" defStyleNum="dsKeyword" color="#0000ff"/> <itemData name="Sort" defStyleNum="dsDataType" color="#0000ff"/> <itemData name="Decimal" defStyleNum="dsString"/> <itemData name="String" defStyleNum="dsString"/> <itemData name="Comment" defStyleNum="dsOthers"/> </itemDatas> </highlighting> <general> <comments> <comment name="singleLine" start="--"/> <comment name="multiLine" start="/*" end="*/"/> </comments> <keywords casesensitive="1"/> </general> </language> ```
/content/code_sandbox/src/data/extra/syntax-highlighting/syntax/opal.xml
xml
2016-10-05T07:24:54
2024-08-16T05:03:40
vnote
vnotex/vnote
11,687
3,205
```xml import { FlexContent, FlexItem } from "@erxes/ui/src/layout/styles"; import { FlexRow, Forms, ReactionItem } from "./styles"; import { IArticle, IErxesForm, ITopic, } from "@erxes/ui-knowledgeBase/src/types"; import { IAttachment, IButtonMutateProps, IFormProps, IOption, } from "@erxes/ui/src/types"; import Select, { OnChangeValue } from "react-select"; import { __, extractAttachment } from "coreui/utils"; import Button from "@erxes/ui/src/components/Button"; import ControlLabel from "@erxes/ui/src/components/form/Label"; import { FILE_MIME_TYPES } from "@erxes/ui-settings/src/general/constants"; import Form from "@erxes/ui/src/components/form/Form"; import FormControl from "@erxes/ui/src/components/form/Control"; import FormGroup from "@erxes/ui/src/components/form/Group"; import Icon from "@erxes/ui/src/components/Icon"; import { ModalFooter } from "@erxes/ui/src/styles/main"; import React from "react"; import { RichTextEditor } from "@erxes/ui/src/components/richTextEditor/TEditor"; import Uploader from "@erxes/ui/src/components/Uploader"; import { articleReactions } from "../../icons.constant"; type Props = { article: IArticle; currentCategoryId: string; renderButton: (props: IButtonMutateProps) => JSX.Element; closeModal: () => void; topics: ITopic[]; topicId?: string; }; type State = { content: string; reactionChoices: string[]; topicId?: string; categoryId: string; attachments: IAttachment[]; image: IAttachment | null; erxesForms: IErxesForm[]; isPrivate: boolean; }; class ArticleForm extends React.Component<Props, State> { constructor(props: Props) { super(props); const article = props.article || ({ content: "" } as IArticle); const attachments = (article.attachments && extractAttachment(article.attachments)) || []; const image = article.image ? extractAttachment([article.image])[0] : null; this.state = { content: article.content, reactionChoices: article.reactionChoices || [], topicId: article.topicId, categoryId: article.categoryId, erxesForms: article.forms || [], image, attachments, isPrivate: article.isPrivate || false, }; } componentDidUpdate(prevProps) { const { topics, currentCategoryId } = this.props; const self = this; if (!this.state.topicId && topics && topics.length > 0) { this.setState({ topicId: self.props.topicId, categoryId: currentCategoryId, }); } } getFirstAttachment = () => { const { attachments } = this.state; return attachments.length > 0 ? attachments[0] : ({} as IAttachment); }; generateDoc = (values: { _id?: string; title: string; summary: string; status: string; code?: string; }) => { const { article, currentCategoryId } = this.props; const { attachments, content, reactionChoices, topicId, categoryId, image, erxesForms, isPrivate, } = this.state; const finalValues = values; if (article) { finalValues._id = article._id; } return { _id: finalValues._id, doc: { title: finalValues.title, code: finalValues.code, summary: finalValues.summary, content, reactionChoices, status: finalValues.status, isPrivate, categoryIds: [currentCategoryId], topicId, forms: erxesForms.map((f) => ({ formId: f.formId, brandId: f.brandId, })), attachments, categoryId, image, }, }; }; onChange = (content: string) => { this.setState({ content }); }; onChangeReactions = (options: OnChangeValue<IOption, true>) => { this.setState({ reactionChoices: options.map((option) => option.value) }); }; onChangeAttachments = (attachments: IAttachment[]) => this.setState({ attachments }); onChangeImage = (images: IAttachment[]) => { if (images && images.length > 0) { this.setState({ image: images[0] }); } else { this.setState({ image: null }); } }; onChangeIsCheckDate = (e) => { const isChecked = (e.currentTarget as HTMLInputElement).checked; this.setState({ isPrivate: isChecked }); }; onChangeAttachment = (key: string, value: string | number) => { this.setState({ attachments: [ { ...this.getFirstAttachment(), [key]: value, }, ], }); }; onChangeForm = (formId: string, key: string, value: string | number) => { const erxesForms = this.state.erxesForms; // find current editing one const erxesForm = erxesForms.find((form) => form.formId === formId) || []; // set new value erxesForm[key] = value; this.setState({ erxesForms }); }; addErxesForm = () => { const erxesForms = this.state.erxesForms.slice(); erxesForms.push({ brandId: "", formId: "", }); this.setState({ erxesForms }); }; removeForm = (formId) => { let erxesForms = this.state.erxesForms; erxesForms = erxesForms.filter((form) => form.formId !== formId); this.setState({ erxesForms }); }; renderOption = (option) => { return ( <ReactionItem> <img src={option.value} alt={option.label} /> {option.label} </ReactionItem> ); }; generateOptions = (options) => { return options.map((option) => ({ value: option._id, label: option.title, })); }; renderTopics(formProps: IFormProps) { const self = this; const { topics } = this.props; const onChange = (e) => { e.preventDefault(); const selectedTopicId = e.target.value; const topic = topics.find((t) => t._id === selectedTopicId); const categories = topic ? topic.categories || [] : []; self.setState({ topicId: selectedTopicId, categoryId: categories.length > 0 ? categories[0]._id : "", }); }; return ( <FormGroup> <ControlLabel required={true}>Choose the knowledgebase</ControlLabel> <br /> <FormControl {...formProps} name="topicId" componentclass="select" required={true} placeholder={__("Choose knowledgebase")} value={self.state.topicId} options={self.generateOptions(topics)} onChange={onChange} /> </FormGroup> ); } renderCategories(formProps: IFormProps) { const self = this; const topic = this.props.topics.find((t) => t._id === self.state.topicId); const categories = topic ? topic.categories || [] : []; const onChange = (e) => { e.preventDefault(); self.setState({ categoryId: e.target.value }); }; return ( <FormGroup> <ControlLabel required={true}>Choose the category</ControlLabel> <br /> <FormControl {...formProps} name="categoryId" componentclass="select" placeholder={__("Choose category")} value={self.state.categoryId} options={self.generateOptions(categories)} onChange={onChange} required={true} /> </FormGroup> ); } renderErxesForm = (form: IErxesForm, formProps: IFormProps) => { const remove = () => { this.removeForm(form.formId); }; return ( <FlexRow key={form.formId}> <FormGroup> <ControlLabel required={true}>{__("Brand id")}</ControlLabel> <FormControl {...formProps} name="brandId" required={true} defaultValue={form.brandId} onChange={(e: any) => this.onChangeForm(form.formId, "brandId", e.target.value) } /> </FormGroup> <FormGroup> <ControlLabel required={true}>{__("Form id")}</ControlLabel> <FormControl {...formProps} name="formId" required={true} defaultValue={form.formId} onChange={(e: any) => this.onChangeForm(form.formId, "formId", e.target.value) } /> </FormGroup> <Button size="small" btnStyle="danger" onClick={remove}> <Icon icon="cancel-1" /> </Button> </FlexRow> ); }; renderContent = (formProps: IFormProps) => { const { article, renderButton, closeModal } = this.props; const { attachments, reactionChoices, content, image, isPrivate } = this.state; const attachment = this.getFirstAttachment(); const mimeTypeOptions = FILE_MIME_TYPES.map((item) => ({ value: item.value, label: `${item.label} (${item.extension})`, })); const { isSubmitted, values } = formProps; const object = article || ({} as IArticle); return ( <> <FormGroup> <ControlLabel required={true}>{__("Title")}</ControlLabel> <FormControl {...formProps} name="title" defaultValue={object.title} required={true} autoFocus={true} /> </FormGroup> <FormGroup> <ControlLabel>{__("Code")}</ControlLabel> <FormControl {...formProps} name="code" defaultValue={object.code} /> </FormGroup> <FormGroup> <ControlLabel>{__("Summary")}</ControlLabel> <FormControl {...formProps} name="summary" defaultValue={object.summary} /> </FormGroup> <FlexContent> <FlexItem count={4}> <FormGroup> <ControlLabel required={true}>{__("Reactions")}</ControlLabel> <Select isMulti={true} value={articleReactions.filter((o) => reactionChoices.includes(o.value) )} options={articleReactions} onChange={this.onChangeReactions} placeholder={__("Select")} /> </FormGroup> </FlexItem> <FlexItem count={2} hasSpace={true}> <FormGroup> <ControlLabel required={true}>{__("Status")}</ControlLabel> <FormControl {...formProps} name="status" componentclass="select" placeholder={__("Select")} defaultValue={object.status || "draft"} required={true} > {[{ value: "draft" }, { value: "publish" }].map((op) => ( <option key={op.value} value={op.value}> {op.value} </option> ))} </FormControl> </FormGroup> <FormGroup> <ControlLabel required={true}>{__("isPrivate")}</ControlLabel> <FormControl componentclass="checkbox" checked={isPrivate} onChange={this.onChangeIsCheckDate} /> </FormGroup> </FlexItem> </FlexContent> <FlexContent> <FlexItem count={3}>{this.renderTopics(formProps)}</FlexItem> <FlexItem count={3} hasSpace={true}> {this.renderCategories(formProps)} </FlexItem> </FlexContent> <FormGroup> <ControlLabel>{__("Image")}</ControlLabel> <Uploader defaultFileList={image ? [image] : []} onChange={this.onChangeImage} single={true} /> </FormGroup> <FormGroup> <ControlLabel>{__("Attachment")}</ControlLabel> <Uploader defaultFileList={attachments} onChange={this.onChangeAttachments} single={true} /> </FormGroup> <FlexContent> <FlexItem count={2} hasSpace={true}> <FormGroup> <ControlLabel>{__("File url")}</ControlLabel> <FormControl placeholder="Url" value={attachment.url || ""} onChange={(e: any) => this.onChangeAttachment("url", e.target.value) } /> </FormGroup> <FormGroup> <ControlLabel>{__("File name")}</ControlLabel> <FormControl placeholder="Name" value={attachment.name || ""} onChange={(e: any) => this.onChangeAttachment("name", e.target.value) } /> </FormGroup> </FlexItem> <FlexItem count={2} hasSpace={true}> <FormGroup> <ControlLabel>{__("File size (byte)")}</ControlLabel> <FormControl placeholder="Size (byte)" value={attachment.size || ""} type="number" onChange={(e: any) => this.onChangeAttachment("size", parseInt(e.target.value, 10)) } /> </FormGroup> <FormGroup> <ControlLabel>{__("File type")}</ControlLabel> <FormControl componentclass="select" value={attachment.type || ""} onChange={(e: any) => this.onChangeAttachment("type", e.target.value) } options={[ { value: "", label: "Select type" }, ...mimeTypeOptions, ]} /> </FormGroup> </FlexItem> <FlexItem count={2} hasSpace={true}> <FormGroup> <ControlLabel>{__("File duration (sec)")}</ControlLabel> <FormControl placeholder="Duration" value={attachment.duration || 0} onChange={(e: any) => this.onChangeAttachment( "duration", parseInt(e.target.value, 10) ) } /> </FormGroup> </FlexItem> </FlexContent> <FormGroup> <ControlLabel>{__("erxes forms")}</ControlLabel> <Forms> {this.state.erxesForms.map((form) => this.renderErxesForm(form, formProps) )} </Forms> <Button btnStyle="simple" size="small" onClick={this.addErxesForm} icon="add" > Add another form </Button> </FormGroup> <FormGroup> <ControlLabel required={true}>{__("Content")}</ControlLabel> <RichTextEditor content={content} onChange={this.onChange} isSubmitted={isSubmitted} height={300} name={`knowledgeBase_${article ? article._id : "create"}`} /> </FormGroup> <ModalFooter> <Button btnStyle="simple" type="button" onClick={this.props.closeModal} icon="times-circle" > {__("Cancel")} </Button> {renderButton({ passedName: "article", values: this.generateDoc(values), isSubmitted, callback: closeModal, object: article, })} </ModalFooter> </> ); }; render() { return <Form renderContent={this.renderContent} />; } } export default ArticleForm; ```
/content/code_sandbox/packages/plugin-knowledgebase-ui/src/components/article/ArticleForm.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
3,335
```xml import { MAX_DSA_ADDITIONAL_INFO_LENGTH, MAX_DSA_LAW_BROKEN_LENGTH, } from "coral-common/common/lib/constants"; import { Config } from "coral-server/config"; import { DataCache } from "coral-server/data/cache/dataCache"; import { MongoContext } from "coral-server/data/context"; import { CommentNotFoundError, DSAReportAdditionalInfoTooLongError, DSAReportLawBrokenTooLongError, StoryNotFoundError, } from "coral-server/errors"; import { CoralEventPublisherBroker } from "coral-server/events/publisher"; import { Comment } from "coral-server/models/comment"; import { changeDSAReportStatus as changeReportStatus, createDSAReport as createReport, createDSAReportNote as createReportNote, createDSAReportShare as createReportShare, deleteDSAReportNote as deleteReportNote, makeDSAReportDecision as makeReportDecision, retrieveDSAReport, } from "coral-server/models/dsaReport/report"; import { isStoryArchived, retrieveStory } from "coral-server/models/story"; import { Tenant } from "coral-server/models/tenant"; import { rejectComment } from "coral-server/stacks"; import { Request } from "coral-server/types/express"; import { GQLDSAReportDecisionLegality, GQLDSAReportStatus, GQLNOTIFICATION_TYPE, GQLREJECTION_REASON_CODE, } from "coral-server/graph/schema/__generated__/types"; import { I18n } from "../i18n"; import { InternalNotificationContext } from "../notifications/internal/context"; import { AugmentedRedis } from "../redis"; export interface CreateDSAReportInput { commentID: string; userID?: string | null; lawBrokenDescription: string; additionalInformation: string; submissionID?: string; } /** * createDSAReport creates a new DSAReport * @param mongo is the mongo context. * @param tenant is the filtering tenant for this operation. * @param input is the input used for creating the DSAReport * @param now is the time this DSAReport was created * @returns the newly created DSAReport. */ export async function createDSAReport( mongo: MongoContext, tenant: Tenant, input: CreateDSAReportInput, now = new Date() ) { if (input.lawBrokenDescription.length > MAX_DSA_LAW_BROKEN_LENGTH) { throw new DSAReportLawBrokenTooLongError(input.commentID); } if (input.additionalInformation.length > MAX_DSA_ADDITIONAL_INFO_LENGTH) { throw new DSAReportAdditionalInfoTooLongError(input.commentID); } const result = await createReport(mongo, tenant.id, input, now); const { dsaReport } = result; return dsaReport; } export interface AddDSAReportNoteInput { userID: string; body: string; reportID: string; } /** * addDSAReportNote adds a note to the history of a DSAReport * @param mongo is the mongo context. * @param tenant is the filtering tenant for this operation. * @param input is the input used for adding the note * @param now is the time this note was created * @returns the DSAReport with the new note added to its history. */ export async function addDSAReportNote( mongo: MongoContext, tenant: Tenant, input: AddDSAReportNoteInput, now = new Date() ) { const result = await createReportNote(mongo, tenant.id, input, now); const { dsaReport } = result; return dsaReport; } export interface AddDSAReportShareInput { userID: string; reportID: string; } /** * addDSAReportNote adds a share item to the history of a DSAReport * @param mongo is the mongo context. * @param tenant is the filtering tenant for this operation. * @param input is the input used for adding the share item * @param now is the time this DSAReport was shared * @returns the DSAReport with the new share added to its history. */ export async function addDSAReportShare( mongo: MongoContext, tenant: Tenant, input: AddDSAReportShareInput, now = new Date() ) { const result = await createReportShare(mongo, tenant.id, input, now); const { dsaReport } = result; return dsaReport; } export interface DeleteDSAReportNoteInput { id: string; reportID: string; } /** * deleteDSAReportNote deletes a note from the history of a DSAReport * @param mongo is the mongo context. * @param tenant is the filtering tenant for this operation. * @param input is the input used for deleting the note * @returns the DSAReport with the note deleted from is history. */ export async function deleteDSAReportNote( mongo: MongoContext, tenant: Tenant, input: DeleteDSAReportNoteInput, now = new Date() ) { const result = await deleteReportNote(mongo, tenant.id, input); const { dsaReport } = result; return dsaReport; } export interface ChangeDSAReportStatusInput { userID: string; status: GQLDSAReportStatus; reportID: string; } /** * changeDSAReportStatus changes the status of a DSAReport * and also adds the status change to its history * @param mongo is the mongo context. * @param tenant is the filtering tenant for this operation. * @param input is the input used for changing the status * @returns the DSAReport with its new status */ export async function changeDSAReportStatus( mongo: MongoContext, tenant: Tenant, input: ChangeDSAReportStatusInput, now = new Date() ) { const result = await changeReportStatus(mongo, tenant.id, input, now); const { dsaReport } = result; return dsaReport; } export interface MakeDSAReportDecisionInput { commentID: string; commentRevisionID: string; userID: string; reportID: string; legality: GQLDSAReportDecisionLegality; legalGrounds?: string; detailedExplanation?: string; } /** * makeDSAReportDecison makes an illegal vs legal decision for a DSAReport * and also adds the decision to its history * @param mongo is the mongo context. * @param tenant is the filtering tenant for this operation. * @param input is the input used for making the decision * @returns the DSAReport with its decision */ export async function makeDSAReportDecision( mongo: MongoContext, redis: AugmentedRedis, cache: DataCache, config: Config, i18n: I18n, broker: CoralEventPublisherBroker, notifications: InternalNotificationContext, tenant: Tenant, comment: Readonly<Comment> | null, input: MakeDSAReportDecisionInput, req: Request | undefined, now = new Date() ) { const { commentID, commentRevisionID, userID, legalGrounds, detailedExplanation, reportID, } = input; if (!comment) { throw new CommentNotFoundError(commentID); } const story = await retrieveStory(mongo, tenant.id, comment.storyID); if (!story) { throw new StoryNotFoundError(comment.storyID); } const isArchived = isStoryArchived(story); // REJECT if ILLEGAL if (input.legality === GQLDSAReportDecisionLegality.ILLEGAL) { const rejectedComment = await rejectComment( mongo, redis, cache, config, i18n, broker, notifications, tenant, commentID, commentRevisionID, userID, now, { code: GQLREJECTION_REASON_CODE.ILLEGAL_CONTENT, legalGrounds, detailedExplanation, }, reportID, req, false, // set to false because we're about to notify below isArchived ); if (rejectedComment.authorID) { await notifications.create(tenant.id, tenant.locale, { targetUserID: rejectedComment.authorID, type: GQLNOTIFICATION_TYPE.ILLEGAL_REJECTED, comment: rejectedComment, previousStatus: comment.status, legal: { legality: input.legality, grounds: legalGrounds, explanation: detailedExplanation, }, }); } } const report = await retrieveDSAReport(mongo, tenant.id, reportID); if (report && report.userID) { await notifications.create(tenant.id, tenant.locale, { targetUserID: report.userID, type: GQLNOTIFICATION_TYPE.DSA_REPORT_DECISION_MADE, comment, report, legal: { legality: input.legality, grounds: legalGrounds, explanation: detailedExplanation, }, }); } const result = await makeReportDecision(mongo, tenant.id, input, now); const { dsaReport } = result; return dsaReport; } ```
/content/code_sandbox/server/src/core/server/services/dsaReports/reports.ts
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
1,968
```xml /* * Wire * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see path_to_url * */ import React from 'react'; import {TabIndex} from '@wireapp/react-ui-kit/lib/types/enums'; import {Avatar, AVATAR_SIZE} from 'Components/Avatar'; import {UserStatusBadges} from 'Components/UserBadges'; import {Participant} from 'src/script/calling/Participant'; import {useKoSubscribableChildren} from 'Util/ComponentUtil'; import {handleKeyDown} from 'Util/KeyboardUtil'; import {t} from 'Util/LocalizerUtil'; import {setContextMenuPosition} from 'Util/util'; import {CallParticipantItemContent} from './CallParticipantItemContent'; import { callParticipantListItemWrapper, callParticipantListItem, callParticipantAvatar, callParticipantConnecting, } from './CallParticipantsListItem.styles'; import {CallParticipantStatusIcons} from './CallParticipantStatusIcons'; export interface CallParticipantsListItemProps { callParticipant: Participant; showContextMenu: boolean; onContextMenu: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void; isSelfVerified?: boolean; isLast?: boolean; } export const CallParticipantsListItem = ({ callParticipant, isSelfVerified = false, showContextMenu, onContextMenu, isLast = false, }: CallParticipantsListItemProps) => { const {user} = callParticipant; const {isMe: isSelf, isFederated} = user; const {isAudioEstablished} = useKoSubscribableChildren(callParticipant, ['isAudioEstablished']); const { isDirectGuest, is_verified: isVerified, name: userName, isExternal, } = useKoSubscribableChildren(user, ['isDirectGuest', 'is_verified', 'name', 'isExternal']); const handleContextKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => { handleKeyDown(event, () => { const newEvent = setContextMenuPosition(event); onContextMenu?.(newEvent as unknown as React.MouseEvent<HTMLDivElement>); }); }; const reactiveProps = isAudioEstablished && showContextMenu ? { role: 'button', tabIndex: TabIndex.FOCUSABLE, onContextMenu, onClick: onContextMenu, onKeyDown: handleContextKeyDown, } : undefined; return ( <div {...reactiveProps} data-uie-name="item-user" data-uie-value={userName} css={callParticipantListItemWrapper(isLast)} > <div css={callParticipantListItem(true)}> <Avatar avatarSize={AVATAR_SIZE.SMALL} participant={user} aria-hidden="true" css={callParticipantAvatar(isAudioEstablished)} /> <CallParticipantItemContent isAudioEstablished={isAudioEstablished} user={user} isSelf={isSelf} showContextMenu={showContextMenu} onDropdownClick={event => onContextMenu?.(event as unknown as React.MouseEvent<HTMLDivElement>)} /> {isAudioEstablished ? ( <> <UserStatusBadges config={{ guest: isDirectGuest && !isFederated, federated: isFederated, external: isExternal, verified: isSelfVerified && isVerified, }} /> <CallParticipantStatusIcons callParticipant={callParticipant} /> </> ) : ( <span css={callParticipantConnecting}>{t('videoCallParticipantConnecting')}</span> )} </div> </div> ); }; ```
/content/code_sandbox/src/script/components/calling/CallParticipantsListItem/CallParticipantsListItem.tsx
xml
2016-07-21T15:34:05
2024-08-16T11:40:13
wire-webapp
wireapp/wire-webapp
1,125
826
```xml import type * as types from "./types" import * as protocol from "./stdio_protocol" declare const ESBUILD_VERSION: string const quote: (x: string) => string = JSON.stringify const buildLogLevelDefault = 'warning' const transformLogLevelDefault = 'silent' function validateTarget(target: string): string { validateStringValue(target, 'target') if (target.indexOf(',') >= 0) throw new Error(`Invalid target: ${target}`) return target } let canBeAnything = () => null let mustBeBoolean = (value: boolean | undefined): string | null => typeof value === 'boolean' ? null : 'a boolean' let mustBeString = (value: string | undefined): string | null => typeof value === 'string' ? null : 'a string' let mustBeRegExp = (value: RegExp | undefined): string | null => value instanceof RegExp ? null : 'a RegExp object' let mustBeInteger = (value: number | undefined): string | null => typeof value === 'number' && value === (value | 0) ? null : 'an integer' let mustBeFunction = (value: Function | undefined): string | null => typeof value === 'function' ? null : 'a function' let mustBeArray = <T>(value: T[] | undefined): string | null => Array.isArray(value) ? null : 'an array' let mustBeObject = (value: Object | undefined): string | null => typeof value === 'object' && value !== null && !Array.isArray(value) ? null : 'an object' let mustBeEntryPoints = (value: types.BuildOptions['entryPoints']): string | null => typeof value === 'object' && value !== null ? null : 'an array or an object' let mustBeWebAssemblyModule = (value: WebAssembly.Module | undefined): string | null => value instanceof WebAssembly.Module ? null : 'a WebAssembly.Module' let mustBeObjectOrNull = (value: Object | null | undefined): string | null => typeof value === 'object' && !Array.isArray(value) ? null : 'an object or null' let mustBeStringOrBoolean = (value: string | boolean | undefined): string | null => typeof value === 'string' || typeof value === 'boolean' ? null : 'a string or a boolean' let mustBeStringOrObject = (value: string | Object | undefined): string | null => typeof value === 'string' || typeof value === 'object' && value !== null && !Array.isArray(value) ? null : 'a string or an object' let mustBeStringOrArray = (value: string | string[] | undefined): string | null => typeof value === 'string' || Array.isArray(value) ? null : 'a string or an array' let mustBeStringOrUint8Array = (value: string | Uint8Array | undefined): string | null => typeof value === 'string' || value instanceof Uint8Array ? null : 'a string or a Uint8Array' let mustBeStringOrURL = (value: string | URL | undefined): string | null => typeof value === 'string' || value instanceof URL ? null : 'a string or a URL' type OptionKeys = { [key: string]: boolean } function getFlag<T, K extends (keyof T & string)>(object: T, keys: OptionKeys, key: K, mustBeFn: (value: T[K]) => string | null): T[K] | undefined { let value = object[key] keys[key + ''] = true if (value === undefined) return undefined let mustBe = mustBeFn(value) if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`) return value } function checkForInvalidFlags(object: Object, keys: OptionKeys, where: string): void { for (let key in object) { if (!(key in keys)) { throw new Error(`Invalid option ${where}: ${quote(key)}`) } } } export function validateInitializeOptions(options: types.InitializeOptions): types.InitializeOptions { let keys: OptionKeys = Object.create(null) let wasmURL = getFlag(options, keys, 'wasmURL', mustBeStringOrURL) let wasmModule = getFlag(options, keys, 'wasmModule', mustBeWebAssemblyModule) let worker = getFlag(options, keys, 'worker', mustBeBoolean) checkForInvalidFlags(options, keys, 'in initialize() call') return { wasmURL, wasmModule, worker, } } type MangleCache = Record<string, string | false> function validateMangleCache(mangleCache: MangleCache | undefined): MangleCache | undefined { let validated: MangleCache | undefined if (mangleCache !== undefined) { validated = Object.create(null) as MangleCache for (let key in mangleCache) { let value = mangleCache[key] if (typeof value === 'string' || value === false) { validated[key] = value } else { throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`) } } } return validated } type CommonOptions = types.BuildOptions | types.TransformOptions function pushLogFlags(flags: string[], options: CommonOptions, keys: OptionKeys, isTTY: boolean, logLevelDefault: types.LogLevel): void { let color = getFlag(options, keys, 'color', mustBeBoolean) let logLevel = getFlag(options, keys, 'logLevel', mustBeString) let logLimit = getFlag(options, keys, 'logLimit', mustBeInteger) if (color !== void 0) flags.push(`--color=${color}`) else if (isTTY) flags.push(`--color=true`); // This is needed to fix "execFileSync" which buffers stderr flags.push(`--log-level=${logLevel || logLevelDefault}`) flags.push(`--log-limit=${logLimit || 0}`) } function validateStringValue(value: unknown, what: string, key?: string): string { if (typeof value !== 'string') { throw new Error(`Expected value for ${what}${key !== void 0 ? ' ' + quote(key) : ''} to be a string, got ${typeof value} instead`) } return value } function pushCommonFlags(flags: string[], options: CommonOptions, keys: OptionKeys): void { let legalComments = getFlag(options, keys, 'legalComments', mustBeString) let sourceRoot = getFlag(options, keys, 'sourceRoot', mustBeString) let sourcesContent = getFlag(options, keys, 'sourcesContent', mustBeBoolean) let target = getFlag(options, keys, 'target', mustBeStringOrArray) let format = getFlag(options, keys, 'format', mustBeString) let globalName = getFlag(options, keys, 'globalName', mustBeString) let mangleProps = getFlag(options, keys, 'mangleProps', mustBeRegExp) let reserveProps = getFlag(options, keys, 'reserveProps', mustBeRegExp) let mangleQuoted = getFlag(options, keys, 'mangleQuoted', mustBeBoolean) let minify = getFlag(options, keys, 'minify', mustBeBoolean) let minifySyntax = getFlag(options, keys, 'minifySyntax', mustBeBoolean) let minifyWhitespace = getFlag(options, keys, 'minifyWhitespace', mustBeBoolean) let minifyIdentifiers = getFlag(options, keys, 'minifyIdentifiers', mustBeBoolean) let lineLimit = getFlag(options, keys, 'lineLimit', mustBeInteger) let drop = getFlag(options, keys, 'drop', mustBeArray) let dropLabels = getFlag(options, keys, 'dropLabels', mustBeArray) let charset = getFlag(options, keys, 'charset', mustBeString) let treeShaking = getFlag(options, keys, 'treeShaking', mustBeBoolean) let ignoreAnnotations = getFlag(options, keys, 'ignoreAnnotations', mustBeBoolean) let jsx = getFlag(options, keys, 'jsx', mustBeString) let jsxFactory = getFlag(options, keys, 'jsxFactory', mustBeString) let jsxFragment = getFlag(options, keys, 'jsxFragment', mustBeString) let jsxImportSource = getFlag(options, keys, 'jsxImportSource', mustBeString) let jsxDev = getFlag(options, keys, 'jsxDev', mustBeBoolean) let jsxSideEffects = getFlag(options, keys, 'jsxSideEffects', mustBeBoolean) let define = getFlag(options, keys, 'define', mustBeObject) let logOverride = getFlag(options, keys, 'logOverride', mustBeObject) let supported = getFlag(options, keys, 'supported', mustBeObject) let pure = getFlag(options, keys, 'pure', mustBeArray) let keepNames = getFlag(options, keys, 'keepNames', mustBeBoolean) let platform = getFlag(options, keys, 'platform', mustBeString) let tsconfigRaw = getFlag(options, keys, 'tsconfigRaw', mustBeStringOrObject) if (legalComments) flags.push(`--legal-comments=${legalComments}`) if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`) if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`) if (target) { if (Array.isArray(target)) flags.push(`--target=${Array.from(target).map(validateTarget).join(',')}`) else flags.push(`--target=${validateTarget(target)}`) } if (format) flags.push(`--format=${format}`) if (globalName) flags.push(`--global-name=${globalName}`) if (platform) flags.push(`--platform=${platform}`) if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === 'string' ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`) if (minify) flags.push('--minify') if (minifySyntax) flags.push('--minify-syntax') if (minifyWhitespace) flags.push('--minify-whitespace') if (minifyIdentifiers) flags.push('--minify-identifiers') if (lineLimit) flags.push(`--line-limit=${lineLimit}`) if (charset) flags.push(`--charset=${charset}`) if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`) if (ignoreAnnotations) flags.push(`--ignore-annotations`) if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, 'drop')}`) if (dropLabels) flags.push(`--drop-labels=${Array.from(dropLabels).map(what => validateStringValue(what, 'dropLabels')).join(',')}`) if (mangleProps) flags.push(`--mangle-props=${mangleProps.source}`) if (reserveProps) flags.push(`--reserve-props=${reserveProps.source}`) if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`) if (jsx) flags.push(`--jsx=${jsx}`) if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`) if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`) if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`) if (jsxDev) flags.push(`--jsx-dev`) if (jsxSideEffects) flags.push(`--jsx-side-effects`) if (define) { for (let key in define) { if (key.indexOf('=') >= 0) throw new Error(`Invalid define: ${key}`) flags.push(`--define:${key}=${validateStringValue(define[key], 'define', key)}`) } } if (logOverride) { for (let key in logOverride) { if (key.indexOf('=') >= 0) throw new Error(`Invalid log override: ${key}`) flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], 'log override', key)}`) } } if (supported) { for (let key in supported) { if (key.indexOf('=') >= 0) throw new Error(`Invalid supported: ${key}`) const value = supported[key] if (typeof value !== 'boolean') throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`) flags.push(`--supported:${key}=${value}`) } } if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, 'pure')}`) if (keepNames) flags.push(`--keep-names`) } function flagsForBuildOptions( callName: string, options: types.BuildOptions, isTTY: boolean, logLevelDefault: types.LogLevel, writeDefault: boolean, ): { entries: [string, string][], flags: string[], write: boolean, stdinContents: Uint8Array | null, stdinResolveDir: string | null, absWorkingDir: string | undefined, nodePaths: string[], mangleCache: MangleCache | undefined, } { let flags: string[] = [] let entries: [string, string][] = [] let keys: OptionKeys = Object.create(null) let stdinContents: Uint8Array | null = null let stdinResolveDir: string | null = null pushLogFlags(flags, options, keys, isTTY, logLevelDefault) pushCommonFlags(flags, options, keys) let sourcemap = getFlag(options, keys, 'sourcemap', mustBeStringOrBoolean) let bundle = getFlag(options, keys, 'bundle', mustBeBoolean) let splitting = getFlag(options, keys, 'splitting', mustBeBoolean) let preserveSymlinks = getFlag(options, keys, 'preserveSymlinks', mustBeBoolean) let metafile = getFlag(options, keys, 'metafile', mustBeBoolean) let outfile = getFlag(options, keys, 'outfile', mustBeString) let outdir = getFlag(options, keys, 'outdir', mustBeString) let outbase = getFlag(options, keys, 'outbase', mustBeString) let tsconfig = getFlag(options, keys, 'tsconfig', mustBeString) let resolveExtensions = getFlag(options, keys, 'resolveExtensions', mustBeArray) let nodePathsInput = getFlag(options, keys, 'nodePaths', mustBeArray) let mainFields = getFlag(options, keys, 'mainFields', mustBeArray) let conditions = getFlag(options, keys, 'conditions', mustBeArray) let external = getFlag(options, keys, 'external', mustBeArray) let packages = getFlag(options, keys, 'packages', mustBeString) let alias = getFlag(options, keys, 'alias', mustBeObject) let loader = getFlag(options, keys, 'loader', mustBeObject) let outExtension = getFlag(options, keys, 'outExtension', mustBeObject) let publicPath = getFlag(options, keys, 'publicPath', mustBeString) let entryNames = getFlag(options, keys, 'entryNames', mustBeString) let chunkNames = getFlag(options, keys, 'chunkNames', mustBeString) let assetNames = getFlag(options, keys, 'assetNames', mustBeString) let inject = getFlag(options, keys, 'inject', mustBeArray) let banner = getFlag(options, keys, 'banner', mustBeObject) let footer = getFlag(options, keys, 'footer', mustBeObject) let entryPoints = getFlag(options, keys, 'entryPoints', mustBeEntryPoints) let absWorkingDir = getFlag(options, keys, 'absWorkingDir', mustBeString) let stdin = getFlag(options, keys, 'stdin', mustBeObject) let write = getFlag(options, keys, 'write', mustBeBoolean) ?? writeDefault; // Default to true if not specified let allowOverwrite = getFlag(options, keys, 'allowOverwrite', mustBeBoolean) let mangleCache = getFlag(options, keys, 'mangleCache', mustBeObject) keys.plugins = true; // "plugins" has already been read earlier checkForInvalidFlags(options, keys, `in ${callName}() call`) if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? '' : `=${sourcemap}`}`) if (bundle) flags.push('--bundle') if (allowOverwrite) flags.push('--allow-overwrite') if (splitting) flags.push('--splitting') if (preserveSymlinks) flags.push('--preserve-symlinks') if (metafile) flags.push(`--metafile`) if (outfile) flags.push(`--outfile=${outfile}`) if (outdir) flags.push(`--outdir=${outdir}`) if (outbase) flags.push(`--outbase=${outbase}`) if (tsconfig) flags.push(`--tsconfig=${tsconfig}`) if (packages) flags.push(`--packages=${packages}`) if (resolveExtensions) { let values: string[] = [] for (let value of resolveExtensions) { validateStringValue(value, 'resolve extension') if (value.indexOf(',') >= 0) throw new Error(`Invalid resolve extension: ${value}`) values.push(value) } flags.push(`--resolve-extensions=${values.join(',')}`) } if (publicPath) flags.push(`--public-path=${publicPath}`) if (entryNames) flags.push(`--entry-names=${entryNames}`) if (chunkNames) flags.push(`--chunk-names=${chunkNames}`) if (assetNames) flags.push(`--asset-names=${assetNames}`) if (mainFields) { let values: string[] = [] for (let value of mainFields) { validateStringValue(value, 'main field') if (value.indexOf(',') >= 0) throw new Error(`Invalid main field: ${value}`) values.push(value) } flags.push(`--main-fields=${values.join(',')}`) } if (conditions) { let values: string[] = [] for (let value of conditions) { validateStringValue(value, 'condition') if (value.indexOf(',') >= 0) throw new Error(`Invalid condition: ${value}`) values.push(value) } flags.push(`--conditions=${values.join(',')}`) } if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, 'external')}`) if (alias) { for (let old in alias) { if (old.indexOf('=') >= 0) throw new Error(`Invalid package name in alias: ${old}`) flags.push(`--alias:${old}=${validateStringValue(alias[old], 'alias', old)}`) } } if (banner) { for (let type in banner) { if (type.indexOf('=') >= 0) throw new Error(`Invalid banner file type: ${type}`) flags.push(`--banner:${type}=${validateStringValue(banner[type], 'banner', type)}`) } } if (footer) { for (let type in footer) { if (type.indexOf('=') >= 0) throw new Error(`Invalid footer file type: ${type}`) flags.push(`--footer:${type}=${validateStringValue(footer[type], 'footer', type)}`) } } if (inject) for (let path of inject) flags.push(`--inject:${validateStringValue(path, 'inject')}`) if (loader) { for (let ext in loader) { if (ext.indexOf('=') >= 0) throw new Error(`Invalid loader extension: ${ext}`) flags.push(`--loader:${ext}=${validateStringValue(loader[ext], 'loader', ext)}`) } } if (outExtension) { for (let ext in outExtension) { if (ext.indexOf('=') >= 0) throw new Error(`Invalid out extension: ${ext}`) flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], 'out extension', ext)}`) } } if (entryPoints) { if (Array.isArray(entryPoints)) { for (let i = 0, n = entryPoints.length; i < n; i++) { let entryPoint = entryPoints[i] if (typeof entryPoint === 'object' && entryPoint !== null) { let entryPointKeys: OptionKeys = Object.create(null) let input = getFlag(entryPoint, entryPointKeys, 'in', mustBeString) let output = getFlag(entryPoint, entryPointKeys, 'out', mustBeString) checkForInvalidFlags(entryPoint, entryPointKeys, 'in entry point at index ' + i) if (input === undefined) throw new Error('Missing property "in" for entry point at index ' + i) if (output === undefined) throw new Error('Missing property "out" for entry point at index ' + i) entries.push([output, input]) } else { entries.push(['', validateStringValue(entryPoint, 'entry point at index ' + i)]) } } } else { for (let key in entryPoints) { entries.push([key, validateStringValue(entryPoints[key], 'entry point', key)]) } } } if (stdin) { let stdinKeys: OptionKeys = Object.create(null) let contents = getFlag(stdin, stdinKeys, 'contents', mustBeStringOrUint8Array) let resolveDir = getFlag(stdin, stdinKeys, 'resolveDir', mustBeString) let sourcefile = getFlag(stdin, stdinKeys, 'sourcefile', mustBeString) let loader = getFlag(stdin, stdinKeys, 'loader', mustBeString) checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object') if (sourcefile) flags.push(`--sourcefile=${sourcefile}`) if (loader) flags.push(`--loader=${loader}`) if (resolveDir) stdinResolveDir = resolveDir if (typeof contents === 'string') stdinContents = protocol.encodeUTF8(contents) else if (contents instanceof Uint8Array) stdinContents = contents } let nodePaths: string[] = [] if (nodePathsInput) { for (let value of nodePathsInput) { value += '' nodePaths.push(value) } } return { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache: validateMangleCache(mangleCache), } } function flagsForTransformOptions( callName: string, options: types.TransformOptions, isTTY: boolean, logLevelDefault: types.LogLevel, ): { flags: string[], mangleCache: MangleCache | undefined, } { let flags: string[] = [] let keys: OptionKeys = Object.create(null) pushLogFlags(flags, options, keys, isTTY, logLevelDefault) pushCommonFlags(flags, options, keys) let sourcemap = getFlag(options, keys, 'sourcemap', mustBeStringOrBoolean) let sourcefile = getFlag(options, keys, 'sourcefile', mustBeString) let loader = getFlag(options, keys, 'loader', mustBeString) let banner = getFlag(options, keys, 'banner', mustBeString) let footer = getFlag(options, keys, 'footer', mustBeString) let mangleCache = getFlag(options, keys, 'mangleCache', mustBeObject) checkForInvalidFlags(options, keys, `in ${callName}() call`) if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? 'external' : sourcemap}`) if (sourcefile) flags.push(`--sourcefile=${sourcefile}`) if (loader) flags.push(`--loader=${loader}`) if (banner) flags.push(`--banner=${banner}`) if (footer) flags.push(`--footer=${footer}`) return { flags, mangleCache: validateMangleCache(mangleCache), } } export interface StreamIn { writeToStdin: (data: Uint8Array) => void readFileSync?: (path: string, encoding: 'utf8') => string isSync: boolean hasFS: boolean esbuild: types.PluginBuild['esbuild'] } export interface StreamOut { readFromStdout: (data: Uint8Array) => void afterClose: (error: Error | null) => void service: StreamService } export interface StreamFS { writeFile(contents: string | Uint8Array, callback: (path: string | null) => void): void readFile(path: string, callback: (err: Error | null, contents: string | null) => void): void } export interface Refs { ref(): void unref(): void } export interface StreamService { buildOrContext(args: { callName: string, refs: Refs | null, options: types.BuildOptions, isTTY: boolean, defaultWD: string, callback: (err: Error | null, res: types.BuildResult | types.BuildContext | null) => void, }): void transform(args: { callName: string, refs: Refs | null, input: string | Uint8Array, options: types.TransformOptions, isTTY: boolean, fs: StreamFS, callback: (err: Error | null, res: types.TransformResult | null) => void, }): void formatMessages(args: { callName: string, refs: Refs | null, messages: types.PartialMessage[], options: types.FormatMessagesOptions, callback: (err: Error | null, res: string[] | null) => void, }): void analyzeMetafile(args: { callName: string, refs: Refs | null, metafile: string, options: types.AnalyzeMetafileOptions | undefined, callback: (err: Error | null, res: string | null) => void, }): void } type CloseData = { didClose: boolean, reason: string } type RequestCallback = (id: number, request: any) => Promise<void> | void // This can't use any promises in the main execution flow because it must work // for both sync and async code. There is an exception for plugin code because // that can't work in sync code anyway. export function createChannel(streamIn: StreamIn): StreamOut { const requestCallbacksByKey: { [key: number]: { [command: string]: RequestCallback } } = {} const closeData: CloseData = { didClose: false, reason: '' } let responseCallbacks: { [id: number]: (error: string | null, response: protocol.Value) => void } = {} let nextRequestID = 0 let nextBuildKey = 0 // Use a long-lived buffer to store stdout data let stdout = new Uint8Array(16 * 1024) let stdoutUsed = 0 let readFromStdout = (chunk: Uint8Array) => { // Append the chunk to the stdout buffer, growing it as necessary let limit = stdoutUsed + chunk.length if (limit > stdout.length) { let swap = new Uint8Array(limit * 2) swap.set(stdout) stdout = swap } stdout.set(chunk, stdoutUsed) stdoutUsed += chunk.length // Process all complete (i.e. not partial) packets let offset = 0 while (offset + 4 <= stdoutUsed) { let length = protocol.readUInt32LE(stdout, offset) if (offset + 4 + length > stdoutUsed) { break } offset += 4 handleIncomingPacket(stdout.subarray(offset, offset + length)) offset += length } if (offset > 0) { stdout.copyWithin(0, offset, stdoutUsed) stdoutUsed -= offset } } let afterClose = (error: Error | null) => { // When the process is closed, fail all pending requests closeData.didClose = true if (error) closeData.reason = ': ' + (error.message || error) const text = 'The service was stopped' + closeData.reason for (let id in responseCallbacks) { responseCallbacks[id](text, null) } responseCallbacks = {} } let sendRequest = <Req, Res>(refs: Refs | null, value: Req, callback: (error: string | null, response: Res | null) => void): void => { if (closeData.didClose) return callback('The service is no longer running' + closeData.reason, null) let id = nextRequestID++ responseCallbacks[id] = (error, response) => { try { callback(error, response as any) } finally { if (refs) refs.unref() // Do this after the callback so the callback can extend the lifetime if needed } } if (refs) refs.ref() streamIn.writeToStdin(protocol.encodePacket({ id, isRequest: true, value: value as any })) } let sendResponse = (id: number, value: protocol.Value): void => { if (closeData.didClose) throw new Error('The service is no longer running' + closeData.reason) streamIn.writeToStdin(protocol.encodePacket({ id, isRequest: false, value })) } let handleRequest = async (id: number, request: any) => { // Catch exceptions in the code below so they get passed to the caller try { if (request.command === 'ping') { sendResponse(id, {}) return } if (typeof request.key === 'number') { const requestCallbacks = requestCallbacksByKey[request.key] if (!requestCallbacks) { // Ignore invalid commands for old builds that no longer exist. // This can happen when "context.cancel" and "context.dispose" // is called while esbuild is processing many files in parallel. // See path_to_url for details. return } const callback = requestCallbacks[request.command] if (callback) { await callback(id, request) return } } throw new Error(`Invalid command: ` + request.command) } catch (e) { const errors = [extractErrorMessageV8(e, streamIn, null, void 0, '')] try { sendResponse(id, { errors } as any) } catch { // This may fail if the esbuild process is no longer running, but // that's ok. Catch and swallow this exception so that we don't // cause an unhandled promise rejection. Our caller isn't expecting // this call to fail and doesn't handle the promise rejection. } } } let isFirstPacket = true let handleIncomingPacket = (bytes: Uint8Array): void => { // The first packet is a version check if (isFirstPacket) { isFirstPacket = false // Validate the binary's version number to make sure esbuild was installed // correctly. This check was added because some people have reported // errors that appear to indicate an incorrect installation. let binaryVersion = String.fromCharCode(...bytes) if (binaryVersion !== ESBUILD_VERSION) { throw new Error(`Cannot start service: Host version "${ESBUILD_VERSION}" does not match binary version ${quote(binaryVersion)}`) } return } let packet = protocol.decodePacket(bytes) as any if (packet.isRequest) { handleRequest(packet.id, packet.value) } else { let callback = responseCallbacks[packet.id]! delete responseCallbacks[packet.id] if (packet.value.error) callback(packet.value.error, {}) else callback(null, packet.value) } } let buildOrContext: StreamService['buildOrContext'] = ({ callName, refs, options, isTTY, defaultWD, callback }) => { let refCount = 0 const buildKey = nextBuildKey++ const requestCallbacks: { [command: string]: RequestCallback } = {} const buildRefs: Refs = { ref() { if (++refCount === 1) { if (refs) refs.ref() } }, unref() { if (--refCount === 0) { delete requestCallbacksByKey[buildKey] if (refs) refs.unref() } }, } requestCallbacksByKey[buildKey] = requestCallbacks // Guard the whole "build" request with a temporary ref count bump. We // don't want the ref count to be bumped above zero and then back down // to zero before the callback is called. buildRefs.ref() buildOrContextImpl( callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY, defaultWD, (err, res) => { // Now that the initial "build" request is done, we can release our // temporary ref count bump. Any code that wants to extend the life // of the build will have to do so by explicitly retaining a count. try { callback(err, res) } finally { buildRefs.unref() } }, ) } let transform: StreamService['transform'] = ({ callName, refs, input, options, isTTY, fs, callback }) => { const details = createObjectStash() // Ideally the "transform()" API would be faster than calling "build()" // since it doesn't need to touch the file system. However, performance // measurements with large files on macOS indicate that sending the data // over the stdio pipe can be 2x slower than just using a temporary file. // // This appears to be an OS limitation. Both the JavaScript and Go code // are using large buffers but the pipe only writes data in 8kb chunks. // An investigation seems to indicate that this number is hard-coded into // the OS source code. Presumably files are faster because the OS uses // a larger chunk size, or maybe even reads everything in one syscall. // // The cross-over size where this starts to be faster is around 1mb on // my machine. In that case, this code tries to use a temporary file if // possible but falls back to sending the data over the stdio pipe if // that doesn't work. let start = (inputPath: string | null) => { try { if (typeof input !== 'string' && !(input instanceof Uint8Array)) throw new Error('The input to "transform" must be a string or a Uint8Array') let { flags, mangleCache, } = flagsForTransformOptions(callName, options, isTTY, transformLogLevelDefault) let request: protocol.TransformRequest = { command: 'transform', flags, inputFS: inputPath !== null, input: inputPath !== null ? protocol.encodeUTF8(inputPath) : typeof input === 'string' ? protocol.encodeUTF8(input) : input, } if (mangleCache) request.mangleCache = mangleCache sendRequest<protocol.TransformRequest, protocol.TransformResponse>(refs, request, (error, response) => { if (error) return callback(new Error(error), null) let errors = replaceDetailsInMessages(response!.errors, details) let warnings = replaceDetailsInMessages(response!.warnings, details) let outstanding = 1 let next = () => { if (--outstanding === 0) { let result: types.TransformResult = { warnings, code: response!.code, map: response!.map, mangleCache: undefined, legalComments: undefined, } if ('legalComments' in response!) result.legalComments = response?.legalComments if (response!.mangleCache) result.mangleCache = response?.mangleCache callback(null, result) } } if (errors.length > 0) return callback(failureErrorWithLog('Transform failed', errors, warnings), null) // Read the JavaScript file from the file system if (response!.codeFS) { outstanding++ fs.readFile(response!.code, (err, contents) => { if (err !== null) { callback(err, null) } else { response!.code = contents! next() } }) } // Read the source map file from the file system if (response!.mapFS) { outstanding++ fs.readFile(response!.map, (err, contents) => { if (err !== null) { callback(err, null) } else { response!.map = contents! next() } }) } next() }) } catch (e) { let flags: string[] = [] try { pushLogFlags(flags, options, {}, isTTY, transformLogLevelDefault) } catch { } const error = extractErrorMessageV8(e, streamIn, details, void 0, '') sendRequest(refs, { command: 'error', flags, error }, () => { error.detail = details.load(error.detail) callback(failureErrorWithLog('Transform failed', [error], []), null) }) } } if ((typeof input === 'string' || input instanceof Uint8Array) && input.length > 1024 * 1024) { let next = start start = () => fs.writeFile(input, next) } start(null) } let formatMessages: StreamService['formatMessages'] = ({ callName, refs, messages, options, callback }) => { if (!options) throw new Error(`Missing second argument in ${callName}() call`) let keys: OptionKeys = {} let kind = getFlag(options, keys, 'kind', mustBeString) let color = getFlag(options, keys, 'color', mustBeBoolean) let terminalWidth = getFlag(options, keys, 'terminalWidth', mustBeInteger) checkForInvalidFlags(options, keys, `in ${callName}() call`) if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`) if (kind !== 'error' && kind !== 'warning') throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`) let request: protocol.FormatMsgsRequest = { command: 'format-msgs', messages: sanitizeMessages(messages, 'messages', null, '', terminalWidth), isWarning: kind === 'warning', } if (color !== void 0) request.color = color if (terminalWidth !== void 0) request.terminalWidth = terminalWidth sendRequest<protocol.FormatMsgsRequest, protocol.FormatMsgsResponse>(refs, request, (error, response) => { if (error) return callback(new Error(error), null) callback(null, response!.messages) }) } let analyzeMetafile: StreamService['analyzeMetafile'] = ({ callName, refs, metafile, options, callback }) => { if (options === void 0) options = {} let keys: OptionKeys = {} let color = getFlag(options, keys, 'color', mustBeBoolean) let verbose = getFlag(options, keys, 'verbose', mustBeBoolean) checkForInvalidFlags(options, keys, `in ${callName}() call`) let request: protocol.AnalyzeMetafileRequest = { command: 'analyze-metafile', metafile, } if (color !== void 0) request.color = color if (verbose !== void 0) request.verbose = verbose sendRequest<protocol.AnalyzeMetafileRequest, protocol.AnalyzeMetafileResponse>(refs, request, (error, response) => { if (error) return callback(new Error(error), null) callback(null, response!.result) }) } return { readFromStdout, afterClose, service: { buildOrContext, transform, formatMessages, analyzeMetafile, }, } } function buildOrContextImpl( callName: string, buildKey: number, sendRequest: <Req, Res>(refs: Refs | null, value: Req, callback: (error: string | null, response: Res | null) => void) => void, sendResponse: (id: number, value: protocol.Value) => void, refs: Refs, streamIn: StreamIn, requestCallbacks: { [command: string]: RequestCallback }, options: types.BuildOptions, isTTY: boolean, defaultWD: string, callback: (err: Error | null, res: types.BuildResult | types.BuildContext | null) => void, ): void { const details = createObjectStash() const isContext = callName === 'context' const handleError = (e: any, pluginName: string): void => { const flags: string[] = [] try { pushLogFlags(flags, options, {}, isTTY, buildLogLevelDefault) } catch { } const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName) sendRequest(refs, { command: 'error', flags, error: message }, () => { message.detail = details.load(message.detail) callback(failureErrorWithLog(isContext ? 'Context failed' : 'Build failed', [message], []), null) }) } let plugins: types.Plugin[] | undefined if (typeof options === 'object') { const value = options.plugins if (value !== void 0) { if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), '') plugins = value } } if (plugins && plugins.length > 0) { if (streamIn.isSync) return handleError(new Error('Cannot use plugins in synchronous API calls'), '') // Plugins can use async/await because they can't be run with "buildSync" handlePlugins( buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details, ).then( result => { if (!result.ok) return handleError(result.error, result.pluginName) try { buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks) } catch (e) { handleError(e, '') } }, e => handleError(e, ''), ) return } try { buildOrContextContinue(null, (result, done) => done([], []), () => { }) } catch (e) { handleError(e, '') } // "buildOrContext" cannot be written using async/await due to "buildSync" // and must be written in continuation-passing style instead function buildOrContextContinue(requestPlugins: protocol.BuildPlugin[] | null, runOnEndCallbacks: RunOnEndCallbacks, scheduleOnDisposeCallbacks: () => void) { const writeDefault = streamIn.hasFS const { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache, } = flagsForBuildOptions(callName, options, isTTY, buildLogLevelDefault, writeDefault) if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`) // Construct the request const request: protocol.BuildRequest = { command: 'build', key: buildKey, entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir: absWorkingDir || defaultWD, nodePaths, context: isContext, } if (requestPlugins) request.plugins = requestPlugins if (mangleCache) request.mangleCache = mangleCache // Factor out response handling so it can be reused for rebuilds const buildResponseToResult = ( response: protocol.BuildResponse | null, callback: (error: types.BuildFailure | null, result: types.BuildResult | null, onEndErrors: types.Message[], onEndWarnings: types.Message[]) => void, ): void => { const result: types.BuildResult = { errors: replaceDetailsInMessages(response!.errors, details), warnings: replaceDetailsInMessages(response!.warnings, details), outputFiles: undefined, metafile: undefined, mangleCache: undefined, } const originalErrors = result.errors.slice() const originalWarnings = result.warnings.slice() if (response!.outputFiles) result.outputFiles = response!.outputFiles.map(convertOutputFiles) if (response!.metafile) result.metafile = JSON.parse(response!.metafile) if (response!.mangleCache) result.mangleCache = response!.mangleCache if (response!.writeToStdout !== void 0) console.log(protocol.decodeUTF8(response!.writeToStdout).replace(/\n$/, '')) runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => { if (originalErrors.length > 0 || onEndErrors.length > 0) { const error = failureErrorWithLog('Build failed', originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)) return callback(error, null, onEndErrors, onEndWarnings) } callback(null, result, onEndErrors, onEndWarnings) }) } // In context mode, Go runs the "onEnd" callbacks instead of JavaScript let latestResultPromise: Promise<types.BuildResult> | undefined let provideLatestResult: ((error: types.BuildFailure | null, result: types.BuildResult | null) => void) | undefined if (isContext) requestCallbacks['on-end'] = (id, request: protocol.OnEndRequest) => new Promise(resolve => { buildResponseToResult(request, (err, result, onEndErrors, onEndWarnings) => { const response: protocol.OnEndResponse = { errors: onEndErrors, warnings: onEndWarnings, } if (provideLatestResult) provideLatestResult(err, result) latestResultPromise = undefined provideLatestResult = undefined sendResponse(id, response as any) resolve() }) }) sendRequest<protocol.BuildRequest, protocol.BuildResponse>(refs, request, (error, response) => { if (error) return callback(new Error(error), null) if (!isContext) { return buildResponseToResult(response!, (err, res) => { scheduleOnDisposeCallbacks() return callback(err, res) }) } // Construct a context object if (response!.errors.length > 0) { return callback(failureErrorWithLog('Context failed', response!.errors, response!.warnings), null) } let didDispose = false const result: types.BuildContext = { rebuild: () => { if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => { let settlePromise: (() => void) | undefined provideLatestResult = (err, result) => { if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result!) } const triggerAnotherBuild = (): void => { const request: protocol.RebuildRequest = { command: 'rebuild', key: buildKey, } sendRequest<protocol.RebuildRequest, protocol.RebuildResponse>(refs, request, (error, response) => { if (error) { reject(new Error(error)) } else if (settlePromise) { // It's possible to settle the promise that we returned from // this "rebuild()" function earlier than this point. However, // at that point the user could call "rebuild()" again which // would unexpectedly merge with the same build that's still // ongoing. To prevent that, we defer settling the promise // until now when we know that the build has finished. settlePromise() } else { // When we call "rebuild()", we call out to the Go "Rebuild()" // API over IPC. That may trigger a build, but may also "join" // an existing build. At some point the Go code sends us an // "on-end" message with the build result to tell us to run // our "onEnd" plugins. We capture that build result and return // it here. // // However, there's a potential problem: For performance, the // Go code will only send us the result if it's needed, which // only happens if there are "onEnd" callbacks or if "rebuild" // was called. So there's a race where the following things // happen: // // 1. Go starts a rebuild (e.g. due to watch mode) // 2. JS calls "rebuild()" // 3. Go ends the build and starts Go's "OnEnd" callback // 4. Go's "OnEnd" callback sees no need to send the result // 5. JS asks Go to rebuild, which merges with the existing build // 6. Go's existing build ends // 7. The merged build ends, which wakes up JS and ends up here // // In that situation we didn't get an "on-end" message since // Go thought it wasn't necessary. In that situation, we // trigger another rebuild below so that Go will (almost // surely) send us an "on-end" message next time. I suspect // that this is a very rare case, so the performance impact // of building twice shouldn't really matter. It also only // happens when "rebuild()" is used with "watch()" and/or // "serve()". triggerAnotherBuild() } }) } triggerAnotherBuild() }) return latestResultPromise }, watch: (options = {}) => new Promise((resolve, reject) => { if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`) const keys: OptionKeys = {} checkForInvalidFlags(options, keys, `in watch() call`) const request: protocol.WatchRequest = { command: 'watch', key: buildKey, } sendRequest<protocol.WatchRequest, null>(refs, request, error => { if (error) reject(new Error(error)) else resolve(undefined) }) }), serve: (options = {}) => new Promise((resolve, reject) => { if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`) const keys: OptionKeys = {} const port = getFlag(options, keys, 'port', mustBeInteger) const host = getFlag(options, keys, 'host', mustBeString) const servedir = getFlag(options, keys, 'servedir', mustBeString) const keyfile = getFlag(options, keys, 'keyfile', mustBeString) const certfile = getFlag(options, keys, 'certfile', mustBeString) const fallback = getFlag(options, keys, 'fallback', mustBeString) const onRequest = getFlag(options, keys, 'onRequest', mustBeFunction) checkForInvalidFlags(options, keys, `in serve() call`) const request: protocol.ServeRequest = { command: 'serve', key: buildKey, onRequest: !!onRequest, } if (port !== void 0) request.port = port if (host !== void 0) request.host = host if (servedir !== void 0) request.servedir = servedir if (keyfile !== void 0) request.keyfile = keyfile if (certfile !== void 0) request.certfile = certfile if (fallback !== void 0) request.fallback = fallback sendRequest<protocol.ServeRequest, protocol.ServeResponse>(refs, request, (error, response) => { if (error) return reject(new Error(error)) if (onRequest) { requestCallbacks['serve-request'] = (id, request: protocol.OnServeRequest) => { onRequest(request.args) sendResponse(id, {}) } } resolve(response!) }) }), cancel: () => new Promise(resolve => { if (didDispose) return resolve() const request: protocol.CancelRequest = { command: 'cancel', key: buildKey, } sendRequest<protocol.CancelRequest, null>(refs, request, () => { resolve(); // We don't care about errors here }) }), dispose: () => new Promise(resolve => { if (didDispose) return resolve() didDispose = true // Don't dispose more than once const request: protocol.DisposeRequest = { command: 'dispose', key: buildKey, } sendRequest<protocol.DisposeRequest, null>(refs, request, () => { resolve(); // We don't care about errors here scheduleOnDisposeCallbacks() // Only remove the reference here when we know the Go code has seen // this "dispose" call. We don't want to remove any registered // callbacks before that point because the Go code might still be // sending us events. If we remove the reference earlier then we // will return errors for those events, which may end up being // printed to the terminal where the user can see them, which would // be very confusing. refs.unref() }) }), } refs.ref(); // Keep a reference until "dispose" is called callback(null, result) }) } } type RunOnEndCallbacks = (result: types.BuildResult, done: (errors: types.Message[], warnings: types.Message[]) => void) => void let handlePlugins = async ( buildKey: number, sendRequest: <Req, Res>(refs: Refs | null, value: Req, callback: (error: string | null, response: Res | null) => void) => void, sendResponse: (id: number, value: protocol.Value) => void, refs: Refs, streamIn: StreamIn, requestCallbacks: { [command: string]: RequestCallback }, initialOptions: types.BuildOptions, plugins: types.Plugin[], details: ObjectStash, ): Promise< | { ok: true, requestPlugins: protocol.BuildPlugin[], runOnEndCallbacks: RunOnEndCallbacks, scheduleOnDisposeCallbacks: () => void } | { ok: false, error: any, pluginName: string } > => { let onStartCallbacks: { name: string, note: () => types.Note | undefined, callback: () => (types.OnStartResult | null | void | Promise<types.OnStartResult | null | void>), }[] = [] let onEndCallbacks: { name: string, note: () => types.Note | undefined, callback: (result: types.BuildResult) => (types.OnEndResult | null | void | Promise<types.OnEndResult | null | void>), }[] = [] let onResolveCallbacks: { [id: number]: { name: string, note: () => types.Note | undefined, callback: (args: types.OnResolveArgs) => (types.OnResolveResult | null | undefined | Promise<types.OnResolveResult | null | undefined>), }, } = {} let onLoadCallbacks: { [id: number]: { name: string, note: () => types.Note | undefined, callback: (args: types.OnLoadArgs) => (types.OnLoadResult | null | undefined | Promise<types.OnLoadResult | null | undefined>), }, } = {} let onDisposeCallbacks: (() => void)[] = [] let nextCallbackID = 0 let i = 0 let requestPlugins: protocol.BuildPlugin[] = [] let isSetupDone = false // Clone the plugin array to guard against mutation during iteration plugins = [...plugins] for (let item of plugins) { let keys: OptionKeys = {} if (typeof item !== 'object') throw new Error(`Plugin at index ${i} must be an object`) const name = getFlag(item, keys, 'name', mustBeString) if (typeof name !== 'string' || name === '') throw new Error(`Plugin at index ${i} is missing a name`) try { let setup = getFlag(item, keys, 'setup', mustBeFunction) if (typeof setup !== 'function') throw new Error(`Plugin is missing a setup function`) checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`) let plugin: protocol.BuildPlugin = { name, onStart: false, onEnd: false, onResolve: [], onLoad: [], } i++ let resolve = (path: string, options: types.ResolveOptions = {}): Promise<types.ResolveResult> => { if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed') if (typeof path !== 'string') throw new Error(`The path to resolve must be a string`) let keys: OptionKeys = Object.create(null) let pluginName = getFlag(options, keys, 'pluginName', mustBeString) let importer = getFlag(options, keys, 'importer', mustBeString) let namespace = getFlag(options, keys, 'namespace', mustBeString) let resolveDir = getFlag(options, keys, 'resolveDir', mustBeString) let kind = getFlag(options, keys, 'kind', mustBeString) let pluginData = getFlag(options, keys, 'pluginData', canBeAnything) let importAttributes = getFlag(options, keys, 'with', mustBeObject) checkForInvalidFlags(options, keys, 'in resolve() call') return new Promise((resolve, reject) => { const request: protocol.ResolveRequest = { command: 'resolve', path, key: buildKey, pluginName: name, } if (pluginName != null) request.pluginName = pluginName if (importer != null) request.importer = importer if (namespace != null) request.namespace = namespace if (resolveDir != null) request.resolveDir = resolveDir if (kind != null) request.kind = kind else throw new Error(`Must specify "kind" when calling "resolve"`) if (pluginData != null) request.pluginData = details.store(pluginData) if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, 'with') sendRequest<protocol.ResolveRequest, protocol.ResolveResponse>(refs, request, (error, response) => { if (error !== null) reject(new Error(error)) else resolve({ errors: replaceDetailsInMessages(response!.errors, details), warnings: replaceDetailsInMessages(response!.warnings, details), path: response!.path, external: response!.external, sideEffects: response!.sideEffects, namespace: response!.namespace, suffix: response!.suffix, pluginData: details.load(response!.pluginData), }) }) }) } let promise = setup({ initialOptions, resolve, onStart(callback) { let registeredText = `This error came from the "onStart" callback registered here:` let registeredNote = extractCallerV8(new Error(registeredText), streamIn, 'onStart') onStartCallbacks.push({ name: name!, callback, note: registeredNote }) plugin.onStart = true }, onEnd(callback) { let registeredText = `This error came from the "onEnd" callback registered here:` let registeredNote = extractCallerV8(new Error(registeredText), streamIn, 'onEnd') onEndCallbacks.push({ name: name!, callback, note: registeredNote }) plugin.onEnd = true }, onResolve(options, callback) { let registeredText = `This error came from the "onResolve" callback registered here:` let registeredNote = extractCallerV8(new Error(registeredText), streamIn, 'onResolve') let keys: OptionKeys = {} let filter = getFlag(options, keys, 'filter', mustBeRegExp) let namespace = getFlag(options, keys, 'namespace', mustBeString) checkForInvalidFlags(options, keys, `in onResolve() call for plugin ${quote(name)}`) if (filter == null) throw new Error(`onResolve() call is missing a filter`) let id = nextCallbackID++ onResolveCallbacks[id] = { name: name!, callback, note: registeredNote } plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || '' }) }, onLoad(options, callback) { let registeredText = `This error came from the "onLoad" callback registered here:` let registeredNote = extractCallerV8(new Error(registeredText), streamIn, 'onLoad') let keys: OptionKeys = {} let filter = getFlag(options, keys, 'filter', mustBeRegExp) let namespace = getFlag(options, keys, 'namespace', mustBeString) checkForInvalidFlags(options, keys, `in onLoad() call for plugin ${quote(name)}`) if (filter == null) throw new Error(`onLoad() call is missing a filter`) let id = nextCallbackID++ onLoadCallbacks[id] = { name: name!, callback, note: registeredNote } plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || '' }) }, onDispose(callback) { onDisposeCallbacks.push(callback) }, esbuild: streamIn.esbuild, }) // Await a returned promise if there was one. This allows plugins to do // some asynchronous setup while still retaining the ability to modify // the build options. This deliberately serializes asynchronous plugin // setup instead of running them concurrently so that build option // modifications are easier to reason about. if (promise) await promise requestPlugins.push(plugin) } catch (e) { return { ok: false, error: e, pluginName: name } } } requestCallbacks['on-start'] = async (id, request: protocol.OnStartRequest) => { // Reset the "pluginData" map before each new build to avoid a memory leak. // This is done before each new build begins instead of after each build ends // because I believe the current API doesn't restrict when you can call // "resolve" and there may be some uses of it that call it around when the // build ends, and we don't want to accidentally break those use cases. details.clear() let response: protocol.OnStartResponse = { errors: [], warnings: [] } await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => { try { let result = await callback() if (result != null) { if (typeof result !== 'object') throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`) let keys: OptionKeys = {} let errors = getFlag(result, keys, 'errors', mustBeArray) let warnings = getFlag(result, keys, 'warnings', mustBeArray) checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`) if (errors != null) response.errors!.push(...sanitizeMessages(errors, 'errors', details, name, undefined)) if (warnings != null) response.warnings!.push(...sanitizeMessages(warnings, 'warnings', details, name, undefined)) } } catch (e) { response.errors!.push(extractErrorMessageV8(e, streamIn, details, note && note(), name)) } })) sendResponse(id, response as any) } requestCallbacks['on-resolve'] = async (id, request: protocol.OnResolveRequest) => { let response: protocol.OnResolveResponse = {}, name = '', callback, note for (let id of request.ids) { try { ({ name, callback, note } = onResolveCallbacks[id]) let result = await callback({ path: request.path, importer: request.importer, namespace: request.namespace, resolveDir: request.resolveDir, kind: request.kind, pluginData: details.load(request.pluginData), with: request.with, }) if (result != null) { if (typeof result !== 'object') throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`) let keys: OptionKeys = {} let pluginName = getFlag(result, keys, 'pluginName', mustBeString) let path = getFlag(result, keys, 'path', mustBeString) let namespace = getFlag(result, keys, 'namespace', mustBeString) let suffix = getFlag(result, keys, 'suffix', mustBeString) let external = getFlag(result, keys, 'external', mustBeBoolean) let sideEffects = getFlag(result, keys, 'sideEffects', mustBeBoolean) let pluginData = getFlag(result, keys, 'pluginData', canBeAnything) let errors = getFlag(result, keys, 'errors', mustBeArray) let warnings = getFlag(result, keys, 'warnings', mustBeArray) let watchFiles = getFlag(result, keys, 'watchFiles', mustBeArray) let watchDirs = getFlag(result, keys, 'watchDirs', mustBeArray) checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`) response.id = id if (pluginName != null) response.pluginName = pluginName if (path != null) response.path = path if (namespace != null) response.namespace = namespace if (suffix != null) response.suffix = suffix if (external != null) response.external = external if (sideEffects != null) response.sideEffects = sideEffects if (pluginData != null) response.pluginData = details.store(pluginData) if (errors != null) response.errors = sanitizeMessages(errors, 'errors', details, name, undefined) if (warnings != null) response.warnings = sanitizeMessages(warnings, 'warnings', details, name, undefined) if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, 'watchFiles') if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, 'watchDirs') break } } catch (e) { response = { id, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] } break } } sendResponse(id, response as any) } requestCallbacks['on-load'] = async (id, request: protocol.OnLoadRequest) => { let response: protocol.OnLoadResponse = {}, name = '', callback, note for (let id of request.ids) { try { ({ name, callback, note } = onLoadCallbacks[id]) let result = await callback({ path: request.path, namespace: request.namespace, suffix: request.suffix, pluginData: details.load(request.pluginData), with: request.with, }) if (result != null) { if (typeof result !== 'object') throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`) let keys: OptionKeys = {} let pluginName = getFlag(result, keys, 'pluginName', mustBeString) let contents = getFlag(result, keys, 'contents', mustBeStringOrUint8Array) let resolveDir = getFlag(result, keys, 'resolveDir', mustBeString) let pluginData = getFlag(result, keys, 'pluginData', canBeAnything) let loader = getFlag(result, keys, 'loader', mustBeString) let errors = getFlag(result, keys, 'errors', mustBeArray) let warnings = getFlag(result, keys, 'warnings', mustBeArray) let watchFiles = getFlag(result, keys, 'watchFiles', mustBeArray) let watchDirs = getFlag(result, keys, 'watchDirs', mustBeArray) checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`) response.id = id if (pluginName != null) response.pluginName = pluginName if (contents instanceof Uint8Array) response.contents = contents else if (contents != null) response.contents = protocol.encodeUTF8(contents) if (resolveDir != null) response.resolveDir = resolveDir if (pluginData != null) response.pluginData = details.store(pluginData) if (loader != null) response.loader = loader if (errors != null) response.errors = sanitizeMessages(errors, 'errors', details, name, undefined) if (warnings != null) response.warnings = sanitizeMessages(warnings, 'warnings', details, name, undefined) if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, 'watchFiles') if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, 'watchDirs') break } } catch (e) { response = { id, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] } break } } sendResponse(id, response as any) } let runOnEndCallbacks: RunOnEndCallbacks = (result, done) => done([], []) if (onEndCallbacks.length > 0) { runOnEndCallbacks = (result, done) => { (async () => { const onEndErrors: types.Message[] = [] const onEndWarnings: types.Message[] = [] for (const { name, callback, note } of onEndCallbacks) { let newErrors: types.Message[] | undefined let newWarnings: types.Message[] | undefined try { const value = await callback(result) if (value != null) { if (typeof value !== 'object') throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`) let keys: OptionKeys = {} let errors = getFlag(value, keys, 'errors', mustBeArray) let warnings = getFlag(value, keys, 'warnings', mustBeArray) checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`) if (errors != null) newErrors = sanitizeMessages(errors, 'errors', details, name, undefined) if (warnings != null) newWarnings = sanitizeMessages(warnings, 'warnings', details, name, undefined) } } catch (e) { newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)] } // Try adding the errors and warnings to the result object, but // continue if something goes wrong. If error-reporting has errors // then nothing can help us... if (newErrors) { onEndErrors.push(...newErrors) try { result.errors.push(...newErrors) } catch { } } if (newWarnings) { onEndWarnings.push(...newWarnings) try { result.warnings.push(...newWarnings) } catch { } } } done(onEndErrors, onEndWarnings) })() } } let scheduleOnDisposeCallbacks = (): void => { // Run each "onDispose" callback with its own call stack for (const cb of onDisposeCallbacks) { setTimeout(() => cb(), 0) } } isSetupDone = true return { ok: true, requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks, } } // This stores JavaScript objects on the JavaScript side and temporarily // substitutes them with an integer that can be passed through the Go side // and back. That way we can associate JavaScript objects with Go objects // even if the JavaScript objects aren't serializable. And we also avoid // the overhead of serializing large JavaScript objects. interface ObjectStash { clear(): void load(id: number): any store(value: any): number } function createObjectStash(): ObjectStash { const map = new Map<number, any>() let nextID = 0 return { clear() { map.clear() }, load(id) { return map.get(id) }, store(value) { if (value === void 0) return -1 const id = nextID++ map.set(id, value) return id }, } } function extractCallerV8(e: Error, streamIn: StreamIn, ident: string): () => types.Note | undefined { let note: types.Note | undefined let tried = false return () => { if (tried) return note tried = true try { let lines = (e.stack + '').split('\n') lines.splice(1, 1) let location = parseStackLinesV8(streamIn, lines, ident) if (location) { note = { text: e.message, location } return note } } catch { } } } function extractErrorMessageV8(e: any, streamIn: StreamIn, stash: ObjectStash | null, note: types.Note | undefined, pluginName: string): types.Message { let text = 'Internal error' let location: types.Location | null = null try { text = ((e && e.message) || e) + '' } catch { } // Optionally attempt to extract the file from the stack trace, works in V8/node try { location = parseStackLinesV8(streamIn, (e.stack + '').split('\n'), '') } catch { } return { id: '', pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 } } function parseStackLinesV8(streamIn: StreamIn, lines: string[], ident: string): types.Location | null { let at = ' at ' // Check to see if this looks like a V8 stack trace if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) { for (let i = 1; i < lines.length; i++) { let line = lines[i] if (!line.startsWith(at)) continue line = line.slice(at.length) while (true) { // Unwrap a function name let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line) if (match) { line = match[1] continue } // Unwrap an eval wrapper match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line) if (match) { line = match[1] continue } // Match on the file location match = /^(\S+):(\d+):(\d+)$/.exec(line) if (match) { let contents try { contents = streamIn.readFileSync(match[1], 'utf8') } catch { break } let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || '' let column = +match[3] - 1 let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0 return { file: match[1], namespace: 'file', line: +match[2], column: protocol.encodeUTF8(lineText.slice(0, column)).length, length: protocol.encodeUTF8(lineText.slice(column, column + length)).length, lineText: lineText + '\n' + lines.slice(1).join('\n'), suggestion: '', } } break } } } return null } function failureErrorWithLog(text: string, errors: types.Message[], warnings: types.Message[]): types.BuildFailure { let limit = 5 text += errors.length < 1 ? '' : ` with ${errors.length} error${errors.length < 2 ? '' : 's'}:` + errors.slice(0, limit + 1).map((e, i) => { if (i === limit) return '\n...' if (!e.location) return `\nerror: ${e.text}` let { file, line, column } = e.location let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : '' return `\n${file}:${line}:${column}: ERROR: ${pluginText}${e.text}` }).join('') let error: any = new Error(text) // Use a getter instead of a plain property so that when the error is thrown // without being caught and the node process exits, the error objects aren't // printed. The error objects are pretty big and not helpful because a) esbuild // already prints errors to stderr by default and b) the error summary already // has a more helpful abbreviated form of the error messages. for (const [key, value] of [['errors', errors], ['warnings', warnings]] as const) { Object.defineProperty(error, key, { configurable: true, enumerable: true, get: () => value, set: value => Object.defineProperty(error, key, { configurable: true, enumerable: true, value, }), }) } return error } function replaceDetailsInMessages(messages: types.Message[], stash: ObjectStash): types.Message[] { for (const message of messages) { message.detail = stash.load(message.detail) } return messages } function sanitizeLocation(location: types.PartialMessage['location'], where: string, terminalWidth: number | undefined): types.Message['location'] { if (location == null) return null let keys: OptionKeys = {} let file = getFlag(location, keys, 'file', mustBeString) let namespace = getFlag(location, keys, 'namespace', mustBeString) let line = getFlag(location, keys, 'line', mustBeInteger) let column = getFlag(location, keys, 'column', mustBeInteger) let length = getFlag(location, keys, 'length', mustBeInteger) let lineText = getFlag(location, keys, 'lineText', mustBeString) let suggestion = getFlag(location, keys, 'suggestion', mustBeString) checkForInvalidFlags(location, keys, where) // Performance hack: Some people pass enormous minified files as the line // text with a column near the beginning of the line and then complain // when this function is slow. The slowness comes from serializing a huge // string. But the vast majority of that string is unnecessary. Try to // detect when this is the case and trim the string before serialization // to avoid the performance hit. See: path_to_url if (lineText) { // Try to conservatively guess the maximum amount of relevant text const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)) // Make sure it's ASCII (so the byte-oriented column and length values // are correct) and that there are no newlines (so that our logging code // doesn't look at the end of the string) if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) { lineText = relevantASCII } } // Note: We could technically make this even faster by maintaining two copies // of this code, one in Go and one in TypeScript. But I'm not going to do that. // The point of this function is to call into the real Go code to get what it // does. If someone wants a JS version, they can port it themselves. return { file: file || '', namespace: namespace || '', line: line || 0, column: column || 0, length: length || 0, lineText: lineText || '', suggestion: suggestion || '', } } function sanitizeMessages( messages: types.PartialMessage[], property: string, stash: ObjectStash | null, fallbackPluginName: string, terminalWidth: number | undefined, ): types.Message[] { let messagesClone: types.Message[] = [] let index = 0 for (const message of messages) { let keys: OptionKeys = {} let id = getFlag(message, keys, 'id', mustBeString) let pluginName = getFlag(message, keys, 'pluginName', mustBeString) let text = getFlag(message, keys, 'text', mustBeString) let location = getFlag(message, keys, 'location', mustBeObjectOrNull) let notes = getFlag(message, keys, 'notes', mustBeArray) let detail = getFlag(message, keys, 'detail', canBeAnything) let where = `in element ${index} of "${property}"` checkForInvalidFlags(message, keys, where) let notesClone: types.Note[] = [] if (notes) { for (const note of notes) { let noteKeys: OptionKeys = {} let noteText = getFlag(note, noteKeys, 'text', mustBeString) let noteLocation = getFlag(note, noteKeys, 'location', mustBeObjectOrNull) checkForInvalidFlags(note, noteKeys, where) notesClone.push({ text: noteText || '', location: sanitizeLocation(noteLocation, where, terminalWidth), }) } } messagesClone.push({ id: id || '', pluginName: pluginName || fallbackPluginName, text: text || '', location: sanitizeLocation(location, where, terminalWidth), notes: notesClone, detail: stash ? stash.store(detail) : -1, }) index++ } return messagesClone } function sanitizeStringArray(values: any[], property: string): string[] { const result: string[] = [] for (const value of values) { if (typeof value !== 'string') throw new Error(`${quote(property)} must be an array of strings`) result.push(value) } return result } function sanitizeStringMap(map: Record<string, any>, property: string): Record<string, string> { const result: Record<string, string> = Object.create(null) for (const key in map) { const value = map[key] if (typeof value !== 'string') throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`) result[key] = value } return result } function convertOutputFiles({ path, contents, hash }: protocol.BuildOutputFile): types.OutputFile { // The text is lazily-generated for performance reasons. If no one asks for // it, then it never needs to be generated. let text: string | null = null return { path, contents, hash, get text() { // People want to be able to set "contents" and have esbuild automatically // derive "text" for them, so grab the contents off of this object instead // of using our original value. const binary = this.contents // This deliberately doesn't do bidirectional derivation because that could // result in the inefficiency. For example, if we did do this and then you // set "contents" and "text" and then asked for "contents", the second // setter for "text" will have erased our cached "contents" value so we'd // need to regenerate it again. Instead, "contents" is unambiguously the // primary value and "text" is unambiguously the derived value. if (text === null || binary !== contents) { contents = binary text = protocol.decodeUTF8(binary) } return text }, } } ```
/content/code_sandbox/lib/shared/common.ts
xml
2016-06-14T16:08:50
2024-08-16T20:02:02
esbuild
evanw/esbuild
37,820
18,597
```xml import "../../src/index.js"; ```
/content/code_sandbox/packages/specs/schema/test/helpers/setup.ts
xml
2016-02-21T18:38:47
2024-08-14T21:19:48
tsed
tsedio/tsed
2,817
7
```xml <RelativeLayout xmlns:android="path_to_url" android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:padding="6dip" > <TextView android:id="@+id/message_topic_text" android:layout_width="fill_parent" android:layout_height="26dip" android:ellipsize="marquee" android:text="@string/message_topic" android:textSize="12sp" android:layout_below="@+id/message_text" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:maxLines="1" /> <TextView android:id="@+id/message_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_alignWithParentIfMissing="true" android:gravity="center_vertical" android:text="@string/placeholder_example" android:textSize="16sp" /> <TextView android:layout_width="100dip" android:layout_height="26dip" android:text="@string/message_time" android:id="@+id/message_date_text" android:textSize="12sp" android:layout_below="@+id/message_text" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> </RelativeLayout> ```
/content/code_sandbox/org.eclipse.paho.android.sample/src/main/res/layout/message_list_item.xml
xml
2016-02-19T15:44:50
2024-08-15T08:21:05
paho.mqtt.android
eclipse/paho.mqtt.android
2,902
317
```xml <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>true</ImplicitUsings> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.SyndicationFeed.ReaderWriter" Version="1.0.2" /> </ItemGroup> </Project> ```
/content/code_sandbox/projects/mvc/output-formatter-syndication/output-formatter-syndication.csproj
xml
2016-07-27T08:23:40
2024-08-16T19:15:21
practical-aspnetcore
dodyg/practical-aspnetcore
9,106
81
```xml import type { RxDocumentData, RxJsonSchema } from '../../types/index.d.ts'; import type { DocWithIndexString, MemoryStorageInternals, MemoryStorageInternalsByIndex } from './memory-types.ts'; import type { RxStorageInstanceMemory } from './rx-storage-instance-memory.ts'; export declare function getMemoryCollectionKey(databaseName: string, collectionName: string, schemaVersion: number): string; export declare function ensureNotRemoved(instance: RxStorageInstanceMemory<any>): void; export declare function attachmentMapKey(documentId: string, attachmentId: string): string; /** * @hotPath */ export declare function putWriteRowToState<RxDocType>(docId: string, state: MemoryStorageInternals<RxDocType>, stateByIndex: MemoryStorageInternalsByIndex<RxDocType>[], document: RxDocumentData<RxDocType>, docInState?: RxDocumentData<RxDocType>): void; export declare function removeDocFromState<RxDocType>(primaryPath: string, schema: RxJsonSchema<RxDocumentData<RxDocType>>, state: MemoryStorageInternals<RxDocType>, doc: RxDocumentData<RxDocType>): void; export declare function compareDocsWithIndex<RxDocType>(a: DocWithIndexString<RxDocType>, b: DocWithIndexString<RxDocType>): 1 | 0 | -1; ```
/content/code_sandbox/dist/types/plugins/storage-memory/memory-helper.d.ts
xml
2016-12-02T19:34:42
2024-08-16T15:47:20
rxdb
pubkey/rxdb
21,054
292
```xml import { FakeAccountService, mockAccountServiceWith, } from "@bitwarden/common/../spec/fake-account-service"; import { FakeActiveUserState } from "@bitwarden/common/../spec/fake-state"; import { FakeStateProvider } from "@bitwarden/common/../spec/fake-state-provider"; import { mock, MockProxy } from "jest-mock-extended"; import { firstValueFrom, ReplaySubject } from "rxjs"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; import { PolicyType } from "@bitwarden/common/admin-console/enums"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { UserId } from "@bitwarden/common/types/guid"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { CollectionService } from "@bitwarden/common/vault/abstractions/collection.service"; import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { CollectionView } from "@bitwarden/common/vault/models/view/collection.view"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; import { COLLAPSED_GROUPINGS } from "@bitwarden/common/vault/services/key-state/collapsed-groupings.state"; import { VaultFilterService } from "./vault-filter.service"; describe("vault filter service", () => { let vaultFilterService: VaultFilterService; let organizationService: MockProxy<OrganizationService>; let folderService: MockProxy<FolderService>; let cipherService: MockProxy<CipherService>; let policyService: MockProxy<PolicyService>; let i18nService: MockProxy<I18nService>; let collectionService: MockProxy<CollectionService>; let organizations: ReplaySubject<Organization[]>; let folderViews: ReplaySubject<FolderView[]>; let collectionViews: ReplaySubject<CollectionView[]>; let personalOwnershipPolicy: ReplaySubject<boolean>; let singleOrgPolicy: ReplaySubject<boolean>; let stateProvider: FakeStateProvider; const mockUserId = Utils.newGuid() as UserId; let accountService: FakeAccountService; let collapsedGroupingsState: FakeActiveUserState<string[]>; beforeEach(() => { organizationService = mock<OrganizationService>(); folderService = mock<FolderService>(); cipherService = mock<CipherService>(); policyService = mock<PolicyService>(); i18nService = mock<I18nService>(); accountService = mockAccountServiceWith(mockUserId); stateProvider = new FakeStateProvider(accountService); i18nService.collator = new Intl.Collator("en-US"); collectionService = mock<CollectionService>(); organizations = new ReplaySubject<Organization[]>(1); folderViews = new ReplaySubject<FolderView[]>(1); collectionViews = new ReplaySubject<CollectionView[]>(1); personalOwnershipPolicy = new ReplaySubject<boolean>(1); singleOrgPolicy = new ReplaySubject<boolean>(1); organizationService.memberOrganizations$ = organizations; folderService.folderViews$ = folderViews; collectionService.decryptedCollections$ = collectionViews; policyService.policyAppliesToActiveUser$ .calledWith(PolicyType.PersonalOwnership) .mockReturnValue(personalOwnershipPolicy); policyService.policyAppliesToActiveUser$ .calledWith(PolicyType.SingleOrg) .mockReturnValue(singleOrgPolicy); vaultFilterService = new VaultFilterService( organizationService, folderService, cipherService, policyService, i18nService, stateProvider, collectionService, ); collapsedGroupingsState = stateProvider.activeUser.getFake(COLLAPSED_GROUPINGS); }); describe("collapsed filter nodes", () => { const nodes = new Set(["1", "2"]); it("should update the collapsedFilterNodes$", async () => { await vaultFilterService.setCollapsedFilterNodes(nodes); const collapsedGroupingsState = stateProvider.activeUser.getFake(COLLAPSED_GROUPINGS); expect(await firstValueFrom(collapsedGroupingsState.state$)).toEqual(Array.from(nodes)); expect(collapsedGroupingsState.nextMock).toHaveBeenCalledWith([ mockUserId, Array.from(nodes), ]); }); it("loads from state on initialization", async () => { collapsedGroupingsState.nextState(["1", "2"]); await expect(firstValueFrom(vaultFilterService.collapsedFilterNodes$)).resolves.toEqual( nodes, ); }); }); describe("organizations", () => { beforeEach(() => { const storedOrgs = [createOrganization("1", "org1"), createOrganization("2", "org2")]; organizations.next(storedOrgs); personalOwnershipPolicy.next(false); singleOrgPolicy.next(false); }); it("returns a nested tree", async () => { const tree = await firstValueFrom(vaultFilterService.organizationTree$); expect(tree.children.length).toBe(3); expect(tree.children.find((o) => o.node.name === "org1")); expect(tree.children.find((o) => o.node.name === "org2")); }); it("hides My Vault if personal ownership policy is enabled", async () => { personalOwnershipPolicy.next(true); const tree = await firstValueFrom(vaultFilterService.organizationTree$); expect(tree.children.length).toBe(2); expect(!tree.children.find((o) => o.node.id === "MyVault")); }); it("returns 1 organization and My Vault if single organization policy is enabled", async () => { singleOrgPolicy.next(true); const tree = await firstValueFrom(vaultFilterService.organizationTree$); expect(tree.children.length).toBe(2); expect(tree.children.find((o) => o.node.name === "org1")); expect(tree.children.find((o) => o.node.id === "MyVault")); }); it("returns 1 organization if both single organization and personal ownership policies are enabled", async () => { singleOrgPolicy.next(true); personalOwnershipPolicy.next(true); const tree = await firstValueFrom(vaultFilterService.organizationTree$); expect(tree.children.length).toBe(1); expect(tree.children.find((o) => o.node.name === "org1")); }); }); describe("folders", () => { describe("filtered folders with organization", () => { beforeEach(() => { // Org must be updated before folderService else the subscription uses the null org default value vaultFilterService.setOrganizationFilter(createOrganization("org test id", "Test Org")); }); it("returns folders filtered by current organization", async () => { const storedCiphers = [ createCipherView("1", "org test id", "folder test id"), createCipherView("2", "non matching org id", "non matching folder id"), ]; cipherService.getAllDecrypted.mockResolvedValue(storedCiphers); const storedFolders = [ createFolderView("folder test id", "test"), createFolderView("non matching folder id", "test2"), ]; folderViews.next(storedFolders); await expect(firstValueFrom(vaultFilterService.filteredFolders$)).resolves.toEqual([ createFolderView("folder test id", "test"), ]); }); it("returns current organization", () => { vaultFilterService.getOrganizationFilter().subscribe((org) => { expect(org.id).toEqual("org test id"); expect(org.identifier).toEqual("Test Org"); }); }); }); describe("folder tree", () => { it("returns a nested tree", async () => { const storedFolders = [ createFolderView("Folder 1 Id", "Folder 1"), createFolderView("Folder 2 Id", "Folder 1/Folder 2"), createFolderView("Folder 3 Id", "Folder 1/Folder 3"), ]; folderViews.next(storedFolders); const result = await firstValueFrom(vaultFilterService.folderTree$); expect(result.children[0].node.id === "Folder 1 Id"); expect(result.children[0].children.find((c) => c.node.id === "Folder 2 Id")); expect(result.children[0].children.find((c) => c.node.id === "Folder 3 Id")); }, 10000); }); }); describe("collections", () => { describe("filtered collections", () => { it("returns collections filtered by current organization", async () => { vaultFilterService.setOrganizationFilter(createOrganization("org test id", "Test Org")); const storedCollections = [ createCollectionView("1", "collection 1", "org test id"), createCollectionView("2", "collection 2", "non matching org id"), ]; collectionViews.next(storedCollections); await expect(firstValueFrom(vaultFilterService.filteredCollections$)).resolves.toEqual([ createCollectionView("1", "collection 1", "org test id"), ]); }); }); describe("collection tree", () => { it("returns tree with children", async () => { const storedCollections = [ createCollectionView("id-1", "Collection 1", "org test id"), createCollectionView("id-2", "Collection 1/Collection 2", "org test id"), createCollectionView("id-3", "Collection 1/Collection 3", "org test id"), ]; collectionViews.next(storedCollections); const result = await firstValueFrom(vaultFilterService.collectionTree$); expect(result.children.map((c) => c.node.id)).toEqual(["id-1"]); expect(result.children[0].children.map((c) => c.node.id)).toEqual(["id-2", "id-3"]); }); it("returns tree where non-existing collections are excluded from children", async () => { const storedCollections = [ createCollectionView("id-1", "Collection 1", "org test id"), createCollectionView("id-3", "Collection 1/Collection 2/Collection 3", "org test id"), ]; collectionViews.next(storedCollections); const result = await firstValueFrom(vaultFilterService.collectionTree$); expect(result.children.map((c) => c.node.id)).toEqual(["id-1"]); expect(result.children[0].children.map((c) => c.node.id)).toEqual(["id-3"]); expect(result.children[0].children[0].node.name).toBe("Collection 2/Collection 3"); }); it("returns tree with parents", async () => { const storedCollections = [ createCollectionView("id-1", "Collection 1", "org test id"), createCollectionView("id-2", "Collection 1/Collection 2", "org test id"), createCollectionView("id-3", "Collection 1/Collection 2/Collection 3", "org test id"), createCollectionView("id-4", "Collection 1/Collection 4", "org test id"), ]; collectionViews.next(storedCollections); const result = await firstValueFrom(vaultFilterService.collectionTree$); const c1 = result.children[0]; const c2 = c1.children[0]; const c3 = c2.children[0]; const c4 = c1.children[1]; expect(c2.parent.node.id).toEqual("id-1"); expect(c3.parent.node.id).toEqual("id-2"); expect(c4.parent.node.id).toEqual("id-1"); }); it("returns tree where non-existing collections are excluded from parents", async () => { const storedCollections = [ createCollectionView("id-1", "Collection 1", "org test id"), createCollectionView("id-3", "Collection 1/Collection 2/Collection 3", "org test id"), ]; collectionViews.next(storedCollections); const result = await firstValueFrom(vaultFilterService.collectionTree$); const c1 = result.children[0]; const c3 = c1.children[0]; expect(c3.parent.node.id).toEqual("id-1"); }); }); }); function createOrganization(id: string, name: string) { const org = new Organization(); org.id = id; org.name = name; org.identifier = name; org.isMember = true; return org; } function createCipherView(id: string, orgId: string, folderId: string) { const cipher = new CipherView(); cipher.id = id; cipher.organizationId = orgId; cipher.folderId = folderId; return cipher; } function createFolderView(id: string, name: string): FolderView { const folder = new FolderView(); folder.id = id; folder.name = name; return folder; } function createCollectionView(id: string, name: string, orgId: string): CollectionView { const collection = new CollectionView(); collection.id = id; collection.name = name; collection.organizationId = orgId; return collection; } }); ```
/content/code_sandbox/apps/web/src/app/vault/individual-vault/vault-filter/services/vault-filter.service.spec.ts
xml
2016-03-09T23:14:01
2024-08-16T15:07:51
clients
bitwarden/clients
8,877
2,894
```xml <resources> <string name="app_name">MVPDagger2</string> </resources> ```
/content/code_sandbox/Android/MVPDagger2/app/src/main/res/values/strings.xml
xml
2016-05-02T05:43:21
2024-08-16T06:51:39
journaldev
WebJournal/journaldev
1,314
23