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 import { min, max } from 'd3-array'; import { DataComponent as DC } from '../runtime'; import { flow } from './utils/flow'; import { tagCloud } from './utils/d3-cloud'; type Callable<T> = T | ((datum: any, i: number) => T); /** * See the document here: path_to_url */ export type WordCloudOptions = { /** * Internally, the layout uses setInterval to avoid locking up the browsers event loop. * If specified, time is the maximum amount of time that can be spent during the current timestep. * If not specified, returns the current maximum time interval, which defaults to Infinity. */ timeInterval: number; /** * If specified, sets the words array. If not specified, returns the current words array, which defaults to []. */ words: any[]; /** * If specified, sets the rectangular [width, height] of the layout. * If not specified, returns the current size, which defaults to [1, 1]. */ size: [number, number]; /** * If specified, sets the font accessor function, which indicates the font face for each word. * If not specified, returns the current font accessor function, which defaults to "serif". * A constant may be specified instead of a function. */ font: Callable<CSSStyleDeclaration['fontFamily']>; /** * TODO: Cname of font. */ fontFamily: Callable<CSSStyleDeclaration['fontFamily']>; /** * If specified, sets the fontStyle accessor function, which indicates the font style for each word. * If not specified, returns the current fontStyle accessor function, which defaults to "normal". * A constant may be specified instead of a function. */ fontStyle: Callable<CSSStyleDeclaration['fontFamily']>; /** * If specified, sets the fontWeight accessor function, which indicates the font weight for each word. * If not specified, returns the current fontWeight accessor function, which defaults to "normal". * A constant may be specified instead of a function. */ fontWeight: Callable<CSSStyleDeclaration['fontFamily']>; /** * If specified, sets the fontSize accessor function, which indicates the numerical font size for each word. * If not specified, returns the current fontSize accessor function, which defaults to: * * > function(d) { return Math.sqrt(d.value); } * * A constant may be specified instead of a function. * * If the fontSize is an array, it will be normalized to the range of [min, max] of the data value. * If the fontSize is a function, it will be called with the data value. * If the fontSize is a number, it will be used as the constant value. */ fontSize: number | [number, number] | ((d: any) => number); /** * If specified, sets the rotate accessor function, which indicates the rotation angle (in degrees) for each word. * If not specified, returns the current rotate accessor function, which defaults to: * * function() { return (~~(Math.random() * 6) - 3) * 30; } * * A constant may be specified instead of a function. */ rotate: Callable<number>; /** * If specified, sets the text accessor function, which indicates the text for each word. * If not specified, returns the current text accessor function, which defaults to: * * function(d) { return d.text; } * * A constant may be specified instead of a function. */ text: Callable<string>; /** * If specified, sets the padding accessor function, which indicates the numerical padding for each word. * If not specified, returns the current padding, which defaults to 1. */ padding: Callable<number>; /** * If specified, sets the internal random number generator, used for selecting the initial position of each word, * and the clockwise/counterclockwise direction of the spiral for each word. * This should return a number in the range [0, 1). * If not specified, returns the current random number generator, which defaults to Math.random. */ random: () => number; /** * If specified, sets the spiral used for positioning words. */ spiral: any; /** * If specified, sets the image mask used for positioning words. */ canvas: HTMLCanvasElement; }; const DEFAULT_OPTIONS = { fontSize: [20, 60], font: 'Impact', padding: 2, rotate: function () { return (~~(Math.random() * 6) - 3) * 30; }, }; /** * Process the image mask of wordCloud. * @param img * @returns */ export function processImageMask( img: HTMLImageElement | string, ): Promise<HTMLImageElement> { return new Promise((res, rej) => { if (img instanceof HTMLImageElement) { res(img); return; } if (typeof img === 'string') { const image = new Image(); image.crossOrigin = 'anonymous'; image.src = img; image.onload = () => res(image); image.onerror = () => { console.error(`'image ${img} load failed !!!'`); rej(); }; return; } rej(); }); } /** * normalize fontSize range to d3-cloud fontSize function. * @param fontSize * @param range * @returns */ export function normalizeFontSize(fontSize: any, range?: [number, number]) { if (typeof fontSize === 'function') return fontSize; if (Array.isArray(fontSize)) { const [fMin, fMax] = fontSize; if (!range) return () => (fMax + fMin) / 2; const [min, max] = range; if (max === min) return () => (fMax + fMin) / 2; return ({ value }) => ((fMax - fMin) / (max - min)) * (value - min) + fMin; } return () => fontSize; } export const WordCloud: DC<Partial<WordCloudOptions>> = (options, context) => { return async (data) => { const cloudOptions = Object.assign({}, DEFAULT_OPTIONS, options, { canvas: context.createCanvas, }); const layout = tagCloud(); await flow(layout, cloudOptions) .set('fontSize', (v) => { const arr = data.map((d) => d.value); return normalizeFontSize(v, [min(arr) as any, max(arr) as any]); }) .set('font') .set('fontStyle') .set('fontWeight') .set('padding') .set('rotate') .set('size') .set('spiral') .set('timeInterval') .set('random') .set('text') .set('on') .set('canvas') .setAsync('imageMask', processImageMask, layout.createMask); layout.words([...data]); const result = layout.start(); const [cw, ch] = cloudOptions.size; const defaultBounds = [ { x: 0, y: 0 }, { x: cw, y: ch }, ]; const { _bounds: bounds = defaultBounds, _tags, hasImage } = result; const tags = _tags.map(({ x, y, font, ...rest }) => ({ ...rest, x: x + cw / 2, y: y + ch / 2, fontFamily: font, })); // Append two data to replace the corner of top-left and bottom-right, avoid calculate the actual bounds will occur some error. const [{ x: tlx, y: tly }, { x: brx, y: bry }] = bounds; const invisibleText = { text: '', value: 0, opacity: 0, fontSize: 0 }; tags.push( { ...invisibleText, x: hasImage ? 0 : tlx, y: hasImage ? 0 : tly, }, { ...invisibleText, x: hasImage ? cw : brx, y: hasImage ? ch : bry, }, ); return tags; }; }; WordCloud.props = {}; ```
/content/code_sandbox/src/data/wordCloud.ts
xml
2016-05-26T09:21:04
2024-08-15T16:11:17
G2
antvis/G2
12,060
1,817
```xml <?xml version="1.0" encoding="utf-8"?> <!-- ~ All Rights Reserved. --> <LinearLayout xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/item_content_horizontal_margin" android:layout_marginRight="@dimen/item_content_horizontal_margin" android:background="?colorBackgroundFloating" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="@dimen/screen_edge_horizontal_margin" android:paddingRight="@dimen/screen_edge_horizontal_margin" android:paddingTop="@dimen/content_vertical_space" android:paddingBottom="@dimen/content_vertical_space" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/item_collection_list_title" android:textAppearance="@style/TextAppearance.AppCompat.Subhead" /> <Space android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="1" /> <me.zhanghai.android.douya.ui.ColoredBorderButton android:id="@+id/create" android:layout_width="wrap_content" android:layout_height="wrap_content" android:minWidth="0dp" android:minHeight="0dp" android:layout_marginLeft="-4dp" android:layout_marginRight="-4dp" android:layout_marginTop="-6dp" android:layout_marginBottom="-6dp" android:padding="6dp" android:text="@string/item_collection_list_create" android:textSize="@dimen/abc_text_size_caption_material" style="@style/Widget.AppCompat.Button.Borderless.Colored" /> </LinearLayout> <me.zhanghai.android.douya.ui.AdapterLinearLayout android:id="@+id/item_collection_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" /> <Button android:id="@+id/view_more" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?selectableItemBackground" android:paddingTop="@dimen/content_vertical_space" android:paddingBottom="@dimen/content_vertical_space" android:includeFontPadding="false" android:text="@string/item_collection_list_view_more" android:textAppearance="@style/TextAppearance.AppCompat.Widget.Button.Borderless.Colored" /> </LinearLayout> ```
/content/code_sandbox/app/src/main/res/layout/item_fragment_collection_list.xml
xml
2016-02-01T13:44:19
2024-08-15T05:23:34
Douya
zhanghai/Douya
4,549
570
```xml import type { AnimationEvent, CSSProperties, MouseEventHandler, PropsWithChildren, ReactElement, ReactNode, RefObject, } from 'react'; import { Children, cloneElement, useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useCombinedRefs } from '@proton/hooks'; import discoverIllustration from '@proton/styles/assets/img/illustrations/spotlight-binoculars.svg'; import newIllustration from '@proton/styles/assets/img/illustrations/spotlight-stars.svg'; import clsx from '@proton/utils/clsx'; import { generateUID } from '../../helpers'; import { useIsClosing } from '../../hooks'; import { Icon } from '../icon'; import type { PopperPlacement } from '../popper'; import { usePopper, usePopperState } from '../popper'; import { shouldShowSideRadius } from '../popper/utils'; import Portal from '../portal/Portal'; type SpotlightType = 'discover' | 'new'; export interface SpotlightProps { show: boolean; content: ReactNode; type?: SpotlightType; onDisplayed?: () => void; onClose?: MouseEventHandler; originalPlacement?: PopperPlacement; hasClose?: boolean; /** * Setting the anchor is optional, it will default on the root child */ anchorRef?: RefObject<HTMLElement>; style?: CSSProperties; className?: string; innerClassName?: string; size?: 'large'; footer?: ReactNode; } const Spotlight = ({ children, show, content, type, onDisplayed, onClose, originalPlacement = 'top', hasClose = true, anchorRef: inputAnchorRef, style = {}, className, innerClassName, size, footer, }: PropsWithChildren<SpotlightProps>) => { const [uid] = useState(generateUID('spotlight')); const popperAnchorRef = useRef<HTMLDivElement>(null); const { open, close, isOpen } = usePopperState(); const anchorRef = inputAnchorRef || popperAnchorRef; const { floating, position, arrow, placement } = usePopper({ // Spotlights open automatically and often targets elements which might have layout shifts, // so it's updated more aggressively than dropdowns and tooltips which are user triggered. updateAnimationFrame: true, reference: { mode: 'element', value: anchorRef?.current, }, isOpen, originalPlacement, }); const showSideRadius = shouldShowSideRadius(arrow['--arrow-offset'], placement, 8); const [isClosing, isClosed, setIsClosed] = useIsClosing(isOpen); const child = Children.only(children) as ReactElement; // Types are wrong? Not sure why ref doesn't exist on a ReactElement // @ts-ignore const mergedRef = useCombinedRefs(popperAnchorRef, child?.ref); useEffect(() => { if (show) { open(); onDisplayed?.(); } }, [show]); if (isClosed || !show) { return cloneElement(child, { ref: mergedRef }); } const handleAnimationEnd = ({ animationName }: AnimationEvent) => { if (animationName.includes('anime-spotlight-out') && isClosing) { setIsClosed(); } }; const handleClose: MouseEventHandler = (event) => { onClose?.(event); close(); }; const closeText = c('Action').t`Close`; const illustrationURL = type ? { discover: discoverIllustration as string, new: newIllustration as string, }[type] : null; return ( <> {cloneElement(child, { ref: mergedRef, 'aria-describedby': uid, })} <Portal> <div ref={floating} id={uid} style={{ ...position, ...arrow, ...style }} className={clsx([ 'spotlight', size && `spotlight--${size}`, `spotlight--${placement}`, isClosing && 'is-spotlight-out', type && 'spotlight--with-illustration', !showSideRadius && 'spotlight--no-side-radius', className, ])} onAnimationEnd={handleAnimationEnd} > <div className={clsx(['spotlight-inner', type && 'flex flex-nowrap items-start', innerClassName])} data-testid="spotlight-inner" > {illustrationURL && <img className="shrink-0 mr-6" src={illustrationURL} alt="" />} <div>{content}</div> </div> {footer ? ( <div className="spotlight-footer" data-testid="spotlight-footer"> {footer} </div> ) : null} {hasClose && ( <Button icon shape="ghost" size="small" className="spotlight-close" data-testid="spotlight-inner-close-button" title={closeText} onClick={handleClose} > <Icon name="cross" alt={closeText} /> </Button> )} </div> </Portal> </> ); }; export default Spotlight; ```
/content/code_sandbox/packages/components/components/spotlight/Spotlight.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
1,146
```xml import { Accordion, gridCellBehavior, gridHeaderCellBehavior, gridNestedBehavior, gridRowBehavior, Table, } from '@fluentui/react-northstar'; import * as React from 'react'; import { AutoSizer, List as ReactVirtualizedList, WindowScroller, ListProps, ListRowRenderer } from 'react-virtualized'; import getItems from './itemsGenerator'; // Magic offset for native scrollbar in Edge on Mac const scrollbarOffset = 10; function VirtualizedTablesPrototype() { const [ref, setRef] = React.useState(null); const tables = [ { key: 'table1', title: <div>Table one</div>, content: <VirtualizedTable scrollElementRef={ref} label={'table1'} />, }, { key: 'table2', title: <div>Custom table title</div>, content: <VirtualizedTable scrollElementRef={ref} label={'table2'} />, }, ]; return ( <div id="scrollParent" style={{ height: '700px', overflowY: 'auto' }} ref={setRef} tabIndex={-1} role="none"> {ref && <Accordion panels={tables} />} </div> ); } interface VirtualizedTableProps { scrollElementRef: HTMLDivElement; label: string; } const accessibilityListProperties: Partial<ListProps> = { 'aria-label': '', 'aria-readonly': undefined, containerRole: 'presentation', role: 'presentation', tabIndex: null, }; const accessibilityWrapperProperties: React.HTMLAttributes<HTMLDivElement> = { 'aria-label': '', 'aria-readonly': undefined, role: 'presentation', }; function VirtualizedTable(props: VirtualizedTableProps) { const { header, rows } = getItems(20, 50); const renderedItems = [header, ...rows]; const itemsCount = renderedItems.length; const rowGetter = ({ index }) => { return renderedItems[index]; }; const rowRenderer: ListRowRenderer = ({ index, style }) => { const row = renderedItems[index]; const header = row.key === 'header'; return ( <Table.Row style={style} key={row.key} accessibility={gridRowBehavior} aria-rowindex={index + 1} header={header}> <Table.Cell {...row.items[0]} accessibility={header ? gridHeaderCellBehavior : gridCellBehavior} /> <Table.Cell {...row.items[1]} accessibility={header ? gridHeaderCellBehavior : gridCellBehavior} /> <Table.Cell {...row.items[2]} accessibility={header ? gridHeaderCellBehavior : gridCellBehavior} /> <Table.Cell {...row.items[3]} accessibility={header ? gridHeaderCellBehavior : gridCellBehavior} /> </Table.Row> ); }; return ( <WindowScroller scrollElement={props.scrollElementRef} key={`${props.scrollElementRef}`}> {({ height, isScrolling, registerChild, onChildScroll, scrollTop }) => ( <AutoSizer disableHeight> {({ width }) => { return height ? ( <Table accessibility={gridNestedBehavior} aria-rowcount={itemsCount} aria-label={props.label}> <div ref={el => registerChild(el)} {...accessibilityWrapperProperties}> <ReactVirtualizedList autoHeight disableHeader={true} height={height} rowCount={itemsCount} width={width - scrollbarOffset} onScroll={onChildScroll} scrollTop={scrollTop} rowHeight={80} isScrolling={isScrolling} rowGetter={rowGetter} rowRenderer={rowRenderer} overscanRowCount={20} {...accessibilityListProperties} /> </div> </Table> ) : null; }} </AutoSizer> )} </WindowScroller> ); } export default VirtualizedTablesPrototype; ```
/content/code_sandbox/packages/fluentui/react-northstar-prototypes/src/prototypes/VirtualizedTable/VirtualizedTables.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
845
```xml /* * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. */ import {Container, Ul, Li, SkeletonText} from './styled'; type RowProps = { columnWidths: string[]; }; const Row: React.FC<RowProps> = ({columnWidths}) => { return ( <Li> {columnWidths.map((width, index) => ( <SkeletonText key={index} width={width} /> ))} </Li> ); }; type Props = { dataTestId?: string; columnWidths: string[]; }; const Skeleton: React.FC<Props> = ({dataTestId, columnWidths}) => { return ( <Container> <Ul data-testid={dataTestId}> {[...Array(20)].map((_, index) => ( <Row key={index} columnWidths={columnWidths} /> ))} </Ul> </Container> ); }; export {Skeleton}; ```
/content/code_sandbox/operate/client/src/App/DecisionInstance/VariablesPanel/InputsAndOutputs/Skeleton/index.tsx
xml
2016-03-20T03:38:04
2024-08-16T19:59:58
camunda
camunda/camunda
3,172
214
```xml import * as React from 'react'; import createSvgIcon from '../utils/createSvgIcon'; const RemoteIcon = createSvgIcon({ svg: ({ classes }) => ( <svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false"> <path d="M259 733l90-90 701 701-701 701-90-90 611-611-611-611zM1789 93l-611 611 611 611-90 90-701-701L1699 3l90 90z" /> </svg> ), displayName: 'RemoteIcon', }); export default RemoteIcon; ```
/content/code_sandbox/packages/react-icons-mdl2/src/components/RemoteIcon.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
153
```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> <parent> <groupId>org.eclipse.jdt.ls</groupId> <artifactId>parent</artifactId> <version>1.39.0-SNAPSHOT</version> </parent> <artifactId>org.eclipse.jdt.ls.core</artifactId> <packaging>eclipse-plugin</packaging> <name>${base.name} :: Core</name> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <configuration> <artifactItems> <artifactItem> <groupId>com.kotcrab.remark</groupId> <artifactId>remark</artifactId> <version>1.2.0</version> </artifactItem> <artifactItem> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.14.2</version> </artifactItem> <artifactItem> <groupId>com.jetbrains.intellij.java</groupId> <artifactId>java-decompiler-engine</artifactId> <version>231.9011.34</version> </artifactItem> </artifactItems> </configuration> </plugin> <plugin> <groupId>org.codehaus.gmaven</groupId> <artifactId>groovy-maven-plugin</artifactId> <version>2.1.1</version> <executions> <execution> <?m2e ignore?> <phase>generate-resources</phase> <goals> <goal>execute</goal> </goals> <configuration> <source> import groovy.json.JsonSlurper import groovy.json.JsonOutput import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse.BodyHandlers import java.util.concurrent.CompletableFuture import java.util.stream.Collectors; def checksumsFile = new File(project.basedir.absolutePath, "gradle/checksums/checksums.json") if (System.getProperty("eclipse.jdt.ls.skipGradleChecksums") != null &amp;&amp; checksumsFile.exists()) { println "Skipping gradle wrapper validation checksums ..." return } def versionUrl = new URL("path_to_url") def versionStr = versionUrl.text; def versionsFile = new File(project.basedir.absolutePath, "gradle/checksums/versions.json") versionsFile.parentFile.mkdirs() //just in case versionsFile.write(versionStr) println "Wrote to ${versionsFile}" def versions = new JsonSlurper().parseText(versionStr) class Checksum { String wrapperChecksumUrl; String sha256 } HttpClient client = HttpClient.newHttpClient() def futures = [] versions.each { if (it.wrapperChecksumUrl == null) { return } HttpRequest request = HttpRequest.newBuilder().uri(URI.create(it.wrapperChecksumUrl)).build() futures.add(client.sendAsync(request, BodyHandlers.ofString()).thenApply { response -> if (response.statusCode() == 301) { String newUrl = response.headers().firstValue("location").orElse(null) if (newUrl != null) { HttpRequest newRequest = HttpRequest.newBuilder() .uri(URI.create(newUrl)) .build() try { String sha256 = client.send(newRequest, BodyHandlers.ofString()).body() return new Checksum(wrapperChecksumUrl: it.wrapperChecksumUrl, sha256: sha256) } catch (IOException | InterruptedException e) { return null } } else { return null } } else { // Return the body of the original response return new Checksum(wrapperChecksumUrl: it.wrapperChecksumUrl, sha256: response.body()) } }) } def checksums = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) .thenApply { v -> futures.stream().map({ f -> f.join() }).collect(Collectors.toList()) }.get() def json = JsonOutput.toJson(checksums) checksumsFile.write(JsonOutput.prettyPrint(json)) println "Wrote to ${checksumsFile}" </source> </configuration> </execution> </executions> </plugin> </plugins> </build> <repositories> <repository> <id>jetbrains-intellij</id> <url>path_to_url </repository> </repositories> </project> ```
/content/code_sandbox/org.eclipse.jdt.ls.core/pom.xml
xml
2016-06-27T13:06:53
2024-08-16T00:38:32
eclipse.jdt.ls
eclipse-jdtls/eclipse.jdt.ls
1,726
1,113
```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 { html, LitElement } from 'lit'; import { customElement } from 'lit/decorators/custom-element.js'; import { componentIsStable, createTestElement, removeTestElement } from '@cds/core/test'; import { i18n } from './i18n.js'; const i18nValues = { open: 'Open my element', close: 'Close my element', }; /** @element test-18n-element */ @customElement('test-18n-element') class TestI18nElement extends LitElement { @i18n() i18n = i18nValues; render() { return html`<slot></slot>`; } } describe('i18n decorator', () => { let testElement: HTMLElement; let component: TestI18nElement; const closeText = 'Close my example element'; beforeEach(async () => { testElement = await createTestElement(html` <test-18n-element></test-18n-element> `); component = testElement.querySelector<TestI18nElement>('test-18n-element'); }); afterEach(() => { removeTestElement(testElement); }); it('should allow setting values for i18n', () => { expect(component.i18n).toEqual(i18nValues); }); it('should allow setting values for i18n through cds-i18n attribute', async () => { await componentIsStable(component); component.setAttribute('cds-i18n', `{ "close": "${closeText}" }`); await componentIsStable(component); expect(component.i18n.close).toEqual(closeText); component.setAttribute('cds-i18n', `{ "close": "ohai" }`); await componentIsStable(component); expect(component.i18n.close).toEqual('ohai', 'double set i18n'); }); }); ```
/content/code_sandbox/packages/core/src/internal/decorators/i18n.spec.ts
xml
2016-09-29T17:24:17
2024-08-11T17:06:15
clarity
vmware-archive/clarity
6,431
429
```xml <?xml version="1.0"?> <project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.yahoo.vespa</groupId> <artifactId>parent</artifactId> <version>8-SNAPSHOT</version> <relativePath>../parent/pom.xml</relativePath> </parent> <artifactId>config-class-plugin</artifactId> <packaging>maven-plugin</packaging> <version>8-SNAPSHOT</version> <name>config-class-plugin (Vespa ConfigGen Plugin)</name> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-core</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.yahoo.vespa</groupId> <artifactId>configgen</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.maven.plugin-tools</groupId> <artifactId>maven-plugin-annotations</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-plugin-plugin</artifactId> <configuration> <goalPrefix>vespa-cfg</goalPrefix> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <configuration> <doclint>${doclint},-missing</doclint> <tags> <tag> <name>goal</name> <placement>t</placement> </tag> <tag> <name>phase</name> <placement>t</placement> </tag> </tags> </configuration> </plugin> </plugins> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> </project> ```
/content/code_sandbox/config-class-plugin/pom.xml
xml
2016-06-03T20:54:20
2024-08-16T15:32:01
vespa
vespa-engine/vespa
5,524
556
```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 { Modules, StateMachine } from 'lisk-sdk'; import { NFTAttributes } from '../types'; import { mintNftParamsSchema } from '../schema'; interface Params { address: Buffer; collectionID: Buffer; attributesArray: NFTAttributes[]; } export class MintNftCommand extends Modules.BaseCommand { private _nftMethod!: Modules.NFT.NFTMethod; public schema = mintNftParamsSchema; public init(args: { nftMethod: Modules.NFT.NFTMethod }): void { this._nftMethod = args.nftMethod; } public async execute(context: StateMachine.CommandExecuteContext<Params>): Promise<void> { const { params } = context; await this._nftMethod.create( context.getMethodContext(), params.address, params.collectionID, params.attributesArray, ); } } ```
/content/code_sandbox/examples/interop/pos-sidechain-example-one/src/app/modules/testNft/commands/mint_nft.ts
xml
2016-02-01T21:45:35
2024-08-15T19:16:48
lisk-sdk
LiskArchive/lisk-sdk
2,721
267
```xml <?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.4"?> <plugin> <extension point="org.eclipse.ui.menus"> <menuContribution locationURI="menu:toolbox.file.menu?after=toolbox.file.translation.separator"> <command commandId="toolbox.command.tla2tex.producePDF" label="Produce PDF Version" style="push"> <visibleWhen checkEnabled="false"> <with variable="activeWorkbenchWindow.activePerspective"> <not> <equals value="org.lamport.tla.toolbox.ui.perspective.initial"> </equals> </not> </with> </visibleWhen> </command> </menuContribution> </extension> <extension point="org.eclipse.ui.commands"> <command categoryId="toolbox.command.category.module" description="Produce PDF Version of selected module" id="toolbox.command.tla2tex.producePDF" name="Produce PDF Version"> </command> </extension> <extension point="org.eclipse.ui.handlers"> <handler class="org.lamport.tla.toolbox.tool.tla2tex.handler.ProducePDFHandler" commandId="toolbox.command.tla2tex.producePDF"> <activeWhen> <with variable="activeEditorId"> <equals value="org.lamport.tla.toolbox.editor.basic.TLAEditorAndPDFViewer"> </equals> </with> </activeWhen> </handler> </extension> <extension point="org.eclipse.ui.preferencePages"> <page category="toolbox.ui.preferences.GeneralPreferencePage" class="org.lamport.tla.toolbox.tool.tla2tex.preference.TLA2TeXPreferencePage" id="toolbox.tool.tla2tex.preference.TLA2TeXPreferencePage" name="PDF Viewer"> </page> </extension> <extension point="org.eclipse.core.runtime.preferences"> <initializer class="org.lamport.tla.toolbox.tool.tla2tex.preference.TLA2TeXPreferenceInitializer"> </initializer> </extension> <extension point="org.eclipse.ui.views"> </extension> <extension point="org.eclipse.ui.bindings"> <key commandId="toolbox.command.tla2tex.producePDF" contextId="org.eclipse.ui.contexts.window" schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" sequence="M1+M3+P"> </key> </extension> </plugin> ```
/content/code_sandbox/toolbox/org.lamport.tla.toolbox.tool.tla2tex/plugin.xml
xml
2016-02-02T08:48:27
2024-08-16T16:50:00
tlaplus
tlaplus/tlaplus
2,271
570
```xml import type { FC } from 'react'; import { SafeItemIcon } from '@proton/pass/components/Layout/Icon/ItemIcon'; import { itemTypeToSubThemeClassName } from '@proton/pass/components/Layout/Theme/types'; import type { ItemRevision } from '@proton/pass/types'; import { rootFontSize } from '@proton/shared/lib/helpers/dom'; import clsx from '@proton/utils/clsx'; export const ITEM_TAG_MAX_WIDTH = 150; export const ItemTag: FC<ItemRevision> = (item) => ( <div className="flex flex-nowrap items-center gap-2 max-w-custom" style={{ '--max-w-custom': `${ITEM_TAG_MAX_WIDTH / rootFontSize()}rem` }} > <SafeItemIcon className={clsx('shrink-0', itemTypeToSubThemeClassName[item.data.type])} item={item} pill={false} size={2.5} /> <div className="text-ellipsis text-sm">{item.data.metadata.name}</div> </div> ); ```
/content/code_sandbox/packages/pass/components/Item/List/ItemTag.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
223
```xml <resources> <style name="AppThemeLight" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!-- Customize your theme here. --> <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item> </style> <style name="AppThemeDark" parent="Theme.AppCompat"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary2</item> <item name="colorPrimaryDark">@color/colorPrimaryDark2</item> <item name="colorAccent">@color/colorAccent2</item> <!-- Customize your theme here. --> <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item> </style> <!-- This will set the fade in animation on all your activities by default --> <style name="WindowAnimationTransition"> <item name="android:windowEnterAnimation">@android:anim/fade_in</item> <item name="android:windowExitAnimation">@android:anim/fade_out</item> </style> </resources> ```
/content/code_sandbox/ChangeThemeDuringRuntime/app/src/main/res/values/styles.xml
xml
2016-02-25T11:06:48
2024-08-07T21:41:59
android-examples
nisrulz/android-examples
1,747
278
```xml import React, { Component } from 'react'; import { observer, inject } from 'mobx-react'; import { get } from 'lodash'; import WalletUtxo from '../../components/wallet/utxo/WalletUtxo'; import type { InjectedProps } from '../../types/injectedPropsType'; import { getUtxoChartData, getWalletUtxosTotalAmount, } from '../../utils/utxoUtils'; type Props = InjectedProps; @inject('stores', 'actions') @observer class WalletUtxoPage extends Component<Props> { static defaultProps = { actions: null, stores: null, }; componentDidMount() { this.props.actions.walletSettings.startWalletUtxoPolling.trigger(); } componentWillUnmount() { this.props.actions.walletSettings.stopWalletUtxoPolling.trigger(); } render() { const { app, wallets, walletSettings, transactions } = this.props.stores; const { walletUtxos } = walletSettings; const { active: activeWallet } = wallets; if (!activeWallet) throw new Error('Active wallet required for WalletUtxoPage.'); const distribution = get(walletUtxos, 'distribution', {}); const chartData = getUtxoChartData(distribution); const walletUtxosAmount = getWalletUtxosTotalAmount(distribution); const { pendingTransactionsCount: pendingTxnsCount } = transactions; const { getWalletUtxosRequest } = walletSettings; const isLoadingInitialUtxoData = !getWalletUtxosRequest.wasExecuted || getWalletUtxosRequest.isExecutingFirstTime; return ( <WalletUtxo isLoadingInitialUtxoData={isLoadingInitialUtxoData} walletAmount={activeWallet.amount} walletUtxosAmount={walletUtxosAmount} chartData={chartData} onExternalLinkClick={app.openExternalLink} pendingTxnsCount={pendingTxnsCount} /> ); } } export default WalletUtxoPage; ```
/content/code_sandbox/source/renderer/app/containers/wallet/WalletUtxoPage.tsx
xml
2016-10-05T13:48:54
2024-08-13T22:03:19
daedalus
input-output-hk/daedalus
1,230
443
```xml <?xml version="1.0" encoding="utf-8"?> <ApplicationConfiguration xmlns:xsi="path_to_url" xmlns:ua="path_to_url" xmlns="path_to_url" > <ApplicationName>UA Server Configuration Push Test Client</ApplicationName> <ApplicationUri>urn:localhost:opcfoundation.org:ServerConfigurationPushTestClient</ApplicationUri> <ProductUri>path_to_url <ApplicationType>Client_1</ApplicationType> <SecurityConfiguration> <ApplicationCertificate> <StoreType>Directory</StoreType> <StorePath>%LocalApplicationData%/OPC/pki/own</StorePath> <SubjectName>CN=Server Configuration Push Test Client, O=OPC Foundation</SubjectName> </ApplicationCertificate> <TrustedIssuerCertificates> <StoreType>Directory</StoreType> <StorePath>%LocalApplicationData%/OPC/pki/issuers</StorePath> </TrustedIssuerCertificates> <TrustedPeerCertificates> <StoreType>Directory</StoreType> <StorePath>%LocalApplicationData%/OPC/pki/trusted</StorePath> </TrustedPeerCertificates> <RejectedCertificateStore> <StoreType>Directory</StoreType> <StorePath>%LocalApplicationData%/OPC/pki/rejected</StorePath> </RejectedCertificateStore> <!-- WARNING: The following setting (to automatically accept untrusted certificates) should be used for easy debugging purposes ONLY and turned off for production deployments! --> <AutoAcceptUntrustedCertificates>true</AutoAcceptUntrustedCertificates> <!-- WARNING: SHA1 signed certificates are by default rejected and should be phased out. --> <RejectSHA1SignedCertificates>false</RejectSHA1SignedCertificates> <MinimumCertificateKeySize>1024</MinimumCertificateKeySize> <AddAppCertToTrustedStore>false</AddAppCertToTrustedStore> <SendCertificateChain>false</SendCertificateChain> </SecurityConfiguration> <TransportConfigurations></TransportConfigurations> <TransportQuotas> <OperationTimeout>600000</OperationTimeout> <MaxStringLength>1048576</MaxStringLength> <MaxByteStringLength>1048576</MaxByteStringLength> <MaxArrayLength>65535</MaxArrayLength> <MaxMessageSize>4194304</MaxMessageSize> <MaxBufferSize>65535</MaxBufferSize> <ChannelLifetime>300000</ChannelLifetime> <SecurityTokenLifetime>3600000</SecurityTokenLifetime> </TransportQuotas> <ClientConfiguration> <!-- The default timeout for new sessions --> <DefaultSessionTimeout>600000</DefaultSessionTimeout> <!-- The well-known URLs for the local discovery servers URLs are tested in the order they appear in this list. --> <WellKnownDiscoveryUrls> <ua:String>opc.tcp://{0}:4840/UADiscovery</ua:String> </WellKnownDiscoveryUrls> <!-- EndpointDescriptions for system wide discovery servers --> <DiscoveryServers></DiscoveryServers> <!-- The minimum subscription lifetime. This ensures subscriptions are not set to expire too quickly. The requesed lifetime count and keep alive count are calculated using this value and the request publishing interval --> <MinSubscriptionLifetime>10000</MinSubscriptionLifetime> </ClientConfiguration> <Extensions> <ua:XmlElement> <ServerConfigurationPushTestClientConfiguration xmlns="path_to_url"> <ServerUrl>opc.tcp://localhost:58810/GlobalDiscoveryTestServer</ServerUrl> <AppUserName></AppUserName> <AppPassword></AppPassword> <SysAdminUserName>sysadmin</SysAdminUserName> <SysAdminPassword>demo</SysAdminPassword> <TempStorePath>%LocalApplicationData%/OPC/PKI/temp</TempStorePath> </ServerConfigurationPushTestClientConfiguration> </ua:XmlElement> </Extensions> <TraceConfiguration> <OutputFilePath>%LocalApplicationData%/OPC/Logs/Opc.Ua.Gds.Tests.log.txt</OutputFilePath> <DeleteOnLoad>false</DeleteOnLoad> <!-- Show Only Errors --> <!-- <TraceMasks>1</TraceMasks> --> <!-- Show Only Security and Errors --> <!-- <TraceMasks>513</TraceMasks> --> <!-- Show Only Security, Errors and Trace --> <!-- <TraceMasks>515</TraceMasks> --> <!-- Show Only Security, COM Calls, Errors and Trace --> <!-- <TraceMasks>771</TraceMasks> --> <!-- Show Only Security, Service Calls, Errors and Trace --> <!-- <TraceMasks>523</TraceMasks> --> <!-- Show Only Security, ServiceResultExceptions, Errors and Trace --> <TraceMasks>519</TraceMasks> </TraceConfiguration> </ApplicationConfiguration> ```
/content/code_sandbox/Tests/Opc.Ua.Gds.Tests/Opc.Ua.ServerConfigurationPushTestClient.Config.xml
xml
2016-02-12T14:57:06
2024-08-13T10:24:27
UA-.NETStandard
OPCFoundation/UA-.NETStandard
1,910
1,040
```xml <Page x:Class="Xamarin.Forms.Platform.UWP.ShellPageWrapper" xmlns="path_to_url" xmlns:x="path_to_url" xmlns:local="using:Xamarin.Forms.Platform.UAP" xmlns:d="path_to_url" xmlns:mc="path_to_url" mc:Ignorable="d"> <ContentPresenter Name="Root" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> </ContentPresenter> </Page> ```
/content/code_sandbox/Xamarin.Forms.Platform.UAP/Shell/ShellPageWrapper.xaml
xml
2016-03-18T15:52:03
2024-08-16T16:25:43
Xamarin.Forms
xamarin/Xamarin.Forms
5,637
99
```xml import * as React from 'react'; import type { Meta } from '@storybook/react'; import { DARK_MODE, getStoryVariant, RTL, TestWrapperDecorator } from '../../utilities'; import { Steps, StoryWright } from 'storywright'; import { NodesComposition, TreeChart, TreeTraverse } from '@fluentui/react-charting'; export default { title: 'react-charting/TreeChart', decorators: [ (story, context) => TestWrapperDecorator(story, context), (story, context) => { const steps = new Steps().snapshot('default', { cropTo: '.testWrapper' }).end(); return <StoryWright steps={steps}>{story()}</StoryWright>; }, ], } satisfies Meta<typeof TreeChart>; export const Basic = () => { const threeLayerChart = { name: 'Root Node', subname: 'subtext', bodytext: 'bodytext', fill: '#0099BC', children: [ { name: 'Child 1', subname: 'subtext', metric: '100%', fill: '#4F6BED', children: [ { name: 'leaf1', subname: 'sub', fill: '#4F6BED', }, { name: 'leaf2', fill: '#4F6BED', }, { name: 'leaf3', subname: 'The subtext is as follows: sub', fill: '#4F6BED', }, { name: 'leaf4', subname: 'sub', fill: '#4F6BED', }, ], }, { name: 'Child 2 is the child name', fill: '#881798', children: [ { name: 'leaf5', subname: 'sub', fill: '#881798', }, { name: 'leaf6', subname: 'sub', fill: '#881798', }, ], }, { name: 'Child 3', subname: 'The subtext is as follows: subtext', fill: '#AE8C00', children: [ { name: 'leaf7', subname: 'sub', fill: '#AE8C00', }, { name: 'leaf8', subname: 'sub', fill: '#AE8C00', }, { name: 'leaf9', subname: 'sub', fill: '#AE8C00', }, ], }, { name: 'Child 4', subname: 'subtext', metric: '90%', fill: '#FF00FF', children: [ { name: 'leaf10', subname: 'sub', fill: '#FF00FF', }, ], }, ], }; return ( <div style={{ padding: 10 }}> <TreeChart treeData={threeLayerChart} layoutWidth={300} /> </div> ); }; export const BasicDarkMode = getStoryVariant(Basic, DARK_MODE); export const BasicRTL = getStoryVariant(Basic, RTL); export const Compact = () => { const threeLayerChart = { name: 'Root Node', subname: 'subtext', fill: '#0099BC', children: [ { name: 'Child 1', subname: 'subtext', metric: '100%', fill: '#4F6BED', children: [ { name: 'leaf1', subname: 'sub', fill: '#4F6BED', }, { name: 'leaf2', fill: '#4F6BED', }, { name: 'leaf3', subname: 'The subtext is as follows: sub', fill: '#4F6BED', }, { name: 'leaf4', subname: 'sub', fill: '#4F6BED', }, ], }, { name: 'Child 2 is the child name', fill: '#881798', children: [ { name: 'leaf5', subname: 'sub', fill: '#881798', }, { name: 'leaf6', subname: 'sub', fill: '#881798', }, ], }, { name: 'Child 3', subname: 'The subtext is as follows: subtext', fill: '#AE8C00', children: [ { name: 'leaf7', subname: 'sub', fill: '#AE8C00', }, { name: 'leaf8', subname: 'sub', fill: '#AE8C00', }, { name: 'leaf9', subname: 'sub', fill: '#AE8C00', }, ], }, { name: 'Child 4', subname: 'subtext', metric: '90%', fill: '#FF00FF', children: [ { name: 'leaf10', subname: 'sub', fill: '#FF00FF', }, ], }, ], }; return ( <div style={{ padding: 10 }}> <TreeChart treeData={threeLayerChart} composition={NodesComposition.compact} treeTraversal={TreeTraverse.levelOrder} layoutWidth={300} /> </div> ); }; export const CompactDarkMode = getStoryVariant(Compact, DARK_MODE); export const CompactRTL = getStoryVariant(Compact, RTL); ```
/content/code_sandbox/apps/vr-tests/src/stories/react-charting/TreeChart.stories.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
1,246
```xml import { RepeatPipe } from './repeat'; describe('RepeatPipe Tests', () => { let pipe: RepeatPipe; beforeEach(() => { pipe = new RepeatPipe(); }); it('Should repeat string', () => { const result = pipe.transform('foo', 3); expect(result).toEqual('foofoofoo'); }); it('Should repeat string with separator', () => { const result = pipe.transform('foo', 3, '-'); expect(result).toEqual('foo-foo-foo'); }); it('Should return the same value when there are no arguments', () => { const result = pipe.transform('foo'); expect(result).toEqual('foo'); }); it('Should throw range exception if times count is below zero', () => { expect(() => { pipe.transform('foo', -1); }).toThrow(new RangeError()); }); }); ```
/content/code_sandbox/src/ng-pipes/pipes/string/repeat.spec.ts
xml
2016-11-24T22:03:44
2024-08-15T12:52:49
ngx-pipes
danrevah/ngx-pipes
1,589
191
```xml <clickhouse> <max_table_num_to_warn>5</max_table_num_to_warn> <max_view_num_to_warn>5</max_view_num_to_warn> <max_dictionary_num_to_warn>5</max_dictionary_num_to_warn> <max_database_num_to_warn>2</max_database_num_to_warn> <max_part_num_to_warn>10</max_part_num_to_warn> </clickhouse> ```
/content/code_sandbox/tests/config/config.d/max_num_to_warn.xml
xml
2016-06-02T08:28:18
2024-08-16T18:39:33
ClickHouse
ClickHouse/ClickHouse
36,234
89
```xml <!--Back To Menu Animation --> <animated-vector xmlns:android="path_to_url" android:drawable="@drawable/ic_back_vector"> <target android:name="back" android:animation="@animator/back_to_menu_morph"/> <target android:name="rotation" android:animation="@animator/back_to_menu_rotation"/> </animated-vector> ```
/content/code_sandbox/library/src/main/res/drawable-mdpi/ic_back_animated.xml
xml
2016-07-20T13:02:53
2024-08-16T04:55:39
MaterialSearchBar
mancj/MaterialSearchBar
2,031
79
```xml import config from '../config'; import LoginPage from '../pages/login' import NavbarPage from '../pages/navabar'; import ProjectCreatePage from '../pages/project-create'; import ProjectPage from '../pages/project'; import WorkflowCreatePage from '../pages/workflow-create'; import WorkflowPage from '../pages/workflow'; // DATA const projectName = 'CDSE2'; const projectKey = 'CDSE2'; const group = 'aa'; const workflowName = 'myFirstWorkflow'; const pipName = 'myFirstPipeline'; const appName = 'myFirstApplication'; const loginPage = new LoginPage(); const navbarPage = new NavbarPage(); const projectCreatePage = new ProjectCreatePage(); const projectPage = new ProjectPage(projectKey); const workflowCreatePage = new WorkflowCreatePage(projectKey); const workflowPage = new WorkflowPage(projectKey, workflowName); fixture('workflow-create') .meta({ severity: 'critical', priority: 'high', scope: 'workflow' }) .beforeEach(async(t) => { await t.maximizeWindow(); await loginPage.login(config.username, config.password); }); test('workflow-create', async (t) => { await navbarPage.clickCreateProject(); await projectCreatePage.createProject(projectName, projectKey, group); await projectPage.clickCreateWorkflow(); await workflowCreatePage.createWorkflow(workflowName, projectKey, pipName, appName); await workflowPage.runWorkflow(); await t.expect('.runs .item.pointing.success').ok(); }); ```
/content/code_sandbox/ui/e2e/tests/workflow-create.ts
xml
2016-10-11T08:28:23
2024-08-16T01:55:31
cds
ovh/cds
4,535
314
```xml import { classNames } from '@standardnotes/utils' import { EmojiString, Platform, VectorIconNameOrEmoji } from '@standardnotes/snjs' import { ForwardedRef, forwardRef, useCallback, useEffect, useMemo, useRef, useState } from 'react' import Dropdown from '../Dropdown/Dropdown' import { DropdownItem } from '../Dropdown/DropdownItem' import { getEmojiLength } from './EmojiLength' import Icon, { isIconEmoji } from './Icon' import { IconNameToSvgMapping } from './IconNameToSvgMapping' import { IconPickerType } from './IconPickerType' import DecoratedInput from '../Input/DecoratedInput' type Props = { selectedValue: VectorIconNameOrEmoji onIconChange: (value?: VectorIconNameOrEmoji) => void platform: Platform useIconGrid?: boolean iconGridClassName?: string className?: string autoFocus?: boolean } const TabButton = forwardRef( ( { type, label, currentType, selectTab, }: { label: string type: IconPickerType | 'reset' currentType: IconPickerType selectTab: (type: IconPickerType | 'reset') => void }, ref: ForwardedRef<HTMLButtonElement>, ) => { const isSelected = currentType === type return ( <button className={`relative mr-2 cursor-pointer border-0 pb-1.5 text-mobile-menu-item focus:shadow-none md:text-tablet-menu-item lg:text-menu-item ${ isSelected ? 'font-medium text-info' : 'text-text' }`} onClick={() => { selectTab(type) }} ref={ref} > {label} </button> ) }, ) const IconPicker = ({ selectedValue, onIconChange, platform, className, useIconGrid, iconGridClassName, autoFocus, }: Props) => { const iconKeys = useMemo(() => Object.keys(IconNameToSvgMapping), []) const iconOptions = useMemo( () => iconKeys.map( (value) => ({ label: value, value: value, icon: value, }) as DropdownItem, ), [iconKeys], ) const isSelectedEmoji = isIconEmoji(selectedValue) const isMacOS = platform === Platform.MacWeb || platform === Platform.MacDesktop const isWindows = platform === Platform.WindowsWeb || platform === Platform.WindowsDesktop const emojiInputRef = useRef<HTMLInputElement>(null) const [emojiInputFocused, setEmojiInputFocused] = useState(true) const [currentType, setCurrentType] = useState<IconPickerType>(isSelectedEmoji ? 'emoji' : 'icon') const [emojiInputValue, setEmojiInputValue] = useState(isSelectedEmoji ? selectedValue : '') useEffect(() => { setEmojiInputValue(isSelectedEmoji ? selectedValue : '') }, [isSelectedEmoji, selectedValue]) const selectTab = (type: IconPickerType | 'reset') => { if (type === 'reset') { onIconChange(undefined) setEmojiInputValue('') } else { setCurrentType(type) } } const handleIconChange = (value: string) => { onIconChange(value) } const handleEmojiChange = (value: EmojiString) => { setEmojiInputValue(value) const emojiLength = getEmojiLength(value as string) if (emojiLength === 1) { onIconChange(value) emojiInputRef.current?.blur() setEmojiInputFocused(false) } else { setEmojiInputFocused(true) } } const focusOnMount = useCallback((element: HTMLButtonElement | null) => { if (element) { setTimeout(() => { element.focus() }) } }, []) return ( <div className={`flex h-full flex-grow flex-col ${className}`}> <div className="flex"> <TabButton label="Icon" type={'icon'} currentType={currentType} selectTab={selectTab} /> <TabButton label="Emoji" type={'emoji'} currentType={currentType} selectTab={selectTab} /> <TabButton label="Reset" type={'reset'} currentType={currentType} selectTab={selectTab} /> </div> <div className={classNames('mt-1 h-full min-h-0', currentType === 'icon' && 'overflow-auto')}> {currentType === 'icon' && (useIconGrid ? ( <div className={classNames( 'flex w-full flex-wrap items-center gap-6 p-1 md:max-h-24 md:gap-4 md:p-0', iconGridClassName, )} > {iconKeys.map((iconName, index) => ( <button key={iconName} onClick={() => { handleIconChange(iconName) }} ref={index === 0 ? focusOnMount : undefined} > <Icon type={iconName} /> </button> ))} </div> ) : ( <Dropdown fullWidth={true} label="Change the icon for a tag" items={iconOptions} value={selectedValue as string} onChange={handleIconChange} /> ))} {currentType === 'emoji' && ( <> <DecoratedInput ref={emojiInputRef} autocomplete={false} autofocus={autoFocus ?? emojiInputFocused} type="text" value={emojiInputValue as string} onChange={(value) => handleEmojiChange(value)} /> <div className="mt-2 text-sm text-passive-0 lg:text-xs"> Use your keyboard to enter or paste in an emoji character. </div> {isMacOS && ( <div className="mt-2 text-sm text-passive-0 lg:text-xs"> On macOS: + + Space bar to bring up emoji picker. </div> )} {isWindows && ( <div className="mt-2 text-sm text-passive-0 lg:text-xs"> On Windows: Windows key + . to bring up emoji picker. </div> )} </> )} </div> </div> ) } export default IconPicker ```
/content/code_sandbox/packages/web/src/javascripts/Components/Icon/IconPicker.tsx
xml
2016-12-05T23:31:33
2024-08-16T06:51:19
app
standardnotes/app
5,180
1,364
```xml import { Pipe, PipeTransform } from "@angular/core"; import { OrganizationUserType } from "@bitwarden/common/admin-console/enums"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @Pipe({ name: "userType", }) export class UserTypePipe implements PipeTransform { constructor(private i18nService: I18nService) {} transform(value?: OrganizationUserType, unknownText?: string): string { if (value == null) { return unknownText ?? this.i18nService.t("unknown"); } switch (value) { case OrganizationUserType.Owner: return this.i18nService.t("owner"); case OrganizationUserType.Admin: return this.i18nService.t("admin"); case OrganizationUserType.User: return this.i18nService.t("user"); case OrganizationUserType.Custom: return this.i18nService.t("custom"); } } } ```
/content/code_sandbox/apps/web/src/app/admin-console/organizations/shared/components/access-selector/user-type.pipe.ts
xml
2016-03-09T23:14:01
2024-08-16T15:07:51
clients
bitwarden/clients
8,877
207
```xml <?xml version="1.0" encoding="UTF-8"?> <definitions id="definitions" xmlns="path_to_url" xmlns:activiti="path_to_url" targetNamespace="org.flowable.engine.test.api.runtime"> <process id="multipleSubProcessTest"> <startEvent id="theStart" /> <sequenceFlow id="flow1" sourceRef="theStart" targetRef="callSubProcess" /> <sequenceFlow id="flow2" sourceRef="theStart" targetRef="embeddedSubprocess" /> <callActivity id="callSubProcess" calledElement="simpleSubProcess" /> <subProcess id="embeddedSubprocess" name="embeddedSubProcess"> <startEvent id="theSubStart" /> <sequenceFlow id="subflow1" sourceRef="theSubStart" targetRef="task" /> <userTask id="task" name="Task in subprocess" /> <sequenceFlow id="subflow2" sourceRef="task" targetRef="theSubEnd" /> <endEvent id="theSubEnd" /> </subProcess> <sequenceFlow id="flow3" sourceRef="callSubProcess" targetRef="theEnd" /> <sequenceFlow id="flow4" sourceRef="embeddedSubprocess" targetRef="theEnd" /> <endEvent id="theEnd" /> </process> </definitions> ```
/content/code_sandbox/modules/flowable-engine/src/test/resources/org/flowable/engine/test/api/runtime/multipleSubProcess.bpmn20.xml
xml
2016-10-13T07:21:43
2024-08-16T15:23:14
flowable-engine
flowable/flowable-engine
7,715
311
```xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:tools="path_to_url" android:layout_margin="2dp" android:background="@drawable/image_select_cell_rounded" > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:padding="6dp" android:scaleType="fitCenter" tools:src="@drawable/ic_sport_archery" android:adjustViewBounds="true"/> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignStart="@+id/imageView" android:layout_alignEnd="@+id/imageView" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" style="@style/ImageSelectLabel" tools:text="@string/quest_sport_archery" android:maxLines="3" android:padding="8dp" /> </RelativeLayout> ```
/content/code_sandbox/app/src/main/res/layout/cell_labeled_icon_select.xml
xml
2016-07-02T10:44:04
2024-08-16T18:55:54
StreetComplete
streetcomplete/StreetComplete
3,781
278
```xml export { default, default as CreatePassword } from "./CreatePassword"; ```
/content/code_sandbox/client/src/core/client/auth/views/CreatePassword/index.ts
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
15
```xml import { describe, expect, test } from 'vitest'; import { extractTarballFromUrl } from '../src'; describe('extractTarballFromUrl', () => { const metadata: any = { name: 'npm_test', versions: { '1.0.0': { dist: { tarball: 'path_to_url }, }, '1.0.1': { dist: { tarball: 'npm_test-1.0.1.tgz', }, }, '1.0.2': { dist: { tarball: 'path_to_url }, }, }, }; test('should return only name of tarball', () => { expect(extractTarballFromUrl(metadata.versions['1.0.0'].dist.tarball)).toEqual( 'npm_test-1.0.0.tgz' ); expect(extractTarballFromUrl(metadata.versions['1.0.1'].dist.tarball)).toEqual( 'npm_test-1.0.1.tgz' ); expect(extractTarballFromUrl(metadata.versions['1.0.2'].dist.tarball)).toEqual( 'npm_test-1.0.2.tgz' ); }); }); ```
/content/code_sandbox/packages/core/tarball/tests/getLocalRegistryTarballUri.spec.ts
xml
2016-04-15T16:21:12
2024-08-16T09:38:01
verdaccio
verdaccio/verdaccio
16,189
278
```xml import { createElement, Fragment, ReactNode } from 'react' import { Container, useDimensions, SvgWrapper } from '@nivo/core' import { OrdinalColorScaleConfig } from '@nivo/colors' import { BoxLegendSvg } from '@nivo/legends' import { Datum, WaffleSvgProps, LayerId, TooltipComponent } from './types' import { svgDefaultProps } from './defaults' import { useWaffle, useCustomLayerProps } from './hooks' import { WaffleCells } from './WaffleCells' import { WaffleAreas } from './WaffleAreas' type InnerWaffleProps<D extends Datum> = Omit< WaffleSvgProps<D>, 'animate' | 'motionConfig' | 'renderWrapper' | 'theme' > const InnerWaffle = <D extends Datum>({ width, height, margin: partialMargin, data, valueFormat, total, rows, columns, fillDirection = svgDefaultProps.fillDirection, padding = svgDefaultProps.padding, hiddenIds = svgDefaultProps.hiddenIds, layers = svgDefaultProps.layers as LayerId[], cellComponent = svgDefaultProps.cellComponent, colors = svgDefaultProps.colors as OrdinalColorScaleConfig<D>, emptyColor = svgDefaultProps.emptyColor, emptyOpacity = svgDefaultProps.emptyOpacity, borderRadius = svgDefaultProps.borderRadius, borderWidth = svgDefaultProps.borderWidth, borderColor = svgDefaultProps.borderColor, defs = svgDefaultProps.defs, fill = svgDefaultProps.fill, isInteractive = svgDefaultProps.isInteractive, onMouseEnter, onMouseMove, onMouseLeave, onClick, tooltip = svgDefaultProps.tooltip as TooltipComponent<D>, forwardLegendData, legends = svgDefaultProps.legends, motionStagger = svgDefaultProps.motionStagger, role = svgDefaultProps.role, ariaLabel, ariaLabelledBy, ariaDescribedBy, testIdPrefix, }: InnerWaffleProps<D>) => { const { outerWidth, outerHeight, margin, innerWidth, innerHeight } = useDimensions( width, height, partialMargin ) const { cells, legendData, computedData, boundDefs } = useWaffle<D>({ width: innerWidth, height: innerHeight, data, hiddenIds, valueFormat, total, rows, columns, fillDirection, colors, emptyColor, emptyOpacity, borderColor, forwardLegendData, defs, fill, }) const layerById: Record<LayerId, ReactNode> = { cells: null, areas: null, legends: null, } if (layers.includes('cells')) { layerById.cells = ( <WaffleCells<D> key="cells" cells={cells} cellComponent={cellComponent} padding={padding} borderRadius={borderRadius} borderWidth={borderWidth} motionStagger={motionStagger} testIdPrefix={testIdPrefix} /> ) } if (layers.includes('areas')) { layerById.areas = ( <WaffleAreas<D> key="areas" data={computedData} isInteractive={isInteractive} onMouseEnter={onMouseEnter} onMouseMove={onMouseMove} onMouseLeave={onMouseLeave} onClick={onClick} tooltip={tooltip} testIdPrefix={testIdPrefix} /> ) } if (layers.includes('legends')) { layerById.legends = ( <g key="legends"> {legends.map((legend, i) => ( <BoxLegendSvg key={i} {...legend} containerWidth={width} containerHeight={height} data={legendData} /> ))} </g> ) } const customLayerProps = useCustomLayerProps<D>({ cells, computedData, }) return ( <SvgWrapper width={outerWidth} height={outerHeight} margin={margin} defs={boundDefs} role={role} ariaLabel={ariaLabel} ariaLabelledBy={ariaLabelledBy} ariaDescribedBy={ariaDescribedBy} > {layers.map((layer, i) => { if (typeof layer === 'function') { return <Fragment key={i}>{createElement(layer, customLayerProps)}</Fragment> } return layerById?.[layer] ?? null })} </SvgWrapper> ) } export const Waffle = <D extends Datum = Datum>({ isInteractive = svgDefaultProps.isInteractive, animate = svgDefaultProps.animate, motionConfig = svgDefaultProps.motionConfig, theme, renderWrapper, ...otherProps }: WaffleSvgProps<D>) => ( <Container {...{ animate, isInteractive, motionConfig, renderWrapper, theme, }} > <InnerWaffle<D> isInteractive={isInteractive} {...otherProps} /> </Container> ) ```
/content/code_sandbox/packages/waffle/src/Waffle.tsx
xml
2016-04-16T03:27:56
2024-08-16T03:38:37
nivo
plouc/nivo
13,010
1,093
```xml import React, { useEffect, useMemo, useState } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { addTreeFilter, applyFilters, updateFilter } from '@proton/shared/lib/api/filters'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import { AUTO_REPLY_CHARACTER_COUNT_LIMIT } from '@proton/shared/lib/mail/constants'; import { removeImagesFromContent } from '@proton/shared/lib/sanitize/purify'; import type { ModalProps } from '../../../components'; import { Checkbox, Form, Loader, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, useModalState, } from '../../../components'; import { generateUID } from '../../../helpers'; import { useApi, useEventManager, useFilters, useFolders, useLabels, useNotifications } from '../../../hooks'; import { getDefaultFolders, noFolderValue } from '../constants'; import type { Actions, Condition, CreateFilter, Errors, Filter, FilterActions, FilterCondition, FilterOperator, SimpleFilterModalModel, } from '../interfaces'; import { FilterStatement, Step } from '../interfaces'; import { computeFromTree, convertModel } from '../utils'; import CloseFilterModal from './CloseFilterModal'; import FilterActionsForm from './FilterActionsForm'; import FilterConditionsForm from './FilterConditionsForm'; import FilterNameForm from './FilterNameForm'; import FilterPreview from './FilterPreview'; import FooterFilterModal from './FooterFilterModal'; import HeaderFilterModal from './HeaderFilterModal'; import './Filtermodal.scss'; interface Props extends ModalProps { filter?: CreateFilter; onCloseCustomAction?: () => void; } const checkNameErrors = (filters: Filter[], name: string): string => { if (!name || name.trim() === '') { return c('Error').t`This field is required`; } const trimmedName = name.trim(); if (filters.find(({ Name }: Filter) => Name.trim() === trimmedName)) { return c('Error').t`Filter with this name already exists`; } return ''; }; const checkConditionsErrors = (conditions: Condition[]): string => { if (conditions.some((c) => !!c.error)) { return c('Error').t`Error in one of the conditions`; } if (!conditions.length) { return c('Error').t`Require at least one condition`; } return ''; }; const checkActionsErrors = (actions: Actions) => { const { labelAs, markAs, moveTo, autoReply } = actions; if (autoReply && autoReply.length > AUTO_REPLY_CHARACTER_COUNT_LIMIT) { return c('Error').t`You've reached the maximum character number. Please shorten your message.`; } if (!labelAs.labels.length && !moveTo.folder && !markAs.read && !markAs.starred && !autoReply) { return c('Error').t`Require at least one action`; } return ''; }; const modelHasChanged = (a: SimpleFilterModalModel, b: SimpleFilterModalModel): boolean => { const cleanConditions = (c: Condition) => ({ type: c.type, comparator: c.comparator, values: c.values, }); if ( a.name !== b.name || a.statement !== b.statement || !isDeepEqual(a.conditions.map(cleanConditions), b.conditions.map(cleanConditions)) || !isDeepEqual(a.actions.labelAs.labels, b.actions.labelAs.labels) || a.actions.moveTo.folder !== b.actions.moveTo.folder || a.actions.markAs.read !== b.actions.markAs.read || a.actions.markAs.starred !== b.actions.markAs.starred || (a.actions.autoReply && b.actions.autoReply && a.actions.autoReply !== b.actions.autoReply) ) { return true; } return false; }; const FilterModal = ({ filter, onCloseCustomAction, ...rest }: Props) => { const [filters = []] = useFilters(); const [labels = [], loadingLabels] = useLabels(); const [folders = [], loadingFolders] = useFolders(); const api = useApi(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [loading, withLoading] = useLoading(); const isEdit = !!filter?.ID; const [closeFilterModalProps, setCloseFilterModalOpen] = useModalState(); const { onClose } = rest; const initializeModel = (filter?: CreateFilter) => { const computedFilter = filter ? computeFromTree(filter) : {}; const { Actions, Conditions, Operator, }: { Operator?: FilterOperator; Actions?: FilterActions; Conditions?: FilterCondition[]; } = computedFilter || {}; const foldersLabelsMap = Actions?.FileInto.reduce( ( acc: { folder: string[]; labels: string[]; }, folderOrLabel: string ) => { const defaultFolderNames = getDefaultFolders().map((f) => f.value); if (defaultFolderNames.includes(folderOrLabel) || folders?.find((f) => f.Path === folderOrLabel)) { acc.folder = [folderOrLabel]; } if (labels?.find((l) => l.Path === folderOrLabel)) { acc.labels.push(folderOrLabel); } return acc; }, { folder: [], labels: [] } ); return { step: Step.NAME, id: filter?.ID, statement: Operator?.value || FilterStatement.ALL, name: filter?.Name || '', apply: false, conditions: Conditions?.map((cond) => ({ type: cond.Type.value, comparator: cond.Comparator.value, values: isEdit ? cond.Values : [], isOpen: true, defaultValue: cond.Values[0] || '', id: generateUID('condition'), })) || [], actions: { labelAs: { labels: foldersLabelsMap?.labels || [], isOpen: true, }, moveTo: { folder: foldersLabelsMap?.folder && foldersLabelsMap?.folder[0] ? foldersLabelsMap?.folder[0] : noFolderValue, isOpen: true, }, markAs: { read: Actions?.Mark.Read || false, starred: Actions?.Mark.Starred || false, isOpen: true, }, autoReply: Actions?.Vacation || null, }, }; }; const [model, setModel] = useState<SimpleFilterModalModel>(initializeModel()); const title = isEdit ? c('Title').t`Edit filter` : c('Title').t`Add filter`; const { name, conditions, actions } = model; const errors = useMemo<Errors>(() => { return { name: !model.name || filter?.Name !== name ? checkNameErrors(filters, name) : '', conditions: checkConditionsErrors(conditions), actions: checkActionsErrors(actions), }; }, [name, actions, conditions]); const handleCloseModal = () => { onCloseCustomAction?.(); onClose?.(); }; const createFilter = async (filter: CreateFilter) => { try { const { Filter } = await api(addTreeFilter(filter)); createNotification({ text: c('Notification').t`${Filter.Name} created`, }); return Filter; } finally { // Some failed request will add the filter but in disabled mode // So we have to refresh the list in both cases await call(); handleCloseModal(); } }; const editFilter = async (filter: CreateFilter) => { const { Filter } = await api(updateFilter(filter.ID, filter)); await call(); createNotification({ text: c('Filter notification').t`Filter ${Filter.Name} updated`, }); handleCloseModal(); return Filter; }; const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => { let newModel = model; // Remove images from the composer in autoreply if (model.actions.autoReply) { const { message, containsImages } = removeImagesFromContent(model.actions.autoReply); if (containsImages) { createNotification({ type: 'warning', text: c('Info').t`Images have been removed because they are not allowed in auto-reply`, }); } newModel = { ...model, actions: { ...actions, autoReply: message } }; setModel(newModel); } event.preventDefault(); let apiResult: Filter | undefined = undefined; if (isEdit) { apiResult = await editFilter(convertModel(newModel)); } else { apiResult = await createFilter(convertModel(newModel)); } if (newModel.apply && apiResult) { await api(applyFilters({ FilterIDs: [apiResult.ID] })); } }; const handleClose = () => { if (!modelHasChanged(model, initializeModel(filter))) { return handleCloseModal(); } setCloseFilterModalOpen(true); }; const renderStep = () => { switch (model.step) { case Step.NAME: return ( <FilterNameForm model={model} onChange={(newModel) => setModel(newModel as SimpleFilterModalModel)} errors={errors} loading={loading} /> ); case Step.CONDITIONS: return <FilterConditionsForm isEdit={isEdit} model={model} onChange={setModel} />; case Step.ACTIONS: return ( <FilterActionsForm labels={labels} folders={folders} model={model} onChange={setModel} isEdit={isEdit} /> ); case Step.PREVIEW: return <FilterPreview labels={labels} folders={folders} model={model} />; default: return null; } }; useEffect(() => { if (filter && !loadingFolders && !loadingLabels) { setModel(initializeModel(filter)); } }, [loadingFolders, loadingLabels]); return ( <> <ModalTwo as={Form} className="mail-filter-modal" onSubmit={(event: React.FormEvent<HTMLFormElement>) => { withLoading(handleSubmit(event)); }} {...rest} onClose={handleClose} > <ModalTwoHeader title={title} closeButtonProps={{ disabled: loading }} /> <ModalTwoContent> <HeaderFilterModal model={model} errors={errors} onChange={(newModel) => setModel(newModel as SimpleFilterModalModel)} /> {loadingLabels || loadingFolders ? <Loader /> : renderStep()} {[Step.ACTIONS, Step.PREVIEW].includes(model.step) && ( <div className="mt-4"> <Checkbox id="applyfilter" onChange={(event) => setModel({ ...model, apply: !!event.target.checked })} checked={model.apply} > {c('Label').t`Apply filter to existing emails`} </Checkbox> </div> )} </ModalTwoContent> <ModalTwoFooter> <FooterFilterModal model={model} errors={errors} onChange={(newModel) => setModel(newModel as SimpleFilterModalModel)} onClose={handleClose} loading={loading} /> </ModalTwoFooter> </ModalTwo> <CloseFilterModal {...closeFilterModalProps} handleDiscard={handleCloseModal} /> </> ); }; export default FilterModal; ```
/content/code_sandbox/packages/components/containers/filters/modal/FilterModal.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
2,484
```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. */ import type { Locale } from "date-fns"; /** * @param localeCode - ISO 639-1 + optional country code * @returns date-fns `Locale` object */ export type DateFnsLocaleLoader = (localeCode: string) => Promise<Locale | undefined>; export interface DateFnsLocaleProps { /** * Optional custom loader function for the date-fns `Locale` which will be used to localize the date picker. * This is useful in test environments or in build systems where you wish to customize module loading behavior. * If not provided, a default loader will be used which uses dynamic imports to load `date-fns/locale/${localeCode}` * modules. */ dateFnsLocaleLoader?: DateFnsLocaleLoader; /** * date-fns `Locale` object or locale code string ((ISO 639-1 + optional country code) which will be used * to localize the date picker. * * If you provide a locale code string and receive a loading error, please make sure it is included in the list of * date-fns' [supported locales](path_to_url * * @default "en-US" * @see path_to_url */ locale?: Locale | string; } export function getLocaleCodeFromProps(localeOrCode: DateFnsLocaleProps["locale"]): string | undefined { return typeof localeOrCode === "string" ? localeOrCode : localeOrCode?.code; } ```
/content/code_sandbox/packages/datetime2/src/common/dateFnsLocaleProps.ts
xml
2016-10-25T21:17:50
2024-08-16T15:14:48
blueprint
palantir/blueprint
20,593
357
```xml <?xml version="1.0" encoding="utf-8"?> <CheckedTextView xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="24dp" android:drawablePadding="33dp" android:paddingStart="20dp" android:paddingTop="10dp" android:paddingBottom="10dp" android:paddingEnd="10dp" android:layout_gravity="center_vertical" android:gravity="center_vertical" style="?attr/checkedTextViewStyle"/> ```
/content/code_sandbox/app/src/main/res/layout/checked_text_view_dialog_button.xml
xml
2016-05-04T11:46:20
2024-08-15T16:29:10
android
meganz/android
1,537
128
```xml import { Context } from 'egg'; export default { test(this: Context) { return this.url; }, } ```
/content/code_sandbox/test/fixtures/apps/app-ts/app/extend/context.ts
xml
2016-06-18T06:53:23
2024-08-16T10:11:28
egg
eggjs/egg
18,851
27
```xml import { css } from '@emotion/css'; import { stylesFactory } from '@grafana/ui'; import { GrafanaTheme } from '@grafana/data'; export const getStyles = stylesFactory((theme: GrafanaTheme) => { const iconsFill = theme.isLight ? 'black' : 'rgba(255, 255, 255, 0.8)'; return { icon: css` path, polygon, circle { fill: ${iconsFill} } `, }; }); ```
/content/code_sandbox/pmm-app/src/shared/components/Elements/Icons/Icons.styles.ts
xml
2016-01-22T07:14:23
2024-08-13T13:01:59
grafana-dashboards
percona/grafana-dashboards
2,661
109
```xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="path_to_url"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_camera" android:icon="@drawable/ic_menu_camera" android:title="Import" /> <item android:id="@+id/nav_gallery" android:icon="@drawable/ic_menu_gallery" android:title="Gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@drawable/ic_menu_slideshow" android:title="Slideshow" /> <item android:id="@+id/nav_manage" android:icon="@drawable/ic_menu_manage" android:title="Tools" /> </group> <item android:title="Communicate"> <menu> <item android:id="@+id/nav_share" android:icon="@drawable/ic_menu_share" android:title="Share" /> <item android:id="@+id/nav_send" android:icon="@drawable/ic_menu_send" android:title="Send" /> </menu> </item> </menu> ```
/content/code_sandbox/app/src/main/res/menu/activity_main_drawer.xml
xml
2016-03-13T05:16:32
2024-04-29T09:08:01
RxJavaApp
jiang111/RxJavaApp
1,045
247
```xml import React, { Fragment } from 'react'; import { styled } from '@storybook/core/theming'; export interface SeparatorProps { force?: boolean; } export const Separator = styled.span<SeparatorProps>( ({ theme }) => ({ width: 1, height: 20, background: theme.appBorderColor, marginLeft: 2, marginRight: 2, }), ({ force }) => force ? {} : { '& + &': { display: 'none', }, } ); Separator.displayName = 'Separator'; export const interleaveSeparators = (list: any[]) => list.reduce( (acc, item, index) => item ? ( <Fragment key={item.id || item.key || `f-${index}`}> {acc} {} {index > 0 ? <Separator key={`s-${index}`} /> : null} {item.render() || item} </Fragment> ) : ( acc ), null ); ```
/content/code_sandbox/code/core/src/components/components/bar/separator.tsx
xml
2016-03-18T04:23:44
2024-08-16T19:22:08
storybook
storybookjs/storybook
83,755
216
```xml export { default as Toggle } from './Toggle'; ```
/content/code_sandbox/packages/components/components/toggle/index.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
11
```xml // Do not modify this file; it is generated as part of publish. // The checked in version is a placeholder only and will not be updated. import { setVersion } from '@fluentui/set-version'; setVersion('@fluentui/react-cards', '0.0.0'); ```
/content/code_sandbox/packages/react-cards/src/version.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
61
```xml export { createPlaywrightTest as createTest } from 'storybook/internal/preview-api'; ```
/content/code_sandbox/code/renderers/react/src/playwright.ts
xml
2016-03-18T04:23:44
2024-08-16T19:22:08
storybook
storybookjs/storybook
83,755
19
```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net7.0</TargetFramework> <ProjectID>4BC5DF1F-B155-4A69-9719-0AB349B1ACB2</ProjectID> </PropertyGroup> </Project> ```
/content/code_sandbox/dotnet-template-samples/content/14-guid/MyProject.Con/MyProject.Con.csproj
xml
2016-06-28T20:54:16
2024-08-16T14:39:38
templating
dotnet/templating
1,598
79
```xml import {Store} from "@tsed/core"; import {SocketErr} from "../index.js"; describe("@SocketErr", () => { it("should set metadata", () => { class Test {} SocketErr(Test, "test", 0); const store = Store.from(Test); expect(store.get("socketIO")).toEqual({ handlers: { test: { parameters: { "0": { filter: "error", mapIndex: undefined } } } } }); }); }); ```
/content/code_sandbox/packages/third-parties/socketio/src/decorators/socketErr.spec.ts
xml
2016-02-21T18:38:47
2024-08-14T21:19:48
tsed
tsedio/tsed
2,817
114
```xml //@ts-nocheck import React from 'react'; import { Badge, HStack, VStack, Box } from 'native-base'; export function Example() { return ( <Box alignItems="center"> <HStack space={4} mx={{ base: 'auto', md: '0' }}> {['solid', 'outline', 'subtle'].map((key) => ( <VStack key={key} space={4}> <Badge variant={key} alignSelf="center"> DEFAULT </Badge> <Badge colorScheme="success" alignSelf="center" variant={key}> SUCCESS </Badge> <Badge colorScheme="error" alignSelf="center" variant={key}> ERROR </Badge> <Badge colorScheme="info" alignSelf="center" variant={key}> INFO </Badge> <Badge colorScheme="warning" alignSelf="center" variant={key}> WARNING </Badge> </VStack> ))} </HStack> </Box> ); } ```
/content/code_sandbox/example/storybook/stories/components/composites/Badge/variants.tsx
xml
2016-04-15T11:37:23
2024-08-14T16:16:44
NativeBase
GeekyAnts/NativeBase
20,132
223
```xml export { runTestFiles } from './runTestFiles' export { runTestSources } from './runTestSources' export { runTest } from './testRunner' export * from './types' export const assertLibCode = require('../sol/tests.sol.js') ```
/content/code_sandbox/remix-tests/src/index.ts
xml
2016-04-11T09:05:03
2024-08-12T19:22:17
remix
ethereum/remix
1,177
54
```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 {fireEvent, render, screen} from '@testing-library/react'; import {withTheme} from 'src/script/auth/util/test/TestUtil'; import {AccountLink} from './AccountLink'; import * as utils from '../../../../../util/ClipboardUtil'; test('copies correct text', async () => { const mockCopy: any = jest.spyOn(utils, 'copyText'); mockCopy.mockImplementation((text: string) => text); render(withTheme(<AccountLink label="test" value="test-value" />)); const button = await screen.findByRole('button'); fireEvent.click(button); expect(mockCopy).toHaveBeenCalledTimes(1); expect(mockCopy).toHaveReturnedWith('test-value'); }); test('renders elements correctly', () => { render(withTheme(<AccountLink label="test" value="test-value" />)); const label = screen.getByTestId('label-profile-link'); const value = screen.getByTestId('profile-link'); const button = screen.getByTestId('do-copy-profile-link'); expect(label).toBeTruthy(); expect(value).toBeTruthy(); expect(button).toBeTruthy(); }); ```
/content/code_sandbox/src/script/page/MainContent/panels/preferences/accountPreferences/AccountLink.test.tsx
xml
2016-07-21T15:34:05
2024-08-16T11:40:13
wire-webapp
wireapp/wire-webapp
1,125
316
```xml import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { Response } from "../../models/response"; import { MessageResponse } from "../../models/response/message.response"; export class LogoutCommand { constructor( private authService: AuthService, private i18nService: I18nService, private logoutCallback: () => Promise<void>, ) {} async run() { await this.logoutCallback(); this.authService.logOut(() => { /* Do nothing */ }); const res = new MessageResponse("You have logged out.", null); return Response.success(res); } } ```
/content/code_sandbox/apps/cli/src/auth/commands/logout.command.ts
xml
2016-03-09T23:14:01
2024-08-16T15:07:51
clients
bitwarden/clients
8,877
150
```xml import { fromGitHubOrg } from './organization' import { fromGitHubUser } from './user' export function fromGitHubRepository(repo: any) { if (!repo) return null return { id: repo.id || '', name: repo.name || '', fullName: repo.full_name || '', isFork: repo.fork === true, isPrivate: repo.private === true, owner: repo.owner && repo.owner.type === 'Organization' ? fromGitHubOrg(repo.owner) : fromGitHubUser(repo.owner), // description: String // languages: [Language] // stargazers: StargazersConnection // tags: [String] } } ```
/content/code_sandbox/packages/core/src/mappers/repository.ts
xml
2016-11-30T23:24:21
2024-08-16T00:24:59
devhub
devhubapp/devhub
9,652
148
```xml // path_to_url import { XmlComponent } from "@file/xml-components"; import { MathComponent } from "../math-component"; import { MathBase } from "../n-ary"; import { MathBracketProperties } from "./math-bracket-properties"; export class MathAngledBrackets extends XmlComponent { public constructor(options: { readonly children: readonly MathComponent[] }) { super("m:d"); this.root.push( new MathBracketProperties({ beginningCharacter: "", endingCharacter: "", }), ); this.root.push(new MathBase(options.children)); } } ```
/content/code_sandbox/src/file/paragraph/math/brackets/math-angled-brackets.ts
xml
2016-03-26T23:43:56
2024-08-16T13:02:47
docx
dolanmiu/docx
4,139
121
```xml import React from 'react'; import { applyMiddleware, compose, createStore } from 'redux'; import { Provider } from 'react-redux'; import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import { createMemoryHistory } from 'history'; import thunk from 'redux-thunk'; import ReduxPromise from 'redux-promise'; import { Router } from 'react-router'; import { render } from '@testing-library/react'; import en from '@nuclear/i18n/src/locales/en.json'; import rootReducer from '../app/reducers'; import syncStore from '../app/store/enhancers/syncStorage'; import MainContentContainer from '../app/containers/MainContentContainer'; import HelpModalContainer from '../app/containers/HelpModalContainer'; import PlayQueueContainer from '../app/containers/PlayQueueContainer'; import Navbar from '../app/components/Navbar'; import NavButtons from '../app/components/NavButtons'; export type AnyProps = { [k: string]: any; } export const uuidRegex = /\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/; type TestRouteProviderProps = { children: React.ReactNode; history: ReturnType<typeof createMemoryHistory>; } export const configureMockStore = (initialState?: AnyProps) => createStore( rootReducer, initialState, compose( applyMiddleware(ReduxPromise, thunk), syncStore(['downloads']) ) ); export const TestStoreProvider: React.FC<{ initialState?: AnyProps; store?: ReturnType<typeof configureMockStore>; }> = ({ initialState = {}, store, children }) => { return <Provider store={store || configureMockStore(initialState)}> {children} </Provider>; }; export const TestRouterProvider = ({ children, history }: TestRouteProviderProps) => { return ( <Router history={history} > {children} </Router> ); }; export const setupI18Next = () => { i18n .use(initReactI18next) .init({ lng: 'en', fallbackLng: 'en', debug: false, resources: { en } }); return i18n; }; export const mountComponent = ( componentToMount: React.ReactElement, initialHistoryEntries: string[], initialStore?: AnyProps, defaultInitialStore?: AnyProps, renderOptions?: {}) => { const initialState = initialStore || defaultInitialStore; const history = createMemoryHistory({ initialEntries: initialHistoryEntries }); const store = configureMockStore(initialState); const component = render( <TestRouterProvider history={history} > <TestStoreProvider store={store} > {componentToMount} </TestStoreProvider> </TestRouterProvider>, renderOptions ); return { component, history, store }; }; export const mountedComponentFactory = ( initialHistoryEntries: string[], defaultInitialStore?: AnyProps, AdditionalNodes?: React.FC ) => (initialStore?: AnyProps) => mountComponent( <> <MainContentContainer /> {AdditionalNodes && <AdditionalNodes />} </>, initialHistoryEntries, initialStore, defaultInitialStore ); export const mountedNavbarFactory= ( initialHistoryEntries: string[], defaultInitialStore?: AnyProps ) => (initialStore?: AnyProps) => mountComponent( <Navbar> <NavButtons /> <HelpModalContainer /> </Navbar>, initialHistoryEntries, initialStore, defaultInitialStore ); export const mountedPlayQueueFactory= ( initialHistoryEntries: string[], defaultInitialStore?: AnyProps ) => (initialStore?: AnyProps) => mountComponent( <PlayQueueContainer />, initialHistoryEntries, initialStore, defaultInitialStore, { container: document.body } ); ```
/content/code_sandbox/packages/app/test/testUtils.tsx
xml
2016-09-22T22:58:21
2024-08-16T15:47:39
nuclear
nukeop/nuclear
11,862
842
```xml <?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="path_to_url" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pt-BR" original="../HelpStrings.resx"> <body> <trans-unit id="Hint_AmbiguousLanguage"> <source>Re-run the command specifying the language to use with --language option.</source> <target state="translated">Execute novamente o comando especificando o idioma a ser usado com a opo de linguagem --.</target> <note>--language is an option name and should not be translated.</note> </trans-unit> <trans-unit id="Hint_AmbiguousType"> <source>Re-run the command specifying the type to use with --type option.</source> <target state="translated">Execute novamente o comando especificando o tipo a ser usado com a opo --type.</target> <note>--type is an option name and should not be translated.</note> </trans-unit> <trans-unit id="Hint_HelpForOtherLanguages"> <source>To see help for other template languages ({0}), use --language option:</source> <target state="translated">Para ver a ajuda de outros idiomas de modelo ({0}), use a opo--language:</target> <note>{0} is comma-separated list of supported programming languages by template. --language should not be translated.</note> </trans-unit> <trans-unit id="Hint_HelpForOtherTypes"> <source>To see help for other template types ({0}), use --type option:</source> <target state="translated">Para consultar a ajuda para outros tipos de modelo ({0}), utilize a opo --type:</target> <note>{0} is comma-separated list of supported types by template. --type should not be translated.</note> </trans-unit> <trans-unit id="Info_TemplateThirdPartyNotice"> <source>This template contains technologies from parties other than Microsoft, see {0} for details.</source> <target state="translated">Este modelo contm tecnologias de outras pessoas alm da Microsoft, consulte {0} para obter detalhes.</target> <note /> </trans-unit> <trans-unit id="RowHeader_AllowMultiValue"> <source>Multiple values are allowed: {0}</source> <target state="translated">Vrios valores so permitidos: {0}</target> <note>{0} is a boolean flag</note> </trans-unit> <trans-unit id="RowHeader_DefaultIfOptionWithoutValue"> <source>Default if option is provided without a value: {0}</source> <target state="translated">Padro se a opo for fornecida sem um valor: {0}</target> <note>{0} is default value if option was provided without a value</note> </trans-unit> <trans-unit id="RowHeader_DefaultValue"> <source>Default: {0}</source> <target state="translated">Padro: {0}</target> <note>{0} is default value for option</note> </trans-unit> <trans-unit id="RowHeader_Description"> <source>Description: {0}</source> <target state="translated">Descrio: {0}</target> <note /> </trans-unit> <trans-unit id="RowHeader_TemplateAuthor"> <source>Author: {0}</source> <target state="translated">Autor: {0}</target> <note /> </trans-unit> <trans-unit id="RowHeader_Type"> <source>Type: {0}</source> <target state="translated">Tipo: {0}</target> <note>{0} is option type (string, boolean, etc)</note> </trans-unit> <trans-unit id="SectionHeader_TemplateSpecificOptions"> <source>Template options:</source> <target state="translated">Opes do modelo:</target> <note /> </trans-unit> <trans-unit id="TableHeader_AmbiguousTemplatesList"> <source>Unable to resolve the template, these templates matched your input:</source> <target state="translated">No foi possvel resolver o modelo, esses modelos corresponderam sua entrada:</target> <note /> </trans-unit> <trans-unit id="Text_ChoiceArgumentHelpName"> <source>choice</source> <target state="translated">escolha</target> <note>this text is used as argument help name when list of possible values is too long to fit the screen, " --my-o &lt;choice&gt;"</note> </trans-unit> <trans-unit id="Text_Disabled"> <source>Enabled: *false*</source> <target state="translated">Habilitado: *false*</target> <note>Indication that parameter is not enabled</note> </trans-unit> <trans-unit id="Text_EnabledCondition"> <source>Enabled if: {0}</source> <target state="translated">Habilitado se: {0}</target> <note>{0} is the condition expression</note> </trans-unit> <trans-unit id="Text_NoTemplateOptions"> <source>(No options)</source> <target state="translated">(Nenhuma opo)</target> <note /> </trans-unit> <trans-unit id="Text_Required"> <source>Required: *true*</source> <target state="translated">Necessrio: *true*</target> <note>Indication that parameter is always required, do not translate "true".</note> </trans-unit> <trans-unit id="Text_RequiredCondition"> <source>Required if: {0}</source> <target state="translated">Obrigatrio se: {0}</target> <note>{0} is the condition expression</note> </trans-unit> <trans-unit id="Text_UsageTemplateOptionsPart"> <source>[template options]</source> <target state="translated">[opes de modelo]</target> <note>this text will be used as part of command usage: dotnet new console [options] [template options]</note> </trans-unit> </body> </file> </xliff> ```
/content/code_sandbox/src/Cli/Microsoft.TemplateEngine.Cli/Commands/xlf/HelpStrings.pt-BR.xlf
xml
2016-07-22T21:26:02
2024-08-16T17:23:58
sdk
dotnet/sdk
2,627
1,438
```xml <project name="bug3515070" default="filter"> <property name="findbugs.jar" value="../../../../findbugs/lib/findbugs.jar"/> <target name="filter"> <taskdef name="filterbugs" classname="edu.umd.cs.findbugs.anttask.FilterBugsTask" classpath="${findbugs.jar}"/> <filterbugs classpath="${findbugs.jar}" bugPattern="" input="input.xml" output="output.xml"/> </target> </project> ```
/content/code_sandbox/spotbugsTestCases/src/xml/sfBugs/bug3515070.xml
xml
2016-11-04T22:18:08
2024-08-15T14:30:47
spotbugs
spotbugs/spotbugs
3,428
100
```xml <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="path_to_url"> <ItemGroup> <Filter Include="Source Files"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="Header Files"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions> </Filter> <Filter Include="Resource Files"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> </Filter> </ItemGroup> <ItemGroup> <None Include="GlobalExportFunctions.def"> <Filter>Source Files</Filter> </None> <None Include="IconPending.ico"> <Filter>Resource Files</Filter> </None> <None Include="IconSynced.ico"> <Filter>Resource Files</Filter> </None> <None Include="IconSyncing.ico"> <Filter>Resource Files</Filter> </None> <None Include="contextIcon.bmp"> <Filter>Resource Files</Filter> </None> </ItemGroup> <ItemGroup> <ClCompile Include="dllmain.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="ClassFactory.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="ContextMenuExt.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="ClassFactoryContextMenuExt.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="ClassFactoryShellExtSynced.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="ClassFactoryShellExtPending.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="ClassFactoryShellExtSyncing.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="ShellExt.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="RegUtils.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="MEGAinterface.cpp"> <Filter>Source Files</Filter> </ClCompile> <ClCompile Include="ShellExtNotASync.cpp"> <Filter>Source Files</Filter> </ClCompile> </ItemGroup> <ItemGroup> <ClInclude Include="ClassFactory.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="resource.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="ContextMenuExt.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="ClassFactoryContextMenuExt.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="ClassFactoryShellExtSynced.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="ClassFactoryShellExtPending.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="ClassFactoryShellExtSyncing.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="ShellExt.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="RegUtils.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="MEGAinterface.h"> <Filter>Header Files</Filter> </ClInclude> <ClInclude Include="ShellExtNotASync.h"> <Filter>Header Files</Filter> </ClInclude> </ItemGroup> <ItemGroup> <ResourceCompile Include="MEGAShellExt.rc"> <Filter>Resource Files</Filter> </ResourceCompile> </ItemGroup> </Project> ```
/content/code_sandbox/src/MEGAShellExt/MEGAShellExt.vcxproj.filters
xml
2016-02-10T18:28:05
2024-08-16T19:36:44
MEGAsync
meganz/MEGAsync
1,593
1,014
```xml 'use strict'; import { expect, use } from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as path from 'path'; import * as TypeMoq from 'typemoq'; import { IFileSystem } from '../../../client/common/platform/types'; import { IPathUtils } from '../../../client/common/types'; import { EnvironmentVariablesService, parseEnvFile } from '../../../client/common/variables/environment'; import { getSearchPathEnvVarNames } from '../../../client/common/utils/exec'; use(chaiAsPromised); type PathVar = 'Path' | 'PATH'; const PATHS = getSearchPathEnvVarNames(); suite('Environment Variables Service', () => { const filename = 'x/y/z/.env'; const processEnvPath = getSearchPathEnvVarNames()[0]; let pathUtils: TypeMoq.IMock<IPathUtils>; let fs: TypeMoq.IMock<IFileSystem>; let variablesService: EnvironmentVariablesService; setup(() => { pathUtils = TypeMoq.Mock.ofType<IPathUtils>(undefined, TypeMoq.MockBehavior.Strict); fs = TypeMoq.Mock.ofType<IFileSystem>(undefined, TypeMoq.MockBehavior.Strict); variablesService = new EnvironmentVariablesService( // This is the only place that the mocks are used. pathUtils.object, fs.object, ); }); function verifyAll() { pathUtils.verifyAll(); fs.verifyAll(); } function setFile(fileName: string, text: string) { fs.setup((f) => f.pathExists(fileName)) // Handle the specific file. .returns(() => Promise.resolve(true)); // The file exists. fs.setup((f) => f.readFile(fileName)) // Handle the specific file. .returns(() => Promise.resolve(text)); // Pretend to read from the file. } suite('parseFile()', () => { test('Custom variables should be undefined with no argument', async () => { const vars = await variablesService.parseFile(undefined); expect(vars).to.equal(undefined, 'Variables should be undefined'); verifyAll(); }); test('Custom variables should be undefined with non-existent files', async () => { fs.setup((f) => f.pathExists(filename)) // Handle the specific file. .returns(() => Promise.resolve(false)); // The file is missing. const vars = await variablesService.parseFile(filename); expect(vars).to.equal(undefined, 'Variables should be undefined'); verifyAll(); }); test('Custom variables should be undefined when folder name is passed instead of a file name', async () => { const dirname = 'x/y/z'; fs.setup((f) => f.pathExists(dirname)) // Handle the specific "file". .returns(() => Promise.resolve(false)); // It isn't a "regular" file. const vars = await variablesService.parseFile(dirname); expect(vars).to.equal(undefined, 'Variables should be undefined'); verifyAll(); }); test('Custom variables should be not undefined with a valid environment file', async () => { setFile(filename, '...'); const vars = await variablesService.parseFile(filename); expect(vars).to.not.equal(undefined, 'Variables should be undefined'); verifyAll(); }); test('Custom variables should be parsed from env file', async () => { // src/testMultiRootWkspc/workspace4/.env setFile( filename, ` X1234PYEXTUNITTESTVAR=1234 PYTHONPATH=../workspace5 `, ); const vars = await variablesService.parseFile(filename); expect(vars).to.not.equal(undefined, 'Variables is is undefiend'); expect(Object.keys(vars!)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('X1234PYEXTUNITTESTVAR', '1234', 'X1234PYEXTUNITTESTVAR value is invalid'); expect(vars).to.have.property('PYTHONPATH', '../workspace5', 'PYTHONPATH value is invalid'); verifyAll(); }); test('PATH and PYTHONPATH from env file should be returned as is', async () => { const expectedPythonPath = '/usr/one/three:/usr/one/four'; const expectedPath = '/usr/x:/usr/y'; // src/testMultiRootWkspc/workspace4/.env setFile( filename, ` X=1 Y=2 PYTHONPATH=/usr/one/three:/usr/one/four # Unix PATH variable PATH=/usr/x:/usr/y # Windows Path variable Path=/usr/x:/usr/y `, ); const vars = await variablesService.parseFile(filename); expect(vars).to.not.equal(undefined, 'Variables is is undefiend'); expect(Object.keys(vars!)).lengthOf(5, 'Incorrect number of variables'); expect(vars).to.have.property('X', '1', 'X value is invalid'); expect(vars).to.have.property('Y', '2', 'Y value is invalid'); expect(vars).to.have.property('PYTHONPATH', expectedPythonPath, 'PYTHONPATH value is invalid'); expect(vars).to.have.property('PATH', expectedPath, 'PATH value is invalid'); verifyAll(); }); test('Simple variable substitution is supported', async () => { // src/testMultiRootWkspc/workspace4/.env setFile( filename, '\ REPO=/home/user/git/foobar\n\ PYTHONPATH=${REPO}/foo:${REPO}/bar\n\ PYTHON=${BINDIR}/python3\n\ ', ); const vars = await variablesService.parseFile(filename, { BINDIR: '/usr/bin' }); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(3, 'Incorrect number of variables'); expect(vars).to.have.property('REPO', '/home/user/git/foobar', 'value is invalid'); expect(vars).to.have.property( 'PYTHONPATH', '/home/user/git/foobar/foo:/home/user/git/foobar/bar', 'value is invalid', ); expect(vars).to.have.property('PYTHON', '/usr/bin/python3', 'value is invalid'); verifyAll(); }); }); PATHS.map((pathVariable) => { suite(`mergeVariables() (path var: ${pathVariable})`, () => { setup(() => { pathUtils .setup((pu) => pu.getPathVariableName()) // This always gets called. .returns(() => pathVariable as PathVar); // Pretend we're on a specific platform. }); test('Ensure variables are merged', async () => { const vars1 = { ONE: '1', TWO: 'TWO' }; const vars2 = { ONE: 'ONE', THREE: '3' }; variablesService.mergeVariables(vars1, vars2); expect(Object.keys(vars1)).lengthOf(2, 'Source variables modified'); expect(Object.keys(vars2)).lengthOf(3, 'Variables not merged'); expect(vars2).to.have.property('ONE', 'ONE', 'Variable overwritten'); expect(vars2).to.have.property('TWO', 'TWO', 'Incorrect value'); expect(vars2).to.have.property('THREE', '3', 'Variable not merged'); verifyAll(); }); test('Ensure path variabnles variables are not merged into target', async () => { const vars1 = { ONE: '1', TWO: 'TWO', PYTHONPATH: 'PYTHONPATH' }; (vars1 as any)[pathVariable] = 'PATH'; const vars2 = { ONE: 'ONE', THREE: '3' }; variablesService.mergeVariables(vars1, vars2); expect(Object.keys(vars1)).lengthOf(4, 'Source variables modified'); expect(Object.keys(vars2)).lengthOf(3, 'Variables not merged'); expect(vars2).to.have.property('ONE', 'ONE', 'Variable overwritten'); expect(vars2).to.have.property('TWO', 'TWO', 'Incorrect value'); expect(vars2).to.have.property('THREE', '3', 'Variable not merged'); verifyAll(); }); test('Ensure path variables in target are left untouched', async () => { const vars1 = { ONE: '1', TWO: 'TWO' }; const vars2 = { ONE: 'ONE', THREE: '3', PYTHONPATH: 'PYTHONPATH' }; (vars2 as any)[pathVariable] = 'PATH'; variablesService.mergeVariables(vars1, vars2); expect(Object.keys(vars1)).lengthOf(2, 'Source variables modified'); expect(Object.keys(vars2)).lengthOf(5, 'Variables not merged'); expect(vars2).to.have.property('ONE', 'ONE', 'Variable overwritten'); expect(vars2).to.have.property('TWO', 'TWO', 'Incorrect value'); expect(vars2).to.have.property('THREE', '3', 'Variable not merged'); expect(vars2).to.have.property('PYTHONPATH', 'PYTHONPATH', 'Incorrect value'); expect(vars2).to.have.property(processEnvPath, 'PATH', 'Incorrect value'); verifyAll(); }); test('Ensure path variables in target are overwritten', async () => { const source = { ONE: '1', TWO: 'TWO' }; const target = { ONE: 'ONE', THREE: '3', PYTHONPATH: 'PYTHONPATH' }; (target as any)[pathVariable] = 'PATH'; variablesService.mergeVariables(source, target, { overwrite: true }); expect(Object.keys(source)).lengthOf(2, 'Source variables modified'); expect(Object.keys(target)).lengthOf(5, 'Variables not merged'); expect(target).to.have.property('ONE', '1', 'Expected to be overwritten'); expect(target).to.have.property('TWO', 'TWO', 'Incorrect value'); expect(target).to.have.property('THREE', '3', 'Variable not merged'); expect(target).to.have.property('PYTHONPATH', 'PYTHONPATH', 'Incorrect value'); expect(target).to.have.property(processEnvPath, 'PATH', 'Incorrect value'); verifyAll(); }); }); }); PATHS.map((pathVariable) => { suite(`appendPath() (path var: ${pathVariable})`, () => { setup(() => { pathUtils .setup((pu) => pu.getPathVariableName()) // This always gets called. .returns(() => pathVariable as PathVar); // Pretend we're on a specific platform. }); test('Ensure appending PATH has no effect if an undefined value or empty string is provided and PATH does not exist in vars object', async () => { const vars = { ONE: '1' }; variablesService.appendPath(vars); expect(Object.keys(vars)).lengthOf(1, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); variablesService.appendPath(vars, ''); expect(Object.keys(vars)).lengthOf(1, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); variablesService.appendPath(vars, ' ', ''); expect(Object.keys(vars)).lengthOf(1, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); verifyAll(); }); test(`Ensure appending PATH has no effect if an empty string is provided and path does not exist in vars object (${pathVariable})`, async () => { const vars = { ONE: '1' }; (vars as any)[pathVariable] = 'PATH'; variablesService.appendPath(vars); expect(Object.keys(vars)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); expect(vars).to.have.property(processEnvPath, 'PATH', 'Incorrect value'); variablesService.appendPath(vars, ''); expect(Object.keys(vars)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); expect(vars).to.have.property(processEnvPath, 'PATH', 'Incorrect value'); variablesService.appendPath(vars, ' ', ''); expect(Object.keys(vars)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); expect(vars).to.have.property(processEnvPath, 'PATH', 'Incorrect value'); verifyAll(); }); test(`Ensure PATH is appeneded (${pathVariable})`, async () => { const vars = { ONE: '1' }; (vars as any)[pathVariable] = 'PATH'; const pathToAppend = `/usr/one${path.delimiter}/usr/three`; variablesService.appendPath(vars, pathToAppend); expect(Object.keys(vars)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); expect(vars).to.have.property( processEnvPath, `PATH${path.delimiter}${pathToAppend}`, 'Incorrect value', ); verifyAll(); }); }); }); suite('appendPythonPath()', () => { test('Ensure appending PYTHONPATH has no effect if an undefined value or empty string is provided and PYTHONPATH does not exist in vars object', async () => { const vars = { ONE: '1' }; variablesService.appendPythonPath(vars); expect(Object.keys(vars)).lengthOf(1, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); variablesService.appendPythonPath(vars, ''); expect(Object.keys(vars)).lengthOf(1, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); variablesService.appendPythonPath(vars, ' ', ''); expect(Object.keys(vars)).lengthOf(1, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); verifyAll(); }); test('Ensure appending PYTHONPATH has no effect if an empty string is provided and PYTHONPATH does not exist in vars object', async () => { const vars = { ONE: '1', PYTHONPATH: 'PYTHONPATH' }; variablesService.appendPythonPath(vars); expect(Object.keys(vars)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); expect(vars).to.have.property('PYTHONPATH', 'PYTHONPATH', 'Incorrect value'); variablesService.appendPythonPath(vars, ''); expect(Object.keys(vars)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); expect(vars).to.have.property('PYTHONPATH', 'PYTHONPATH', 'Incorrect value'); variablesService.appendPythonPath(vars, ' ', ''); expect(Object.keys(vars)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); expect(vars).to.have.property('PYTHONPATH', 'PYTHONPATH', 'Incorrect value'); verifyAll(); }); test('Ensure appending PYTHONPATH has no effect if an empty string is provided and PYTHONPATH does not exist in vars object', async () => { const vars = { ONE: '1', PYTHONPATH: 'PYTHONPATH' }; const pathToAppend = `/usr/one${path.delimiter}/usr/three`; variablesService.appendPythonPath(vars, pathToAppend); expect(Object.keys(vars)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('ONE', '1', 'Incorrect value'); expect(vars).to.have.property( 'PYTHONPATH', `PYTHONPATH${path.delimiter}${pathToAppend}`, 'Incorrect value', ); verifyAll(); }); }); }); suite('Parsing Environment Variables Files', () => { suite('parseEnvFile()', () => { test('Custom variables should be parsed from env file', () => { const vars = parseEnvFile(` X1234PYEXTUNITTESTVAR=1234 PYTHONPATH=../workspace5 `); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('X1234PYEXTUNITTESTVAR', '1234', 'X1234PYEXTUNITTESTVAR value is invalid'); expect(vars).to.have.property('PYTHONPATH', '../workspace5', 'PYTHONPATH value is invalid'); }); test('PATH and PYTHONPATH from env file should be returned as is', () => { const vars = parseEnvFile(` X=1 Y=2 PYTHONPATH=/usr/one/three:/usr/one/four # Unix PATH variable PATH=/usr/x:/usr/y # Windows Path variable Path=/usr/x:/usr/y `); const expectedPythonPath = '/usr/one/three:/usr/one/four'; const expectedPath = '/usr/x:/usr/y'; expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(5, 'Incorrect number of variables'); expect(vars).to.have.property('X', '1', 'X value is invalid'); expect(vars).to.have.property('Y', '2', 'Y value is invalid'); expect(vars).to.have.property('PYTHONPATH', expectedPythonPath, 'PYTHONPATH value is invalid'); expect(vars).to.have.property('PATH', expectedPath, 'PATH value is invalid'); }); test('Variable names must be alpha + alnum/underscore', () => { const vars = parseEnvFile(` SPAM=1234 ham=5678 Eggs=9012 1bogus2=... bogus 3=... bogus.4=... bogus-5=... bogus~6=... VAR1=3456 VAR_2=7890 _VAR_3=1234 `); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(6, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', '1234', 'value is invalid'); expect(vars).to.have.property('ham', '5678', 'value is invalid'); expect(vars).to.have.property('Eggs', '9012', 'value is invalid'); expect(vars).to.have.property('VAR1', '3456', 'value is invalid'); expect(vars).to.have.property('VAR_2', '7890', 'value is invalid'); expect(vars).to.have.property('_VAR_3', '1234', 'value is invalid'); }); test('Empty values become empty string', () => { const vars = parseEnvFile(` SPAM= `); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(1, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', '', 'value is invalid'); }); test('Outer quotation marks are removed and cause newline substitution', () => { const vars = parseEnvFile(` SPAM=12\\n34 HAM='56\\n78' EGGS="90\\n12" FOO='"34\\n56"' BAR="'78\\n90'" BAZ="\"AB\\nCD" VAR1="EF\\nGH VAR2=IJ\\nKL" VAR3='MN'OP' VAR4="QR"ST" `); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(10, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', '12\\n34', 'value is invalid'); expect(vars).to.have.property('HAM', '56\n78', 'value is invalid'); expect(vars).to.have.property('EGGS', '90\n12', 'value is invalid'); expect(vars).to.have.property('FOO', '"34\n56"', 'value is invalid'); expect(vars).to.have.property('BAR', "'78\n90'", 'value is invalid'); expect(vars).to.have.property('BAZ', '"AB\nCD', 'value is invalid'); expect(vars).to.have.property('VAR1', '"EF\\nGH', 'value is invalid'); expect(vars).to.have.property('VAR2', 'IJ\\nKL"', 'value is invalid'); // TODO: Should the outer marks be left? expect(vars).to.have.property('VAR3', "MN'OP", 'value is invalid'); expect(vars).to.have.property('VAR4', 'QR"ST', 'value is invalid'); }); test('Whitespace is ignored', () => { const vars = parseEnvFile(` SPAM=1234 HAM =5678 EGGS= 9012 FOO = 3456 BAR=7890 BAZ = ABCD VAR1=EFGH ... VAR2=IJKL VAR3=' MNOP ' `); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(9, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', '1234', 'value is invalid'); expect(vars).to.have.property('HAM', '5678', 'value is invalid'); expect(vars).to.have.property('EGGS', '9012', 'value is invalid'); expect(vars).to.have.property('FOO', '3456', 'value is invalid'); expect(vars).to.have.property('BAR', '7890', 'value is invalid'); expect(vars).to.have.property('BAZ', 'ABCD', 'value is invalid'); expect(vars).to.have.property('VAR1', 'EFGH ...', 'value is invalid'); expect(vars).to.have.property('VAR2', 'IJKL', 'value is invalid'); expect(vars).to.have.property('VAR3', ' MNOP ', 'value is invalid'); }); test('Blank lines are ignored', () => { const vars = parseEnvFile(` SPAM=1234 HAM=5678 `); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', '1234', 'value is invalid'); expect(vars).to.have.property('HAM', '5678', 'value is invalid'); }); test('Comments are ignored', () => { const vars = parseEnvFile(` # step 1 SPAM=1234 # step 2 HAM=5678 #step 3 EGGS=9012 # ... # done `); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(3, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', '1234', 'value is invalid'); expect(vars).to.have.property('HAM', '5678', 'value is invalid'); expect(vars).to.have.property('EGGS', '9012 # ...', 'value is invalid'); }); suite('variable substitution', () => { test('Basic substitution syntax', () => { const vars = parseEnvFile( '\ REPO=/home/user/git/foobar \n\ PYTHONPATH=${REPO}/foo:${REPO}/bar \n\ ', ); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('REPO', '/home/user/git/foobar', 'value is invalid'); expect(vars).to.have.property( 'PYTHONPATH', '/home/user/git/foobar/foo:/home/user/git/foobar/bar', 'value is invalid', ); }); test('Example from docs', () => { const vars = parseEnvFile( '\ VAR1=abc \n\ VAR2_A="${VAR1}\\ndef" \n\ VAR2_B="${VAR1}\\n"def \n\ ', ); expect(vars).to.not.equal(undefined, 'Variables is undefined'); expect(Object.keys(vars!)).lengthOf(3, 'Incorrect number of variables'); expect(vars).to.have.property('VAR1', 'abc', 'value is invalid'); expect(vars).to.have.property('VAR2_A', 'abc\ndef', 'value is invalid'); expect(vars).to.have.property('VAR2_B', '"abc\\n"def', 'value is invalid'); }); test('Curly braces are required for substitution', () => { const vars = parseEnvFile('\ SPAM=1234 \n\ EGGS=$SPAM \n\ '); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', '1234', 'value is invalid'); expect(vars).to.have.property('EGGS', '$SPAM', 'value is invalid'); }); test('Nested substitution is not supported', () => { const vars = parseEnvFile( '\ SPAM=EGGS \n\ EGGS=??? \n\ HAM1="-- ${${SPAM}} --"\n\ abcEGGSxyz=!!! \n\ HAM2="-- ${abc${SPAM}xyz} --"\n\ HAM3="-- ${${SPAM} --"\n\ HAM4="-- ${${SPAM}} ${EGGS} --"\n\ ', ); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(7, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', 'EGGS', 'value is invalid'); expect(vars).to.have.property('EGGS', '???', 'value is invalid'); expect(vars).to.have.property('HAM1', '-- ${${SPAM}} --', 'value is invalid'); expect(vars).to.have.property('abcEGGSxyz', '!!!', 'value is invalid'); expect(vars).to.have.property('HAM2', '-- ${abc${SPAM}xyz} --', 'value is invalid'); expect(vars).to.have.property('HAM3', '-- ${${SPAM} --', 'value is invalid'); expect(vars).to.have.property('HAM4', '-- ${${SPAM}} ${EGGS} --', 'value is invalid'); }); test('Other bad substitution syntax', () => { const vars = parseEnvFile( '\ SPAM=EGGS \n\ EGGS=??? \n\ HAM1=${} \n\ HAM2=${ \n\ HAM3=${SPAM+EGGS} \n\ HAM4=$SPAM \n\ ', ); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(6, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', 'EGGS', 'value is invalid'); expect(vars).to.have.property('EGGS', '???', 'value is invalid'); expect(vars).to.have.property('HAM1', '${}', 'value is invalid'); expect(vars).to.have.property('HAM2', '${', 'value is invalid'); expect(vars).to.have.property('HAM3', '${SPAM+EGGS}', 'value is invalid'); expect(vars).to.have.property('HAM4', '$SPAM', 'value is invalid'); }); test('Recursive substitution is allowed', () => { const vars = parseEnvFile( '\ REPO=/home/user/git/foobar \n\ PYTHONPATH=${REPO}/foo \n\ PYTHONPATH=${PYTHONPATH}:${REPO}/bar \n\ ', ); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(2, 'Incorrect number of variables'); expect(vars).to.have.property('REPO', '/home/user/git/foobar', 'value is invalid'); expect(vars).to.have.property( 'PYTHONPATH', '/home/user/git/foobar/foo:/home/user/git/foobar/bar', 'value is invalid', ); }); test('"$" may be escaped', () => { const vars = parseEnvFile( '\ SPAM=1234 \n\ EGGS=\\${SPAM}/foo:\\${SPAM}/bar \n\ HAM=$ ... $$ \n\ FOO=foo\\$bar \n\ ', ); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(4, 'Incorrect number of variables'); expect(vars).to.have.property('SPAM', '1234', 'value is invalid'); expect(vars).to.have.property('EGGS', '${SPAM}/foo:${SPAM}/bar', 'value is invalid'); expect(vars).to.have.property('HAM', '$ ... $$', 'value is invalid'); expect(vars).to.have.property('FOO', 'foo$bar', 'value is invalid'); }); test('base substitution variables', () => { const vars = parseEnvFile('\ PYTHONPATH=${REPO}/foo:${REPO}/bar \n\ ', { REPO: '/home/user/git/foobar', }); expect(vars).to.not.equal(undefined, 'Variables is undefiend'); expect(Object.keys(vars!)).lengthOf(1, 'Incorrect number of variables'); expect(vars).to.have.property( 'PYTHONPATH', '/home/user/git/foobar/foo:/home/user/git/foobar/bar', 'value is invalid', ); }); }); }); }); ```
/content/code_sandbox/src/test/common/variables/envVarsService.unit.test.ts
xml
2016-01-19T10:50:01
2024-08-12T21:05:24
pythonVSCode
DonJayamanne/pythonVSCode
2,078
6,511
```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.microsoft.bot.sample</groupId> <artifactId>bot-usingcards</artifactId> <version>sample</version> <packaging>jar</packaging> <name>${project.groupId}:${project.artifactId}</name> <description>This package contains the Using Cards sample using Spring Boot.</description> <url>path_to_url <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> <relativePath/> </parent> <licenses> <license> <url>path_to_url </license> </licenses> <developers> <developer> <name>Bot Framework Development</name> <email></email> <organization>Microsoft</organization> <organizationUrl>path_to_url </developer> </developers> <properties> <java.version>1.8</java.version> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> <start-class>com.microsoft.bot.sample.usingcards.Application</start-class> </properties> <repositories> <repository> <id>oss-sonatype</id> <name>oss-sonatype</name> <url> path_to_url </url> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>2.4.0</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.17.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.17.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-to-slf4j</artifactId> <version>2.17.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.microsoft.bot</groupId> <artifactId>bot-integration-spring</artifactId> <version>4.14.1</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.microsoft.bot</groupId> <artifactId>bot-dialogs</artifactId> <version>4.14.1</version> <scope>compile</scope> </dependency> </dependencies> <profiles> <profile> <id>build</id> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>false</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.3</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> <configuration> <mainClass>com.microsoft.bot.sample.usingcards.Application</mainClass> </configuration> </execution> </executions> </plugin> <plugin> <groupId>com.microsoft.azure</groupId> <artifactId>azure-webapp-maven-plugin</artifactId> <version>1.12.0</version> <configuration> <schemaVersion>V2</schemaVersion> <resourceGroup>${groupname}</resourceGroup> <appName>${botname}</appName> <appSettings> <property> <name>JAVA_OPTS</name> <value>-Dserver.port=80</value> </property> </appSettings> <runtime> <os>linux</os> <javaVersion>Java 8</javaVersion> <webContainer>Java SE</webContainer> </runtime> <deployment> <resources> <resource> <directory>${project.basedir}/target</directory> <includes> <include>*.jar</include> </includes> </resource> </resources> </deployment> </configuration> </plugin> </plugins> </build> </profile> <profile> <id>publish</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.3</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> </configuration> </plugin> <plugin> <groupId>org.sonatype.plugins</groupId> <artifactId>nexus-staging-maven-plugin</artifactId> <version>1.6.8</version> <extensions>true</extensions> <configuration> <skipRemoteStaging>true</skipRemoteStaging> <serverId>ossrh</serverId> <nexusUrl>path_to_url <autoReleaseAfterClose>true</autoReleaseAfterClose> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <configuration> <source>8</source> <failOnError>false</failOnError> </configuration> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project> ```
/content/code_sandbox/samples/java_springboot/06.using-cards/pom.xml
xml
2016-09-20T16:17:28
2024-08-16T02:44:00
BotBuilder-Samples
microsoft/BotBuilder-Samples
4,323
1,807
```xml import * as React from 'react'; /** Result of transpiling and/or transforming code */ export interface ITransformedCode { /** Transpiled code (defined unless there's an error) */ output?: string; /** Transpile/eval error, if any */ error?: string | string[]; } /** Transpiled and/or transformed example, eval'd to get the component to render. */ export interface ITransformedExample extends ITransformedCode { /** Component to render (defined unless there's an error) */ component?: React.ComponentType; } ```
/content/code_sandbox/packages/react-monaco-editor/src/interfaces/transformedCode.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
119
```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. --> <resources> <string name="app_name">RecyclerViewAnimations</string> </resources> ```
/content/code_sandbox/RecyclerView/RecyclerViewAnimations/app/src/main/res/values/strings.xml
xml
2016-03-08T22:27:22
2024-08-02T07:38:15
android-ui-toolkit-demos
googlearchive/android-ui-toolkit-demos
1,109
56
```xml import { AxiosInstance } from 'axios'; import { toChecksumAddress } from 'ethereumjs-util'; import { UNISWAP_UNI_CLAIM_API } from '@config/data'; import { ApiService } from '@services/ApiService'; import { ProviderHandler } from '@services/EthService'; import { UniDistributor } from '@services/EthService/contracts'; import { ClaimResult, ClaimState, ClaimType, Network, TAddress } from '@types'; import { mapAsync } from '@utils/asyncFilter'; import { CLAIM_CONFIG } from './config'; import { Claim, Response } from './types'; let instantiated = false; export default class ClaimsService { public static instance = new ClaimsService(); private service: AxiosInstance = ApiService.generateInstance({ baseURL: UNISWAP_UNI_CLAIM_API, timeout: 20000 }); constructor() { if (instantiated) { throw new Error(`ClaimsService has already been instantiated.`); } else { instantiated = true; } } public getClaims(type: ClaimType, addresses: TAddress[]) { return this.service .post( '', { addresses: addresses.map((a) => toChecksumAddress(a)) }, { baseURL: CLAIM_CONFIG[type].api } ) .then((res) => res.data) .then(({ claims }: Response) => { return claims; }) .catch((err) => { console.debug('[Claims]: Get Claims failed: ', err); return null; }); } public isClaimed( network: Network, type: ClaimType, claims: Record<string, Claim | null> ): Promise<ClaimResult[]> { const provider = new ProviderHandler(network); return mapAsync(Object.entries(claims), async ([address, claim]) => { if (claim !== null) { const claimed = await provider .call({ to: CLAIM_CONFIG[type].tokenDistributor, data: UniDistributor.isClaimed.encodeInput({ index: claim.Index }) }) .then((data) => UniDistributor.isClaimed.decodeOutput(data)) .then(({ claimed }) => claimed); const config = CLAIM_CONFIG[type]; const amount = config.processAmount ? config.processAmount(claim.Amount) : claim.Amount; return { address, state: claimed ? ClaimState.CLAIMED : ClaimState.UNCLAIMED, amount, index: claim.Index }; } return { address, state: ClaimState.NO_CLAIM, amount: '0x00' }; }); } } ```
/content/code_sandbox/src/services/ApiService/Claims/Claims.ts
xml
2016-12-04T01:35:27
2024-08-14T21:41:58
MyCrypto
MyCryptoHQ/MyCrypto
1,347
553
```xml export { PermissionResponse, PermissionStatus, PermissionExpiration, PermissionHookOptions, } from 'expo-modules-core'; // @needsAudit /** * Describes the current generation of the cellular connection. It is an enum with these possible * values: */ export enum CellularGeneration { /** * Either we are not currently connected to a cellular network or type could not be determined. */ UNKNOWN = 0, /** * Currently connected to a 2G cellular network. Includes CDMA, EDGE, GPRS, and IDEN type connections. */ CELLULAR_2G = 1, /** * Currently connected to a 3G cellular network. Includes EHRPD, EVDO, HSPA, HSUPA, HSDPA, HSPAP, and UTMS type connections. */ CELLULAR_3G = 2, /** * Currently connected to a 4G cellular network. Includes LTE type connections. */ CELLULAR_4G = 3, /** * Currently connected to a 5G cellular network. Includes NR and NRNSA type connections. */ CELLULAR_5G = 4, } ```
/content/code_sandbox/packages/expo-cellular/src/Cellular.types.ts
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
253
```xml /* * Squidex Headless CMS * * @license */ import slugify from 'slugify'; import { MathHelper } from './math-helper'; const IMAGE_REGEX = /!\[(?<alt>[^\]]*)\]\((?<url>.*?)([\s]["\s]*(?<name>[^")]*)["\s]*)?\)/; const IMAGES_REGEX = /!\[(?<alt>[^\]]*)\]\((?<url>.*?)([\s]["\s]*(?<name>[^")]*)["\s]*)?\)/g; export type MarkdownImage = { url: string; name: string }; export function markdownHasImage(markdown: string) { return !!markdown && !!markdown.match(IMAGES_REGEX); } export function markdownExtractImage(markdown: string): MarkdownImage | null { if (!markdown) { return null; } const match = markdown.match(IMAGE_REGEX); if (!match?.groups) { return null; } const { url, alt, name } = match.groups as { url: string; alt?: string; name?: string }; if (!isURL(url)) { return null; } return toImage({ url, alt, name }); } export async function markdownTransformImages(markdown: string, replace: (image: MarkdownImage) => Promise<string>) { if (!markdown) { return markdown; } const jobs: { id: string; url: string; name?: string; alt?: string }[] = []; let transformed = markdown.replace(IMAGES_REGEX, (_, alt, url, _other, name) => { const id = MathHelper.guid(); jobs.push({ id, url, name, alt }); return id; }); const promises = jobs.map(async job => { const url = await replace(toImage(job)); return { job, url }; }); const results = await Promise.all(promises); for (const result of results) { const { job, url } = result; const name = job.name ? ` "${job.name}"` : ''; transformed = transformed.replace(result.job.id, `![${job.alt || ''}](${url}${name})`); } return transformed; } const IMAGE_EXTENSIONS = ['.avif', '.jpeg', '.jpg', '.png', '.webp']; function toImage(image: { url: string; name?: string; alt?: string }): MarkdownImage { let name = image.name || image.alt || 'image'; name = slugify(name, { lower: true, trim: true }); if (!IMAGE_EXTENSIONS.find(ex => name.endsWith(ex))) { name += '.webp'; } return { url: image.url, name }; } function isURL(input: string) { try { new URL(input); return true; } catch { return false; } } ```
/content/code_sandbox/frontend/src/app/framework/utils/markdown-transform.ts
xml
2016-08-29T05:53:40
2024-08-16T17:39:38
squidex
Squidex/squidex
2,222
604
```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 import Complex128 = require( '@stdlib/complex/float64/ctor' ); /** * Tests whether two double-precision complex floating-point numbers are not equal. * * @param z1 - first complex number * @param z2 - second complex number * @returns boolean indicating if both complex numbers are not equal * * @example * var Complex128 = require( '@stdlib/complex/float64/ctor' ); * * var z1 = new Complex128( 5.0, 3.0 ); * var z2 = new Complex128( 5.0, -3.0 ); * * var v = isNotEqual( z1, z2 ); * // returns true */ declare function isNotEqual( z1: Complex128, z2: Complex128 ): boolean; // EXPORTS // export = isNotEqual; ```
/content/code_sandbox/lib/node_modules/@stdlib/complex/float64/base/assert/is-not-equal/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
239
```xml import React, { useContext, useEffect, useState } from 'react'; import { useParams, Link, useNavigate } from 'react-router-dom'; import { MdFavorite, MdFavoriteBorder } from 'react-icons/md'; import { getActorById, GetActorByIdResponse, addFavoritedActor, deleteFavoritedActor, getIfFavoritedActor } from '@movie/dataconnect'; import { onAuthStateChanged, User } from 'firebase/auth'; import { AuthContext } from '@/lib/firebase'; import NotFound from './NotFound'; export default function ActorPage() { const { id } = useParams<{ id: string }>(); const actorId = id || ''; const [actor, setActor] = useState<GetActorByIdResponse['actor'] | null>(null); const [loading, setLoading] = useState(true); const [authUser, setAuthUser] = useState<User | null>(null); const [isFavorited, setIsFavorited] = useState(false); const auth = useContext(AuthContext); const navigate = useNavigate(); useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { async function checkIfFavorited() { try { const response = await getIfFavoritedActor({ actorId }); setIsFavorited(!!response.data.favorite_actor); } catch (error) { console.error('Error checking if favorited:', error); } } if (user) { setAuthUser(user); checkIfFavorited(); } }); return () => unsubscribe(); }, [auth, actorId]); useEffect(() => { if (actorId) { const fetchActor = async () => { try { const response = await getActorById({ id: actorId }); if (response.data.actor) { setActor(response.data.actor); } else { navigate('/not-found'); } } catch (error) { console.error('Error fetching actor:', error); navigate('/not-found'); } finally { setLoading(false); } }; fetchActor(); } }, [actorId, navigate]); async function handleFavoriteToggle() { if (!authUser) return; try { if (isFavorited) { await deleteFavoritedActor({ actorId }); } else { await addFavoritedActor({ actorId }); } setIsFavorited(!isFavorited); } catch (error) { console.error('Error updating favorite status:', error); } } if (loading) return <p>Loading...</p>; return actor ? ( <div className="container mx-auto p-4 bg-gray-900 min-h-screen text-white"> <div className="flex flex-col md:flex-row mb-8"> <img className="w-full md:w-1/3 object-cover rounded-lg shadow-md" src={actor.imageUrl} alt={actor.name} /> <div className="md:ml-8 mt-4 md:mt-0 flex-1"> <h1 className="text-5xl font-bold mb-2">{actor.name}</h1> <div className="mt-4 flex space-x-4"> <button className="flex items-center justify-center p-1 text-red-500 hover:text-red-600 transition-colors duration-200" aria-label="Favorite" onClick={handleFavoriteToggle} > {isFavorited ? <MdFavorite size={24} /> : <MdFavoriteBorder size={24} />} </button> </div> </div> </div> <div className="mt-8"> <h2 className="text-2xl font-bold mb-2">Main Roles</h2> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"> {actor.mainActors.map((movie) => ( <Link key={movie.id} to={`/movie/${movie.id}`}> <div className="bg-gray-800 rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow duration-200 cursor-pointer"> <img className="w-full h-48 object-cover" src={movie.imageUrl} alt={movie.title} /> <div className="p-4"> <h3 className="font-bold text-lg mb-1 text-white">{movie.title}</h3> <p className="text-sm text-gray-400">{movie.genre}</p> <div className="flex flex-wrap gap-1 mt-2"> {movie.tags?.map((tag, index) => ( <span key={index} className="bg-gray-700 text-white px-2 py-1 rounded-full text-xs">{tag}</span> ))} </div> </div> </div> </Link> ))} </div> </div> <div className="mt-8"> <h2 className="text-2xl font-bold mb-2">Supporting Roles</h2> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"> {actor.supportingActors.map((movie) => ( <Link key={movie.id} to={`/movie/${movie.id}`}> <div className="bg-gray-800 rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow duration-200 cursor-pointer"> <img className="w-full h-48 object-cover" src={movie.imageUrl} alt={movie.title} /> <div className="p-4"> <h3 className="font-bold text-lg mb-1 text-white">{movie.title}</h3> <p className="text-sm text-gray-400">{movie.genre}</p> <div className="flex flex-wrap gap-1 mt-2"> {movie.tags?.map((tag, index) => ( <span key={index} className="bg-gray-700 text-white px-2 py-1 rounded-full text-xs">{tag}</span> ))} </div> </div> </div> </Link> ))} </div> </div> </div> ) : ( <NotFound /> ); } ```
/content/code_sandbox/dataconnect/app/src/pages/Actor.tsx
xml
2016-04-26T17:13:48
2024-08-16T13:54:58
quickstart-js
firebase/quickstart-js
5,069
1,334
```xml import { useEffect } from "react" import { queries } from "@/modules/orders/graphql" import useFullOrders from "@/modules/orders/hooks/useFullOrders" import { columnNumberAtom, filterAtom } from "@/store/progress.store" import { useAtomValue } from "jotai" import { ORDER_ITEM_STATUSES, ORDER_STATUSES } from "@/lib/constants" import { Button } from "@/components/ui/button" import Loader from "@/components/ui/loader" import ActiveOrder from "./ActiveOrder" import PrintProgress from "./PrintProgress" const ActiveOrders = () => { const filter = useAtomValue(filterAtom) const num = useAtomValue(columnNumberAtom) const { loading, fullOrders, handleLoadMore, totalCount, subToOrderStatuses, subToItems, } = useFullOrders({ variables: filter, query: queries.progressHistory, }) useEffect(() => { subToOrderStatuses(ORDER_STATUSES.ALL) subToItems(ORDER_ITEM_STATUSES.ALL) }, []) if (loading) { return null } const arr = [] for (let i = 0; i < num; i++) { arr[i] = fullOrders.filter((_, index) => index % num === i) } return ( <div className="mx-4 grid gap-3 my-3 flex-auto" style={{ gridTemplateColumns: `repeat(${num}, minmax(0, 1fr))` }} > {arr.map((orders, idx) => ( <div className="space-y-3" key={idx}> {orders.map((order) => ( <ActiveOrder {...order} key={order._id} /> ))} </div> ))} {totalCount > fullOrders.length && ( <Button className="my-1" onClick={handleLoadMore}> {fullOrders.length}/{totalCount} </Button> )} {loading && <Loader className="absolute inset-0 bg-white/40" />} <PrintProgress /> </div> ) } export default ActiveOrders ```
/content/code_sandbox/pos/app/(main)/(orders)/components/progress/ActiveOrders.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
453
```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="cat_colors_title" translatable="false">Color</string> <string name="cat_colors_description" translatable="false"> Material uses color to create meaningful experiences while also expressing hierarchy, state, and brand identity. </string> <string name="cat_color_label_enabled" translatable="false">Harmonization Enabled</string> <string name="cat_button_label_proceed" translatable="false">Proceed</string> <string name="cat_button_label_error" translatable="false">Error</string> <string name="cat_button_text" translatable="false">Material button</string> <string name="cat_unelevated_button_text" translatable="false">Unelevated button</string> <string name="cat_color_hex_value_text" translatable="false">Color hex value: %1$s</string> <string name="cat_color_harmonization" translatable="false">Color Harmonization Demo</string> <string name="cat_color_dynamic_palette" translatable="false">Dynamic Palette Demo</string> <string name="cat_color_copy" translatable="false">Copy colors</string> <string name="cat_color_res" translatable="false">%1$s%2$s</string> <string name="cat_color_role_background" translatable="false">Background</string> <string name="cat_color_role_on_background" translatable="false">On Background</string> <string name="cat_color_role_surface" translatable="false">Surface</string> <string name="cat_color_role_on_surface" translatable="false">On Surface</string> <string name="cat_color_role_surface_variant" translatable="false">Surface Variant</string> <string name="cat_color_role_on_surface_variant" translatable="false">On Surface Variant</string> <string name="cat_color_role_inverse_surface" translatable="false">Inverse Surface</string> <string name="cat_color_role_inverse_on_surface" translatable="false">Inverse On Surface</string> <string name="cat_color_role_surface_bright" translatable="false">Surface Bright</string> <string name="cat_color_role_surface_dim" translatable="false">Surface Dim</string> <string name="cat_color_role_surface_container" translatable="false">Surface Container</string> <string name="cat_color_role_surface_container_low" translatable="false">Surface Container Low</string> <string name="cat_color_role_surface_container_high" translatable="false">Surface Container High</string> <string name="cat_color_role_surface_container_lowest" translatable="false">Surface Container Lowest</string> <string name="cat_color_role_surface_container_highest" translatable="false">Surface Container Highest</string> <string name="cat_color_surfaces" translatable="false">Surfaces</string> <string name="cat_color_utility" translatable="false">Utility</string> <string name="cat_color_content" translatable="false">Content</string> <string name="cat_color_utility_note" translatable="false">Note: When dynamic color is enabled, the Error color roles will look different from baseline because they will be harmonized with Primary by default.</string> <string name="cat_color_role_primary" translatable="false">Primary</string> <string name="cat_color_role_on_primary" translatable="false">On Primary</string> <string name="cat_color_role_primary_container" translatable="false">Primary Container</string> <string name="cat_color_role_on_primary_container" translatable="false">On Primary Container</string> <string name="cat_color_role_primary_fixed" translatable="false">Primary Fixed</string> <string name="cat_color_role_primary_fixed_dim" translatable="false">Primary Fixed Dim</string> <string name="cat_color_role_on_primary_fixed" translatable="false">On Primary Fixed</string> <string name="cat_color_role_on_primary_fixed_variant" translatable="false">On Primary Fixed Variant</string> <string name="cat_color_role_inverse_primary" translatable="false">Inverse Primary</string> <string name="cat_color_role_secondary" translatable="false">Secondary</string> <string name="cat_color_role_on_secondary" translatable="false">On Secondary</string> <string name="cat_color_role_secondary_container" translatable="false">Secondary Container</string> <string name="cat_color_role_on_secondary_container" translatable="false">On Secondary Container</string> <string name="cat_color_role_secondary_fixed" translatable="false">Secondary Fixed</string> <string name="cat_color_role_secondary_fixed_dim" translatable="false">Secondary Fixed Dim</string> <string name="cat_color_role_on_secondary_fixed" translatable="false">On Secondary Fixed</string> <string name="cat_color_role_on_secondary_fixed_variant" translatable="false">On Secondary Fixed Variant</string> <string name="cat_color_role_tertiary" translatable="false">Tertiary</string> <string name="cat_color_role_on_tertiary" translatable="false">On Tertiary</string> <string name="cat_color_role_tertiary_container" translatable="false">Tertiary Container</string> <string name="cat_color_role_on_tertiary_container" translatable="false">On Tertiary Container</string> <string name="cat_color_role_tertiary_fixed" translatable="false">Tertiary Fixed</string> <string name="cat_color_role_tertiary_fixed_dim" translatable="false">Tertiary Fixed Dim</string> <string name="cat_color_role_on_tertiary_fixed" translatable="false">On Tertiary Fixed</string> <string name="cat_color_role_on_tertiary_fixed_variant" translatable="false">On Tertiary Fixed Variant</string> <string name="cat_color_role_error" translatable="false">Error</string> <string name="cat_color_role_on_error" translatable="false">On Error</string> <string name="cat_color_role_error_container" translatable="false">Error Container</string> <string name="cat_color_role_on_error_container" translatable="false">On Error Container</string> <string name="cat_color_role_outline" translatable="false">Outline</string> <string name="cat_color_role_outline_variant" translatable="false">Outline Variant</string> <string name="cat_color_role_yellow" translatable="false">Yellow</string> <string name="cat_color_role_on_yellow" translatable="false">On Yellow</string> <string name="cat_color_role_yellow_container" translatable="false">Yellow Container</string> <string name="cat_color_role_on_yellow_container" translatable="false">On Yellow Container</string> <string name="cat_color_role_green" translatable="false">Green</string> <string name="cat_color_role_on_green" translatable="false">On Green</string> <string name="cat_color_role_green_container" translatable="false">Green Container</string> <string name="cat_color_role_on_green_container" translatable="false">On Green Container</string> <string name="cat_color_role_blue" translatable="false">Blue</string> <string name="cat_color_role_on_blue" translatable="false">On Blue</string> <string name="cat_color_role_blue_container" translatable="false">Blue Container</string> <string name="cat_color_role_on_blue_container" translatable="false">On Blue Container</string> <string name="cat_color_role__error" translatable="false">Error</string> <string name="cat_color_role_harmonized_error" translatable="false">Harmonized Error</string> <string name="cat_color_role_harmonized_yellow" translatable="false">Harmonized Yellow</string> <string name="cat_color_role_harmonized_green" translatable="false">Harmonized Green</string> <string name="cat_color_role_harmonized_blue" translatable="false">Harmonized Blue</string> <string name="cat_red_button_dark" translatable="false">Error Button 1</string> <string name="cat_red_button_light" translatable="false">Error Button 2</string> <string name="cat_yellow_button_dark" translatable="false">Yellow Button 1</string> <string name="cat_yellow_button_light" translatable="false">Yellow Button 2</string> <string name="cat_green_button_dark" translatable="false">Green Button 1</string> <string name="cat_green_button_light" translatable="false">Green Button 2</string> <string name="cat_blue_button_dark" translatable="false">Blue Button 1</string> <string name="cat_blue_button_light" translatable="false">Blue Button 2</string> <string-array name="cat_error_strings"> <item>@string/cat_color_role_error</item> <item>@string/cat_color_role_on_error</item> <item>@string/cat_color_role_error_container</item> <item>@string/cat_color_role_on_error_container</item> </string-array> <string-array name="cat_yellow_strings"> <item>@string/cat_color_role_yellow</item> <item>@string/cat_color_role_on_yellow</item> <item>@string/cat_color_role_yellow_container</item> <item>@string/cat_color_role_on_yellow_container</item> </string-array> <string-array name="cat_green_strings"> <item>@string/cat_color_role_green</item> <item>@string/cat_color_role_on_green</item> <item>@string/cat_color_role_green_container</item> <item>@string/cat_color_role_on_green_container</item> </string-array> <string-array name="cat_blue_strings"> <item>@string/cat_color_role_blue</item> <item>@string/cat_color_role_on_blue</item> <item>@string/cat_color_role_blue_container</item> <item>@string/cat_color_role_on_blue_container</item> </string-array> </resources> ```
/content/code_sandbox/catalog/java/io/material/catalog/color/res/values/strings.xml
xml
2016-12-05T16:11:29
2024-08-16T17:51:42
material-components-android
material-components/material-components-android
16,176
2,276
```xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE header PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "path_to_url"> <!-- file LICENSE_1_0.txt or copy at path_to_url --> <header name="boost/signals2/trackable.hpp"> <namespace name="boost"> <namespace name="signals2"> <class name="trackable"> <purpose>Provided to ease porting for code using the boost::signals::trackable class from the original Boost.Signals library.</purpose> <description> <para>Use of the <code>trackable</code> class is not recommended for new code. The <code>trackable</code> class is not thread-safe since <code>trackable</code> objects disconnect their associated connections in the <code>trackable</code> destructor. Since the <code>trackable</code> destructor is not run until after the destructors of any derived classes have completed, that leaves open a window where a partially destructed object can still have active connections. </para> <para> The preferred method of automatic connection management with Boost.Signals2 is to manage the lifetime of tracked objects with <code>shared_ptr</code>s and to use the <methodname>signals2::slot::track</methodname> method to track their lifetimes.</para> <para>The <code>trackable</code> class provides automatic disconnection of signals and slots when objects bound in slots (via pointer or reference) are destroyed. <code>trackable</code> class may only be used as a public base class for some other class; when used as such, that class may be bound to function objects used as part of slots. The manner in which a <code>trackable</code> object tracks the set of signal-slot connections it is a part of is unspecified.</para> <para>The actual use of <code>trackable</code> is contingent on the presence of appropriate <functionname>visit_each</functionname> overloads for any type that may contain pointers or references to trackable objects.</para> </description> <constructor> <effects><para>Sets the list of connected slots to empty.</para></effects> <throws><para>Will not throw.</para></throws> </constructor> <constructor> <parameter name="other"> <paramtype>const <classname>trackable</classname>&amp;</paramtype> </parameter> <effects><para>Sets the list of connected slots to empty.</para></effects> <throws><para>Will not throw.</para></throws> <rationale><para>Signal-slot connections can only be created via calls to an explicit connect method, and therefore cannot be created here when trackable objects are copied.</para></rationale> </constructor> <destructor> <effects><para>Disconnects all signal/slot connections that contain a pointer or reference to this trackable object that can be found by <functionname>visit_each</functionname>.</para></effects> </destructor> <copy-assignment> <parameter name="other"> <paramtype>const <classname>trackable</classname>&amp;</paramtype> </parameter> <effects><para>Sets the list of connected slots to empty.</para></effects> <returns><para><code>*this</code></para></returns> <throws><para>Will not throw.</para></throws> <rationale><para>Signal-slot connections can only be created via calls to an explicit connect method, and therefore cannot be created here when trackable objects are copied.</para></rationale> </copy-assignment> </class> </namespace> </namespace> </header> ```
/content/code_sandbox/deps/boost_1_66_0/libs/signals2/doc/reference/trackable.xml
xml
2016-09-05T10:18:44
2024-08-11T13:21:40
LiquidCore
LiquidPlayer/LiquidCore
1,010
861
```xml import cn from "classnames"; import React, { ComponentType, FunctionComponent, HTMLAttributes, Ref, } from "react"; import { AlertTriangleIcon, CalendarInformationIcon, ConversationChatTextIcon, MessagesBubbleSquareIcon, QuestionHelpMessageIcon, SvgIcon, } from "coral-ui/components/icons"; import { withForwardRef, withStyles } from "coral-ui/hocs"; import styles from "./MessageBoxIcon.css"; interface Props extends Omit<HTMLAttributes<HTMLSpanElement>, "color"> { /** * This prop can be used to add custom classnames. * It is handled by the `withStyles `HOC. */ classes: typeof styles; size?: "xs" | "sm" | "md" | "lg" | "xl"; /** The name of the icon to render */ icon: string; /** Internal: Forwarded Ref */ forwardRef?: Ref<HTMLSpanElement>; } export const MessageBoxIcon: FunctionComponent<Props> = (props) => { const { classes, className } = props; const rootClassName = cn(classes.root, className); // This maps the Material icon names to new Streamline icon names const iconMapping: { [index: string]: ComponentType } = { question_answer: ConversationChatTextIcon, today: CalendarInformationIcon, help_outline: QuestionHelpMessageIcon, warning: AlertTriangleIcon, chat_bubble_outline: MessagesBubbleSquareIcon, }; return ( <SvgIcon className={rootClassName} Icon={iconMapping[props.icon]} ref={props.forwardRef} /> ); }; MessageBoxIcon.defaultProps = { size: "md", }; const enhanced = withForwardRef(withStyles(styles)(MessageBoxIcon)); export default enhanced; ```
/content/code_sandbox/client/src/core/client/stream/common/MessageBox/MessageBoxIcon.tsx
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
380
```xml import styled from '@emotion/styled'; import Avatar from '@mui/material/Avatar'; import ListItem from '@mui/material/ListItem'; import ListItemText from '@mui/material/ListItemText'; import { useTheme } from '@mui/styles'; import React from 'react'; import { useSettings } from '../../providers/PersistenceSettingProvider'; import CopyToClipBoard from '../CopyClipboard'; import { Npm, Pnpm, Yarn } from '../Icons'; const InstallItem = styled(ListItem)({ padding: 0, ':hover': { backgroundColor: 'transparent', }, }); const InstallListItemText = styled(ListItemText)({ padding: '0 0 0 10px', margin: 0, }); const PackageMangerAvatar = styled(Avatar)({ backgroundColor: 'transparent', padding: 0, marginLeft: 0, }); export enum DependencyManager { NPM = 'npm', YARN = 'yarn', PNPM = 'pnpm', } interface Interface { packageName: string; dependencyManager: DependencyManager; packageVersion?: string; } export function getGlobalInstall(isLatest, isGlobal, packageVersion, packageName, isYarn = false) { const name = isGlobal ? `${isYarn ? '' : '-g'} ${packageVersion && !isLatest ? `${packageName}@${packageVersion}` : packageName}` : packageVersion && !isLatest ? `${packageName}@${packageVersion}` : packageName; return name.trim(); } const InstallListItem: React.FC<Interface> = ({ packageName, dependencyManager, packageVersion, }) => { const { localSettings } = useSettings(); const theme = useTheme(); const isLatest = localSettings[packageName]?.latest ?? false; const isGlobal = localSettings[packageName]?.global ?? false; switch (dependencyManager) { case DependencyManager.NPM: return ( <InstallItem data-testid={'installListItem-npm'}> <PackageMangerAvatar alt="npm" sx={{ bgcolor: theme.palette.white }}> <Npm /> </PackageMangerAvatar> <InstallListItemText primary={ <CopyToClipBoard dataTestId="installNpm" text={`npm install ${getGlobalInstall(isLatest, isGlobal, packageVersion, packageName)}`} title={`npm install ${getGlobalInstall(isLatest, isGlobal, packageVersion, packageName)}`} /> } /> </InstallItem> ); case DependencyManager.YARN: return ( <InstallItem data-testid={'installListItem-yarn'}> <PackageMangerAvatar alt="yarn" sx={{ bgcolor: theme.palette.white }}> <Yarn /> </PackageMangerAvatar> <InstallListItemText primary={ <CopyToClipBoard dataTestId="installYarn" text={ isGlobal ? `yarn ${localSettings.yarnModern ? '' : 'global'} add ${getGlobalInstall( isGlobal, packageVersion, packageName, true )}` : `yarn add ${getGlobalInstall(isLatest, isGlobal, packageVersion, packageName, true)}` } title={ isGlobal ? `yarn global add ${getGlobalInstall( isGlobal, packageVersion, packageName, true )}` : `yarn add ${getGlobalInstall(isLatest, isGlobal, packageVersion, packageName, true)}` } /> } /> </InstallItem> ); case DependencyManager.PNPM: return ( <InstallItem data-testid={'installListItem-pnpm'}> <PackageMangerAvatar alt={'pnpm'} sx={{ bgcolor: theme.palette.white }}> <Pnpm /> </PackageMangerAvatar> <InstallListItemText primary={ <CopyToClipBoard dataTestId="installPnpm" text={`pnpm install ${getGlobalInstall(isLatest, isGlobal, packageVersion, packageName)}`} title={`pnpm install ${getGlobalInstall(isLatest, isGlobal, packageVersion, packageName)}`} /> } /> </InstallItem> ); default: return null; } }; export default InstallListItem; ```
/content/code_sandbox/packages/ui-components/src/components/Install/InstallListItem.tsx
xml
2016-04-15T16:21:12
2024-08-16T09:38:01
verdaccio
verdaccio/verdaccio
16,189
900
```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 /** * Returns an array of an object's inherited enumerable symbol properties. * * ## Notes * * - Property order is not guaranteed, as object property enumeration is not specified according to the ECMAScript specification. In practice, however, most engines use insertion order to sort an object's properties, thus allowing for deterministic extraction. * - If provided `null` or `undefined`, the function returns an empty array. * * @param value - input object * @param level - inheritance level * @throws second argument must be a positive integer * @returns a list of inherited enumerable symbol properties * * @example * var symbols = inheritedEnumerablePropertySymbols( [] ); */ declare function inheritedEnumerablePropertySymbols( value: any, level?: number ): Array<symbol>; // EXPORTS // export = inheritedEnumerablePropertySymbols; ```
/content/code_sandbox/lib/node_modules/@stdlib/utils/inherited-enumerable-property-symbols/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
232
```xml import * as React from 'react'; import { Component } from 'react'; import { Animated, Platform } from 'react-native'; import { State } from '../../State'; import { BaseButton } from '../GestureButtons'; import { GestureEvent, HandlerStateChangeEvent, } from '../../handlers/gestureHandlerCommon'; import type { NativeViewGestureHandlerPayload } from '../../handlers/GestureHandlerEventPayload'; import type { TouchableNativeFeedbackExtraProps } from './TouchableNativeFeedbackProps'; import type { GenericTouchableProps } from './GenericTouchableProps'; /** * Each touchable is a states' machine which preforms transitions. * On very beginning (and on the very end or recognition) touchable is * UNDETERMINED. Then it moves to BEGAN. If touchable recognizes that finger * travel outside it transits to special MOVED_OUTSIDE state. Gesture recognition * finishes in UNDETERMINED state. */ export const TOUCHABLE_STATE = { UNDETERMINED: 0, BEGAN: 1, MOVED_OUTSIDE: 2, } as const; type TouchableState = typeof TOUCHABLE_STATE[keyof typeof TOUCHABLE_STATE]; interface InternalProps { extraButtonProps: TouchableNativeFeedbackExtraProps; onStateChange?: (oldState: TouchableState, newState: TouchableState) => void; } // TODO: maybe can be better // TODO: all clearTimeout have ! added, maybe they shouldn't ? type Timeout = ReturnType<typeof setTimeout> | null | undefined; /** * GenericTouchable is not intented to be used as it is. * Should be treated as a source for the rest of touchables */ export default class GenericTouchable extends Component< GenericTouchableProps & InternalProps > { static defaultProps = { delayLongPress: 600, extraButtonProps: { rippleColor: 'transparent', exclusive: true, }, }; // Timeout handlers pressInTimeout: Timeout; pressOutTimeout: Timeout; longPressTimeout: Timeout; // This flag is required since recognition of longPress implies not-invoking onPress longPressDetected = false; pointerInside = true; // State of touchable STATE: TouchableState = TOUCHABLE_STATE.UNDETERMINED; // handlePressIn in called on first touch on traveling inside component. // Handles state transition with delay. handlePressIn() { if (this.props.delayPressIn) { this.pressInTimeout = setTimeout(() => { this.moveToState(TOUCHABLE_STATE.BEGAN); this.pressInTimeout = null; }, this.props.delayPressIn); } else { this.moveToState(TOUCHABLE_STATE.BEGAN); } if (this.props.onLongPress) { const time = (this.props.delayPressIn || 0) + (this.props.delayLongPress || 0); this.longPressTimeout = setTimeout(this.onLongPressDetected, time); } } // handleMoveOutside in called on traveling outside component. // Handles state transition with delay. handleMoveOutside() { if (this.props.delayPressOut) { this.pressOutTimeout = this.pressOutTimeout || setTimeout(() => { this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE); this.pressOutTimeout = null; }, this.props.delayPressOut); } else { this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE); } } // handleGoToUndetermined transits to UNDETERMINED state with proper delay handleGoToUndetermined() { clearTimeout(this.pressOutTimeout!); // TODO: maybe it can be undefined if (this.props.delayPressOut) { this.pressOutTimeout = setTimeout(() => { if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) { this.moveToState(TOUCHABLE_STATE.BEGAN); } this.moveToState(TOUCHABLE_STATE.UNDETERMINED); this.pressOutTimeout = null; }, this.props.delayPressOut); } else { if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) { this.moveToState(TOUCHABLE_STATE.BEGAN); } this.moveToState(TOUCHABLE_STATE.UNDETERMINED); } } componentDidMount() { this.reset(); } // Reset timeout to prevent memory leaks. reset() { this.longPressDetected = false; this.pointerInside = true; clearTimeout(this.pressInTimeout!); clearTimeout(this.pressOutTimeout!); clearTimeout(this.longPressTimeout!); this.pressOutTimeout = null; this.longPressTimeout = null; this.pressInTimeout = null; } // All states' transitions are defined here. moveToState(newState: TouchableState) { if (newState === this.STATE) { // Ignore dummy transitions return; } if (newState === TOUCHABLE_STATE.BEGAN) { // First touch and moving inside this.props.onPressIn?.(); } else if (newState === TOUCHABLE_STATE.MOVED_OUTSIDE) { // Moving outside this.props.onPressOut?.(); } else if (newState === TOUCHABLE_STATE.UNDETERMINED) { // Need to reset each time on transition to UNDETERMINED this.reset(); if (this.STATE === TOUCHABLE_STATE.BEGAN) { // ... and if it happens inside button. this.props.onPressOut?.(); } } // Finally call lister (used by subclasses) this.props.onStateChange?.(this.STATE, newState); // ... and make transition. this.STATE = newState; } onGestureEvent = ({ nativeEvent: { pointerInside }, }: GestureEvent<NativeViewGestureHandlerPayload>) => { if (this.pointerInside !== pointerInside) { if (pointerInside) { this.onMoveIn(); } else { this.onMoveOut(); } } this.pointerInside = pointerInside; }; onHandlerStateChange = ({ nativeEvent, }: HandlerStateChangeEvent<NativeViewGestureHandlerPayload>) => { const { state } = nativeEvent; if (state === State.CANCELLED || state === State.FAILED) { // Need to handle case with external cancellation (e.g. by ScrollView) this.moveToState(TOUCHABLE_STATE.UNDETERMINED); } else if ( // This platform check is an implication of slightly different behavior of handlers on different platform. // And Android "Active" state is achieving on first move of a finger, not on press in. // On iOS event on "Began" is not delivered. state === (Platform.OS !== 'android' ? State.ACTIVE : State.BEGAN) && this.STATE === TOUCHABLE_STATE.UNDETERMINED ) { // Moving inside requires this.handlePressIn(); } else if (state === State.END) { const shouldCallOnPress = !this.longPressDetected && this.STATE !== TOUCHABLE_STATE.MOVED_OUTSIDE && this.pressOutTimeout === null; this.handleGoToUndetermined(); if (shouldCallOnPress) { // Calls only inside component whether no long press was called previously this.props.onPress?.(); } } }; onLongPressDetected = () => { this.longPressDetected = true; // Checked for in the caller of `onLongPressDetected`, but better to check twice this.props.onLongPress?.(); }; componentWillUnmount() { // To prevent memory leaks this.reset(); } onMoveIn() { if (this.STATE === TOUCHABLE_STATE.MOVED_OUTSIDE) { // This call is not throttled with delays (like in RN's implementation). this.moveToState(TOUCHABLE_STATE.BEGAN); } } onMoveOut() { // Long press should no longer be detected clearTimeout(this.longPressTimeout!); this.longPressTimeout = null; if (this.STATE === TOUCHABLE_STATE.BEGAN) { this.handleMoveOutside(); } } render() { const hitSlop = (typeof this.props.hitSlop === 'number' ? { top: this.props.hitSlop, left: this.props.hitSlop, bottom: this.props.hitSlop, right: this.props.hitSlop, } : this.props.hitSlop) ?? undefined; const coreProps = { accessible: this.props.accessible !== false, accessibilityLabel: this.props.accessibilityLabel, accessibilityHint: this.props.accessibilityHint, accessibilityRole: this.props.accessibilityRole, // TODO: check if changed to no 's' correctly, also removed 2 props that are no longer available: `accessibilityComponentType` and `accessibilityTraits`, // would be good to check if it is ok for sure, see: path_to_url accessibilityState: this.props.accessibilityState, accessibilityActions: this.props.accessibilityActions, onAccessibilityAction: this.props.onAccessibilityAction, nativeID: this.props.nativeID, onLayout: this.props.onLayout, }; return ( <BaseButton style={this.props.containerStyle} onHandlerStateChange={ // TODO: not sure if it can be undefined instead of null this.props.disabled ? undefined : this.onHandlerStateChange } onGestureEvent={this.onGestureEvent} hitSlop={hitSlop} userSelect={this.props.userSelect} shouldActivateOnStart={this.props.shouldActivateOnStart} disallowInterruption={this.props.disallowInterruption} testID={this.props.testID} touchSoundDisabled={this.props.touchSoundDisabled ?? false} enabled={!this.props.disabled} {...this.props.extraButtonProps}> <Animated.View {...coreProps} style={this.props.style}> {this.props.children} </Animated.View> </BaseButton> ); } } ```
/content/code_sandbox/src/components/touchables/GenericTouchable.tsx
xml
2016-10-27T08:31:38
2024-08-16T12:03:40
react-native-gesture-handler
software-mansion/react-native-gesture-handler
5,989
2,164
```xml import {Store} from "@tsed/core"; import {SocketReturnsTypes} from "../interfaces/SocketReturnsTypes.js"; /** * * @param {string} eventName * @param {SocketReturnsTypes} type * @returns {(target: any, propertyKey: string, descriptor: PropertyDescriptor) => void} * @decorator */ export function SocketReturns(eventName: string, type: SocketReturnsTypes) { return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => { Store.from(target).merge("socketIO", { handlers: { [propertyKey]: { returns: { eventName, type } } } }); }; } ```
/content/code_sandbox/packages/third-parties/socketio/src/decorators/socketReturns.ts
xml
2016-02-21T18:38:47
2024-08-14T21:19:48
tsed
tsedio/tsed
2,817
149
```xml <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\src\App.Metrics.AspNetCore\App.Metrics.AspNetCore.csproj" /> </ItemGroup> </Project> ```
/content/code_sandbox/src/AspNetCore/sandbox/MetricsSandboxCore31/MetricsSandboxCore31.csproj
xml
2016-11-20T04:39:02
2024-08-14T12:43:59
AppMetrics
AppMetrics/AppMetrics
2,215
69
```xml import { Form } from "../../../../src"; const fields = ["username", "email", "country"]; const values = { username: "", email: "", country: "", }; const defaults = { username: "TestUser", email: "s.jobs@apple.com", country: "USA", }; const labels = { username: "User name", email: "Email", country: "Country", }; class NewForm extends Form { } export default new NewForm( { fields, values, defaults, labels, }, { name: "Flat-T" } ); ```
/content/code_sandbox/tests/data/forms/flat/form.t.ts
xml
2016-06-20T22:10:41
2024-08-10T13:14:33
mobx-react-form
foxhound87/mobx-react-form
1,093
129
```xml import { basename, extname } from 'path'; import { oldVisit, Types } from '@graphql-codegen/plugin-helpers'; import { optimizeDocumentNode } from '@graphql-tools/optimize'; import autoBind from 'auto-bind'; import { pascalCase } from 'change-case-all'; import { DepGraph } from 'dependency-graph'; import { DefinitionNode, DirectiveNode, DocumentNode, FragmentDefinitionNode, FragmentSpreadNode, GraphQLSchema, Kind, OperationDefinitionNode, SelectionNode, print, } from 'graphql'; import gqlTag from 'graphql-tag'; import { BaseVisitor, ParsedConfig, RawConfig } from './base-visitor.js'; import { LoadedFragment, ParsedImport } from './types.js'; import { buildScalarsFromConfig, unique, flatten, getConfigValue, groupBy } from './utils.js'; import { FragmentImport, ImportDeclaration, generateFragmentImportStatement } from './imports.js'; gqlTag.enableExperimentalFragmentVariables(); export enum DocumentMode { graphQLTag = 'graphQLTag', documentNode = 'documentNode', documentNodeImportFragments = 'documentNodeImportFragments', external = 'external', string = 'string', } const EXTENSIONS_TO_REMOVE = ['.ts', '.tsx', '.js', '.jsx']; export interface RawClientSideBasePluginConfig extends RawConfig { /** * @description Deprecated. Changes the documentMode to `documentNode`. * @default false */ noGraphQLTag?: boolean; /** * @default graphql-tag#gql * @description Customize from which module will `gql` be imported from. * This is useful if you want to use modules other than `graphql-tag`, e.g. `graphql.macro`. * * @exampleMarkdown * ## graphql.macro * * ```ts filename="codegen.ts" * import type { CodegenConfig } from '@graphql-codegen/cli'; * * const config: CodegenConfig = { * // ... * generates: { * 'path/to/file': { * // plugins... * config: { * gqlImport: 'graphql.macro#gql' * }, * }, * }, * }; * export default config; * ``` * * ## Gatsby * * ```ts filename="codegen.ts" * import type { CodegenConfig } from '@graphql-codegen/cli'; * * const config: CodegenConfig = { * // ... * generates: { * 'path/to/file': { * // plugins... * config: { * gqlImport: 'gatsby#graphql' * }, * }, * }, * }; * export default config; * ``` */ gqlImport?: string; /** * @default graphql#DocumentNode * @description Customize from which module will `DocumentNode` be imported from. * This is useful if you want to use modules other than `graphql`, e.g. `@graphql-typed-document-node`. */ documentNodeImport?: string; /** * @default false * @description Set this configuration to `true` if you wish to tell codegen to generate code with no `export` identifier. */ noExport?: boolean; /** * @default false * @description Set this configuration to `true` if you wish to make sure to remove duplicate operation name suffix. */ dedupeOperationSuffix?: boolean; /** * @default false * @description Set this configuration to `true` if you wish to disable auto add suffix of operation name, like `Query`, `Mutation`, `Subscription`, `Fragment`. */ omitOperationSuffix?: boolean; /** * @default "" * @description Adds a suffix to generated operation result type names */ operationResultSuffix?: string; /** * @default "" * @description Changes the GraphQL operations variables prefix. */ documentVariablePrefix?: string; /** * @default Document * @description Changes the GraphQL operations variables suffix. */ documentVariableSuffix?: string; /** * @default "" * @description Changes the GraphQL fragments variables prefix. */ fragmentVariablePrefix?: string; /** * @default FragmentDoc * @description Changes the GraphQL fragments variables suffix. */ fragmentVariableSuffix?: string; /** * @default graphQLTag * @description Declares how DocumentNode are created: * * - `graphQLTag`: `graphql-tag` or other modules (check `gqlImport`) will be used to generate document nodes. If this is used, document nodes are generated on client side i.e. the module used to generate this will be shipped to the client * - `documentNode`: document nodes will be generated as objects when we generate the templates. * - `documentNodeImportFragments`: Similar to documentNode except it imports external fragments instead of embedding them. * - `external`: document nodes are imported from an external file. To be used with `importDocumentNodeExternallyFrom` * * Note that some plugins (like `typescript-graphql-request`) also supports `string` for this parameter. * */ documentMode?: DocumentMode; /** * @default true * @description If you are using `documentMode: documentNode | documentNodeImportFragments`, you can set this to `true` to apply document optimizations for your GraphQL document. * This will remove all "loc" and "description" fields from the compiled document, and will remove all empty arrays (such as `directives`, `arguments` and `variableDefinitions`). */ optimizeDocumentNode?: boolean; /** * @default "" * @description This config is used internally by presets, but you can use it manually to tell codegen to prefix all base types that it's using. * This is useful if you wish to generate base types from `typescript-operations` plugin into a different file, and import it from there. */ importOperationTypesFrom?: string; /** * @default "" * @description This config should be used if `documentMode` is `external`. This has 2 usage: * * - any string: This would be the path to import document nodes from. This can be used if we want to manually create the document nodes e.g. Use `graphql-tag` in a separate file and export the generated document * - 'near-operation-file': This is a special mode that is intended to be used with `near-operation-file` preset to import document nodes from those files. If these files are `.graphql` files, we make use of webpack loader. * * @exampleMarkdown * ```ts filename="codegen.ts" * import type { CodegenConfig } from '@graphql-codegen/cli'; * * const config: CodegenConfig = { * // ... * generates: { * 'path/to/file': { * // plugins... * config: { * documentMode: 'external', * importDocumentNodeExternallyFrom: 'path/to/document-node-file', * }, * }, * }, * }; * export default config; * ``` * * ```ts filename="codegen.ts" * import type { CodegenConfig } from '@graphql-codegen/cli'; * * const config: CodegenConfig = { * // ... * generates: { * 'path/to/file': { * // plugins... * config: { * documentMode: 'external', * importDocumentNodeExternallyFrom: 'near-operation-file', * }, * }, * }, * }; * export default config; * ``` * */ importDocumentNodeExternallyFrom?: string; /** * @default false * @description This config adds PURE magic comment to the static variables to enforce treeshaking for your bundler. */ pureMagicComment?: boolean; /** * @default false * @description If set to true, it will enable support for parsing variables on fragments. */ experimentalFragmentVariables?: boolean; } export interface ClientSideBasePluginConfig extends ParsedConfig { gqlImport: string; documentNodeImport: string; operationResultSuffix: string; dedupeOperationSuffix: boolean; omitOperationSuffix: boolean; noExport: boolean; documentVariablePrefix: string; documentVariableSuffix: string; fragmentVariablePrefix: string; fragmentVariableSuffix: string; documentMode?: DocumentMode; importDocumentNodeExternallyFrom?: 'near-operation-file' | string; importOperationTypesFrom?: string; globalNamespace?: boolean; pureMagicComment?: boolean; optimizeDocumentNode: boolean; experimentalFragmentVariables?: boolean; unstable_onExecutableDocumentNode?: Unstable_OnExecutableDocumentNode; unstable_omitDefinitions?: boolean; } type ExecutableDocumentNodeMeta = Record<string, unknown>; type Unstable_OnExecutableDocumentNode = (documentNode: DocumentNode) => void | ExecutableDocumentNodeMeta; export class ClientSideBaseVisitor< TRawConfig extends RawClientSideBasePluginConfig = RawClientSideBasePluginConfig, TPluginConfig extends ClientSideBasePluginConfig = ClientSideBasePluginConfig > extends BaseVisitor<TRawConfig, TPluginConfig> { protected _collectedOperations: OperationDefinitionNode[] = []; protected _documents: Types.DocumentFile[] = []; protected _additionalImports: string[] = []; protected _imports = new Set<string>(); private _onExecutableDocumentNode?: Unstable_OnExecutableDocumentNode; private _omitDefinitions?: boolean; private readonly _fragments: ReadonlyMap<string, LoadedFragment>; private readonly fragmentsGraph: DepGraph<LoadedFragment>; constructor( protected _schema: GraphQLSchema, fragments: LoadedFragment[], rawConfig: TRawConfig, additionalConfig: Partial<TPluginConfig>, documents?: Types.DocumentFile[] ) { super(rawConfig, { scalars: buildScalarsFromConfig(_schema, rawConfig), dedupeOperationSuffix: getConfigValue(rawConfig.dedupeOperationSuffix, false), optimizeDocumentNode: getConfigValue(rawConfig.optimizeDocumentNode, true), omitOperationSuffix: getConfigValue(rawConfig.omitOperationSuffix, false), gqlImport: rawConfig.gqlImport || null, documentNodeImport: rawConfig.documentNodeImport || null, noExport: !!rawConfig.noExport, importOperationTypesFrom: getConfigValue(rawConfig.importOperationTypesFrom, null), operationResultSuffix: getConfigValue(rawConfig.operationResultSuffix, ''), documentVariablePrefix: getConfigValue(rawConfig.documentVariablePrefix, ''), documentVariableSuffix: getConfigValue(rawConfig.documentVariableSuffix, 'Document'), fragmentVariablePrefix: getConfigValue(rawConfig.fragmentVariablePrefix, ''), fragmentVariableSuffix: getConfigValue(rawConfig.fragmentVariableSuffix, 'FragmentDoc'), documentMode: ((rawConfig: RawClientSideBasePluginConfig) => { if (typeof rawConfig.noGraphQLTag === 'boolean') { return rawConfig.noGraphQLTag ? DocumentMode.documentNode : DocumentMode.graphQLTag; } return getConfigValue(rawConfig.documentMode, DocumentMode.graphQLTag); })(rawConfig), importDocumentNodeExternallyFrom: getConfigValue(rawConfig.importDocumentNodeExternallyFrom, ''), pureMagicComment: getConfigValue(rawConfig.pureMagicComment, false), experimentalFragmentVariables: getConfigValue(rawConfig.experimentalFragmentVariables, false), ...additionalConfig, } as any); this._documents = documents; this._onExecutableDocumentNode = (rawConfig as any).unstable_onExecutableDocumentNode; this._omitDefinitions = (rawConfig as any).unstable_omitDefinitions; this._fragments = new Map(fragments.map(fragment => [fragment.name, fragment])); this.fragmentsGraph = this._getFragmentsGraph(); autoBind(this); } protected _extractFragments( document: FragmentDefinitionNode | OperationDefinitionNode, withNested = false ): string[] { if (!document) { return []; } const names: Set<string> = new Set(); oldVisit(document, { enter: { FragmentSpread: (node: FragmentSpreadNode) => { names.add(node.name.value); if (withNested) { const foundFragment = this._fragments.get(node.name.value); if (foundFragment) { const childItems = this._extractFragments(foundFragment.node, true); if (childItems && childItems.length > 0) { for (const item of childItems) { names.add(item); } } } } }, }, }); return Array.from(names); } protected _transformFragments(fragmentNames: Array<string>): string[] { return fragmentNames.map(document => this.getFragmentVariableName(document)); } protected _includeFragments(fragments: string[], nodeKind: 'FragmentDefinition' | 'OperationDefinition'): string { if (fragments && fragments.length > 0) { if (this.config.documentMode === DocumentMode.documentNode || this.config.documentMode === DocumentMode.string) { return Array.from(this._fragments.values()) .filter(f => fragments.includes(this.getFragmentVariableName(f.name))) .map(fragment => print(fragment.node)) .join('\n'); } if (this.config.documentMode === DocumentMode.documentNodeImportFragments) { return ''; } if (this.config.dedupeFragments && nodeKind !== 'OperationDefinition') { return ''; } return String(fragments.map(name => '${' + name + '}').join('\n')); } return ''; } protected _prepareDocument(documentStr: string): string { return documentStr; } protected _gql(node: FragmentDefinitionNode | OperationDefinitionNode): string { const includeNestedFragments = this.config.documentMode === DocumentMode.documentNode || this.config.documentMode === DocumentMode.string || (this.config.dedupeFragments && node.kind === 'OperationDefinition'); const fragmentNames = this._extractFragments(node, includeNestedFragments); const fragments = this._transformFragments(fragmentNames); const doc = this._prepareDocument(` ${print(node).split('\\').join('\\\\') /* Re-escape escaped values in GraphQL syntax */} ${this._includeFragments(fragments, node.kind)}`); if (this.config.documentMode === DocumentMode.documentNode) { let gqlObj = gqlTag([doc]); if (this.config.optimizeDocumentNode) { gqlObj = optimizeDocumentNode(gqlObj); } return JSON.stringify(gqlObj); } if (this.config.documentMode === DocumentMode.documentNodeImportFragments) { const gqlObj = gqlTag([doc]); // We need to inline all fragments that are used in this document // Otherwise we might encounter the following issues: // 1. missing fragments // 2. duplicated fragments const fragmentDependencyNames = new Set( fragmentNames.map(name => this.fragmentsGraph.dependenciesOf(name)).flatMap(item => item) ); for (const fragmentName of fragmentNames) { fragmentDependencyNames.add(fragmentName); } const jsonStringify = (json: unknown) => JSON.stringify(json, (key, value) => (key === 'loc' ? undefined : value)); let definitions = [...gqlObj.definitions]; for (const fragmentName of fragmentDependencyNames) { definitions.push(this.fragmentsGraph.getNodeData(fragmentName).node); } if (this.config.optimizeDocumentNode) { definitions = [ ...optimizeDocumentNode({ kind: Kind.DOCUMENT, definitions, }).definitions, ]; } let metaString = ''; if (this._onExecutableDocumentNode && node.kind === Kind.OPERATION_DEFINITION) { const meta = this._getGraphQLCodegenMetadata(node, definitions); if (meta) { if (this._omitDefinitions === true) { return `{${`"__meta__":${JSON.stringify(meta)},`.slice(0, -1)}}`; } metaString = `"__meta__":${JSON.stringify(meta)},`; } } return `{${metaString}"kind":"${Kind.DOCUMENT}","definitions":${jsonStringify(definitions)}}`; } if (this.config.documentMode === DocumentMode.string) { if (node.kind === Kind.FRAGMENT_DEFINITION) { return `new TypedDocumentString(\`${doc}\`, ${JSON.stringify({ fragmentName: node.name.value })})`; } if (this._onExecutableDocumentNode && node.kind === Kind.OPERATION_DEFINITION) { const meta = this._getGraphQLCodegenMetadata(node, gqlTag([doc]).definitions); if (meta) { if (this._omitDefinitions === true) { return `{${`"__meta__":${JSON.stringify(meta)},`.slice(0, -1)}}`; } return `new TypedDocumentString(\`${doc}\`, ${JSON.stringify(meta)})`; } } return `new TypedDocumentString(\`${doc}\`)`; } const gqlImport = this._parseImport(this.config.gqlImport || 'graphql-tag'); return (gqlImport.propName || 'gql') + '`' + doc + '`'; } protected _getGraphQLCodegenMetadata( node: OperationDefinitionNode, definitions?: ReadonlyArray<DefinitionNode> ): Record<string, any> | void | undefined { let meta: Record<string, any> | void | undefined; meta = this._onExecutableDocumentNode({ kind: Kind.DOCUMENT, definitions, }); const deferredFields = this._findDeferredFields(node); if (Object.keys(deferredFields).length) { meta = { ...meta, deferredFields, }; } return meta; } protected _findDeferredFields(node: OperationDefinitionNode): { [fargmentName: string]: string[] } { const deferredFields: { [fargmentName: string]: string[] } = {}; const queue: SelectionNode[] = [...node.selectionSet.selections]; while (queue.length) { const selection = queue.shift(); if ( selection.kind === Kind.FRAGMENT_SPREAD && selection.directives.some((d: DirectiveNode) => d.name.value === 'defer') ) { const fragmentName = selection.name.value; const fragment = this.fragmentsGraph.getNodeData(fragmentName); if (fragment) { const fields = fragment.node.selectionSet.selections.reduce<string[]>((acc, selection) => { if (selection.kind === Kind.FIELD) { acc.push(selection.name.value); } return acc; }, []); deferredFields[fragmentName] = fields; } } else if (selection.kind === Kind.FIELD && selection.selectionSet) { queue.push(...selection.selectionSet.selections); } } return deferredFields; } protected _generateFragment(fragmentDocument: FragmentDefinitionNode): string | void { const name = this.getFragmentVariableName(fragmentDocument); const fragmentTypeSuffix = this.getFragmentSuffix(fragmentDocument); return `export const ${name} =${this.config.pureMagicComment ? ' /*#__PURE__*/' : ''} ${this._gql( fragmentDocument )}${this.getDocumentNodeSignature( this.convertName(fragmentDocument.name.value, { useTypesPrefix: true, suffix: fragmentTypeSuffix, }), this.config.experimentalFragmentVariables ? this.convertName(fragmentDocument.name.value, { suffix: fragmentTypeSuffix + 'Variables', }) : 'unknown', fragmentDocument )};`; } private _getFragmentsGraph(): DepGraph<LoadedFragment> { const graph = new DepGraph<LoadedFragment>({ circular: true }); for (const fragment of this._fragments.values()) { if (graph.hasNode(fragment.name)) { const cachedAsString = print(graph.getNodeData(fragment.name).node); const asString = print(fragment.node); if (cachedAsString !== asString) { throw new Error(`Duplicated fragment called '${fragment.name}'!`); } } graph.addNode(fragment.name, fragment); } for (const fragment of this._fragments.values()) { const depends = this._extractFragments(fragment.node); if (depends && depends.length > 0) { for (const name of depends) { graph.addDependency(fragment.name, name); } } } return graph; } public get fragments(): string { if (this._fragments.size === 0 || this.config.documentMode === DocumentMode.external) { return ''; } const graph = this.fragmentsGraph; const orderedDeps = graph.overallOrder(); const localFragments = orderedDeps .filter(name => !graph.getNodeData(name).isExternal) .map(name => this._generateFragment(graph.getNodeData(name).node)); return localFragments.join('\n'); } protected _parseImport(importStr: string): ParsedImport { // This is a special case when we want to ignore importing, and just use `gql` provided from somewhere else // Plugins that uses that will need to ensure to add import/declaration for the gql identifier if (importStr === 'gql') { return { moduleName: null, propName: 'gql', }; } // This is a special use case, when we don't want this plugin to manage the import statement // of the gql tag. In this case, we provide something like `Namespace.gql` and it will be used instead. if (importStr.includes('.gql')) { return { moduleName: null, propName: importStr, }; } const [moduleName, propName] = importStr.split('#'); return { moduleName, propName, }; } protected _generateImport( { moduleName, propName }: ParsedImport, varName: string, isTypeImport: boolean ): string | null { const typeImport = isTypeImport && this.config.useTypeImports ? 'import type' : 'import'; const propAlias = propName === varName ? '' : ` as ${varName}`; if (moduleName) { return `${typeImport} ${propName ? `{ ${propName}${propAlias} }` : varName} from '${moduleName}';`; } return null; } private clearExtension(path: string): string { const extension = extname(path); if (!this.config.emitLegacyCommonJSImports && extension === '.js') { return path; } if (EXTENSIONS_TO_REMOVE.includes(extension)) { return path.replace(/\.[^/.]+$/, ''); } return path; } public getImports(options: { excludeFragments?: boolean } = {}): string[] { for (const i of this._additionalImports || []) { this._imports.add(i); } switch (this.config.documentMode) { case DocumentMode.documentNode: case DocumentMode.documentNodeImportFragments: { const documentNodeImport = this._parseImport(this.config.documentNodeImport || 'graphql#DocumentNode'); const tagImport = this._generateImport(documentNodeImport, 'DocumentNode', true); if (tagImport) { this._imports.add(tagImport); } break; } case DocumentMode.graphQLTag: { const gqlImport = this._parseImport(this.config.gqlImport || 'graphql-tag'); const tagImport = this._generateImport(gqlImport, 'gql', false); if (tagImport) { this._imports.add(tagImport); } break; } case DocumentMode.external: { if (this._collectedOperations.length > 0) { if (this.config.importDocumentNodeExternallyFrom === 'near-operation-file' && this._documents.length === 1) { let documentPath = `./${this.clearExtension(basename(this._documents[0].location))}`; if (!this.config.emitLegacyCommonJSImports) { documentPath += '.js'; } this._imports.add(`import * as Operations from '${documentPath}';`); } else { if (!this.config.importDocumentNodeExternallyFrom) { // eslint-disable-next-line no-console console.warn('importDocumentNodeExternallyFrom must be provided if documentMode=external'); } this._imports.add( `import * as Operations from '${this.clearExtension(this.config.importDocumentNodeExternallyFrom)}';` ); } } break; } default: break; } const excludeFragments = options.excludeFragments || this.config.globalNamespace || this.config.documentMode !== DocumentMode.graphQLTag; if (!excludeFragments) { const deduplicatedImports = Object.values(groupBy(this.config.fragmentImports, fi => fi.importSource.path)) .map( (fragmentImports): ImportDeclaration<FragmentImport> => ({ ...fragmentImports[0], importSource: { ...fragmentImports[0].importSource, identifiers: unique( flatten(fragmentImports.map(fi => fi.importSource.identifiers)), identifier => identifier.name ), }, emitLegacyCommonJSImports: this.config.emitLegacyCommonJSImports, }) ) .filter(fragmentImport => fragmentImport.outputPath !== fragmentImport.importSource.path); for (const fragmentImport of deduplicatedImports) { this._imports.add(generateFragmentImportStatement(fragmentImport, 'document')); } } return Array.from(this._imports); } protected buildOperation( _node: OperationDefinitionNode, _documentVariableName: string, _operationType: string, _operationResultType: string, _operationVariablesTypes: string, _hasRequiredVariables: boolean ): string { return null; } protected getDocumentNodeSignature( _resultType: string, _variablesTypes: string, _node: FragmentDefinitionNode | OperationDefinitionNode ): string { if ( this.config.documentMode === DocumentMode.documentNode || this.config.documentMode === DocumentMode.documentNodeImportFragments ) { return ` as unknown as DocumentNode`; } return ''; } /** * Checks if the specific operation has variables that are non-null (required), and also doesn't have default. * This is useful for deciding of `variables` should be optional or not. * @param node */ protected checkVariablesRequirements(node: OperationDefinitionNode): boolean { const variables = node.variableDefinitions || []; if (variables.length === 0) { return false; } return variables.some(variableDef => variableDef.type.kind === Kind.NON_NULL_TYPE && !variableDef.defaultValue); } public getOperationVariableName(node: OperationDefinitionNode) { return this.convertName(node, { suffix: this.config.documentVariableSuffix, prefix: this.config.documentVariablePrefix, useTypesPrefix: false, }); } public OperationDefinition(node: OperationDefinitionNode): string { this._collectedOperations.push(node); const documentVariableName = this.getOperationVariableName(node); const operationType: string = pascalCase(node.operation); const operationTypeSuffix: string = this.getOperationSuffix(node, operationType); const operationResultType: string = this.convertName(node, { suffix: operationTypeSuffix + this._parsedConfig.operationResultSuffix, }); const operationVariablesTypes: string = this.convertName(node, { suffix: operationTypeSuffix + 'Variables', }); let documentString = ''; if ( this.config.documentMode !== DocumentMode.external && documentVariableName !== '' // only generate exports for named queries ) { documentString = `${this.config.noExport ? '' : 'export'} const ${documentVariableName} =${ this.config.pureMagicComment ? ' /*#__PURE__*/' : '' } ${this._gql(node)}${this.getDocumentNodeSignature(operationResultType, operationVariablesTypes, node)};`; } const hasRequiredVariables = this.checkVariablesRequirements(node); const additional = this.buildOperation( node, documentVariableName, operationType, operationResultType, operationVariablesTypes, hasRequiredVariables ); return [documentString, additional].filter(a => a).join('\n'); } } ```
/content/code_sandbox/packages/plugins/other/visitor-plugin-common/src/client-side-base-visitor.ts
xml
2016-12-05T19:15:11
2024-08-15T14:56:08
graphql-code-generator
dotansimha/graphql-code-generator
10,759
6,162
```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. --> <com.google.android.flexbox.FlexboxLayout xmlns:android="path_to_url" xmlns:app="path_to_url" android:id="@+id/flexbox_layout" android:layout_width="320dp" android:layout_height="320dp" app:flexDirection="row" app:flexWrap="wrap" app:alignItems="flex_start" app:alignContent="stretch"> <TextView android:id="@+id/text1" android:layout_width="120dp" android:layout_height="120dp" android:text="1" app:layout_alignSelf="stretch" /> <TextView android:id="@+id/text2" android:layout_width="120dp" android:layout_height="120dp" android:text="2" /> <TextView android:id="@+id/text3" android:layout_width="120dp" android:layout_height="120dp" android:text="3" /> </com.google.android.flexbox.FlexboxLayout> ```
/content/code_sandbox/flexbox/src/androidTest/res/layout/activity_align_self_stretch_test.xml
xml
2016-05-04T08:11:22
2024-08-15T12:27:34
flexbox-layout
google/flexbox-layout
18,226
273
```xml import { sortFontsVariantValues } from './sort-fonts-variant-values' /** * Generate the Google Fonts URL given the requested weight(s), style(s) and additional variable axes */ export function getGoogleFontsUrl( fontFamily: string, axes: { wght?: string[] ital?: string[] variableAxes?: [string, string][] }, display: string ) { // Variants are all combinations of weight and style, each variant will result in a separate font file const variants: Array<[string, string][]> = [] if (axes.wght) { for (const wght of axes.wght) { if (!axes.ital) { variants.push([['wght', wght], ...(axes.variableAxes ?? [])]) } else { for (const ital of axes.ital) { variants.push([ ['ital', ital], ['wght', wght], ...(axes.variableAxes ?? []), ]) } } } } else if (axes.variableAxes) { // Variable fonts might not have a range of weights, just add optional variable axes in that case variants.push([...axes.variableAxes]) } // Google api requires the axes to be sorted, starting with lowercase words if (axes.variableAxes) { variants.forEach((variant) => { variant.sort(([a], [b]) => { const aIsLowercase = a.charCodeAt(0) > 96 const bIsLowercase = b.charCodeAt(0) > 96 if (aIsLowercase && !bIsLowercase) return -1 if (bIsLowercase && !aIsLowercase) return 1 return a > b ? 1 : -1 }) }) } let url = `path_to_url{fontFamily.replace( / /g, '+' )}` if (variants.length > 0) { url = `${url}:${variants[0].map(([key]) => key).join(',')}@${variants .map((variant) => variant.map(([, val]) => val).join(',')) .sort(sortFontsVariantValues) .join(';')}` } url = `${url}&display=${display}` return url } ```
/content/code_sandbox/packages/font/src/google/get-google-fonts-url.ts
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
497
```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 {app, Session, webContents} from 'electron'; import * as fs from 'fs-extra'; import {truncate} from 'lodash'; import * as path from 'path'; import {ValidationUtil} from '@wireapp/commons'; import {getLogger} from '../logging/getLogger'; const USER_DATA_DIR = app.getPath('userData'); const LOG_DIR = path.join(USER_DATA_DIR, 'logs'); const logger = getLogger(path.basename(__filename)); const clearStorage = async (session: Session): Promise<void> => { await session.clearStorageData(); await session.clearCache(); session.flushStorageData(); }; export async function deleteAccount(id: number, accountId: string, partitionId?: string): Promise<void> { const truncatedId = truncate(accountId, {length: 5}); // Delete session data try { const webviewWebContent = webContents.fromId(id); if (!webviewWebContent) { throw new Error(`Unable to find webview content id "${id}"`); } if (!webviewWebContent.hostWebContents) { throw new Error('Only a webview can have its storage wiped'); } logger.log(`Deleting session data for account "${truncatedId}"...`); await clearStorage(webviewWebContent.session); logger.log(`Deleted session data for account "${truncatedId}".`); } catch (error: any) { logger.error(`Failed to delete session data for account "${truncatedId}", reason: "${error.message}".`); } // Delete the webview partition // Note: The first account always uses the default session, // therefore partitionId is optional // ToDo: Move the first account to a partition if (partitionId) { try { if (!ValidationUtil.isUUIDv4(partitionId)) { throw new Error('Partition is not an UUID'); } const partitionDir = path.join(USER_DATA_DIR, 'Partitions', partitionId); await fs.remove(partitionDir); logger.log(`Deleted partition "${partitionId}" for account "${truncatedId}".`); } catch (error: any) { logger.log( `Unable to delete partition "${partitionId}" for account "${truncatedId}", reason: "${error.message}".`, ); } } // Delete logs for this account try { if (!ValidationUtil.isUUIDv4(accountId)) { throw new Error('Account is not an UUID'); } const sessionFolder = path.join(LOG_DIR, accountId); await fs.remove(sessionFolder); logger.log(`Deleted logs folder for account "${truncatedId}".`); } catch (error: any) { logger.error(`Failed to delete logs folder for account "${truncatedId}", reason: "${error.message}".`); } } ```
/content/code_sandbox/electron/src/lib/LocalAccountDeletion.ts
xml
2016-07-26T13:55:48
2024-08-16T03:45:51
wire-desktop
wireapp/wire-desktop
1,075
676
```xml import { test } from 'tap'; import { handle } from 'micro/src/lib/handler'; import { stub } from 'sinon'; void test('handle a non-async function', async (t) => { const dir = t.testdir({ 'regular-function-export.js': `module.exports = () => 'Test';`, }); const result = await handle(`${dir}/regular-function-export.js`); t.type(result, 'function'); }); void test('handle async function', async (t) => { const dir = t.testdir({ 'promise-export.js': `module.exports = async () => 'Test';`, }); const result = await handle(`${dir}/promise-export.js`); t.type(result, 'function'); }); void test(`handle ESM's non-async function`, async (t) => { const dir = t.testdir({ 'esm-function-export.mjs': `export default () => 'Hello ESM';`, }); const result = await handle(`${dir}/esm-function-export.mjs`); t.type(result, 'function'); }); void test(`handle ESM's async function`, async (t) => { const dir = t.testdir({ 'esm-async-export.mjs': `export default async () => 'Hello ESM';`, }); const result = await handle(`${dir}/esm-async-export.mjs`); t.type(result, 'function'); }); void test('process.exit when handling an invalid export', async (t) => { const dir = t.testdir({ 'regular-object.js': `module.exports = {};`, }); const processStub = stub(process, 'exit').callsFake(() => { throw new Error('Fake'); }); await t.rejects(handle(`${dir}/regular-object.js`), { message: 'Fake' }); t.equal(processStub.calledOnceWith(1), true); processStub.restore(); }); void test('process.exit when handling and inexisting file', async (t) => { const dir = t.testdir(); const processStub = stub(process, 'exit').callsFake(() => { throw new Error('Fake'); }); await t.rejects(handle(`${dir}/foo/bar`), { message: 'Fake' }); t.equal(processStub.calledOnceWith(1), true); processStub.restore(); }); ```
/content/code_sandbox/test/suite/handler.ts
xml
2016-01-23T05:17:00
2024-08-15T13:02:51
micro
vercel/micro
10,560
499
```xml import 'office-ui-fabric-react/dist/css/fabric.css'; import { PrimaryButton } from 'office-ui-fabric-react'; import { User } from "@microsoft/microsoft-graph-types"; import * as React from 'react'; import { ITeamsMessage } from '../../../model/ITeamsMessage'; import styles from './AllConversations.module.scss'; import { IAllConversationsProps } from './IAllConversationsProps'; import { IAllConversationsState, ViewName } from './IAllConversationsState'; import { ArrowLeftIcon, Button, Provider, teamsTheme } from '@fluentui/react-northstar'; import { Filter } from './filter/Filter'; import { MessageView } from './messageView/MessageView'; import { TableView } from './tableView/TableView'; import { HeaderButton } from './headerButton/HeaderButton'; export default class AllConversations extends React.Component<IAllConversationsProps, IAllConversationsState> { /** * constructor */ public constructor(props: IAllConversationsProps) { super(props); // eslint-disable-next-line no-void void this.getTeamsMessages(); this.state={ allChatMessage:[], filteredMessage:[], nextLink:'', expandedMessageId:'', allRepliedMessage:[], filteredRepliedMessage:[], isFilterOpen: true, viewName: ViewName.Grid, isLoading: true } } /** * function to set the view name * @param viewName name of the view to be set */ public setView = (viewName:ViewName):void =>{ this.setState({viewName:viewName}); } /** * To open close the filter panel */ public flipFilterPanel = (isOpen:boolean):void => { this.setState({isFilterOpen: isOpen}); } /** * Fetch the Messages when clicked on load more */ private getLoadMoreData = async (): Promise<void> => { try { const initialMessage:ITeamsMessage = await this.props.graphService.getNextData(this.state.nextLink); console.log(initialMessage); if(!!initialMessage['@odata.nextLink']){ this.setState({nextLink:initialMessage['@odata.nextLink']}); await this.getLoadMoreData(); }else{ this.setState({nextLink:'', isLoading:false}); } if(initialMessage.value.length > 0){ let tempAllChatMessage = this.state.allChatMessage; tempAllChatMessage = tempAllChatMessage.concat(initialMessage.value); this.setState({allChatMessage:tempAllChatMessage}); } } catch (error) { console.error(error); } } /** * Fetch the initial Message and not on load more */ private getTeamsMessages = async (): Promise<void> => { try { const groupId = this.props.graphService.spcontext.sdks.microsoftTeams.context.groupId; const channelId = this.props.graphService.spcontext.sdks.microsoftTeams.context.channelId; const initialMessage:ITeamsMessage = await this.props.graphService.getMessages(groupId, channelId); console.log(initialMessage); if(!!initialMessage['@odata.nextLink']){ this.setState({nextLink:initialMessage['@odata.nextLink']}); await this.getLoadMoreData(); }else{ this.setState({nextLink:'', isLoading: false}) } if(initialMessage.value.length > 0){ this.setState({allChatMessage:initialMessage.value, filteredMessage: initialMessage.value}); } } catch (error) { console.error(error); } } /** * Fetch the replies for the selected message * @param messageId selected message to get replies */ private getMessageReply = async (messageId:string): Promise<void> => { try { const groupId = this.props.graphService.spcontext.sdks.microsoftTeams.context.groupId; const channelId = this.props.graphService.spcontext.sdks.microsoftTeams.context.channelId; const initialReplies:ITeamsMessage = await this.props.graphService.getMessagesReplies(groupId, channelId, messageId); console.log(initialReplies); this.setState({expandedMessageId:messageId,allRepliedMessage:initialReplies.value, filteredRepliedMessage: initialReplies.value}) } catch (error) { console.error(error); } } /** * For filtering the data based on the selected filters * @param searchText */ private onFilter = (searchText:string,fromDate: Date, toDate: Date, onlyAttachment: boolean, fromUser:Array<User>, mentionedUser:Array<User>):void => { let tempMessages = !!this.state.expandedMessageId ? this.state.allRepliedMessage : this.state.allChatMessage; if(!!searchText){ tempMessages = tempMessages.filter(t=>t.body.content.includes(searchText)); } if(!!fromDate){ tempMessages = tempMessages.filter(t=>new Date(t.createdDateTime) >= fromDate); } if(!!toDate){ tempMessages = tempMessages.filter(t=>new Date(t.createdDateTime) <= toDate); } if(onlyAttachment){ tempMessages = tempMessages.filter(t=>t.attachments.length > 0); } if(fromUser.length > 0){ fromUser.map(u=>{ tempMessages = tempMessages.filter(t=> t.from && t.from.user && t.from.user.id===u.id); }); } if(mentionedUser.length > 0){ mentionedUser.map(u=>{ tempMessages = tempMessages.filter(t=> t.mentions.length > 0 && t.mentions.findIndex(m=> m.mentioned && m.mentioned.user && m.mentioned.user.id===u.id) > -1); }); } if(!!this.state.expandedMessageId){ this.setState({filteredRepliedMessage:tempMessages}); }else{ this.setState({filteredMessage:tempMessages}); } } public render(): React.ReactElement<IAllConversationsProps> { const { hasTeamsContext } = this.props; const dtaaFilteredMessage = !!this.state.expandedMessageId ? this.state.filteredRepliedMessage : this.state.filteredMessage; const dtaaFilteredMessageData = !!this.state.expandedMessageId ? this.state.allChatMessage.filter(t=>t.id===this.state.expandedMessageId) : []; return ( <Provider theme={teamsTheme}> <section className={`${styles.allConversations} ${hasTeamsContext ? styles.teams : ''}`} > <HeaderButton flipFilterPanel={this.flipFilterPanel} setView={this.setView} /> <Filter allChatMessage={dtaaFilteredMessage} onFilter={this.onFilter} isOpen={this.state.isFilterOpen} flipFilterPanel={this.flipFilterPanel} /> {!!this.state.expandedMessageId && <Button icon={<ArrowLeftIcon />} content="Back" onClick={()=>this.setState({expandedMessageId:'',allRepliedMessage:[],filteredRepliedMessage:[]})} text />} {this.state.viewName === ViewName.Grid && <MessageView dtaaFilteredMessage={dtaaFilteredMessage} dtaaFilteredMessageData={dtaaFilteredMessageData} graphService={this.props.graphService} expandedMessageId={this.state.expandedMessageId} getMessageReply={this.getMessageReply} />} {this.state.viewName === ViewName.Table && <TableView dtaaFilteredMessage={dtaaFilteredMessage} dtaaFilteredMessageData={dtaaFilteredMessageData} graphService={this.props.graphService} expandedMessageId={this.state.expandedMessageId} getMessageReply={this.getMessageReply}/>} {!!this.state.nextLink && !this.state.expandedMessageId && !this.state.isLoading && <div className={styles.loadMoreWrapper}> <PrimaryButton text="Load More" onClick={() => this.getLoadMoreData()} className={styles.PrimaryButtonNext} /> </div> } </section> </Provider> ); } } ```
/content/code_sandbox/samples/react-teams-conversationview/src/webparts/allConversations/components/AllConversations.tsx
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
1,715
```xml /** @since 3.9.0 */ export function toArray<T> (value: T | T[]): T[] { return Array.isArray(value) ? value : [value] } ```
/content/code_sandbox/packages/webpack/src/utils/index.ts
xml
2016-10-26T11:18:47
2024-08-16T19:32:46
nuxt
nuxt/nuxt
53,705
39
```xml <?xml version="1.0" encoding="utf-8"?> <schema targetNamespace="path_to_url" xmlns:doc="path_to_url" xmlns:maml="path_to_url" xmlns:dev="path_to_url" xmlns:managed="path_to_url" xmlns="path_to_url" elementFormDefault="qualified" attributeFormDefault="unqualified" blockDefault="#all" xml:lang="en"> <!-- Schema documentation --> <annotation> <documentation>This schema describes MAML (Microsoft Assistance Markup Language). MAML is intended for software documentation. In particular, MAML is intended to accommodate the needs of Microsoft documentation.</documentation> <documentation>The schema is broken into three main areas: end user, developer and IT Pro. These areas represent the main categories of Microsoft documentation.</documentation> <documentation>The namespace uri for this version of MAML is: path_to_url <documentation>Each backwards-incompatible revision to MAML will require that the date fields be appropriately incremented in uri of the updated version of the MAML schema.</documentation> </annotation> <annotation> <documentation>This portion of the schema was created by chains in Dec 2004.</documentation> </annotation> <import schemaLocation="maml.xsd" namespace="path_to_url"/> <import schemaLocation="developer.xsd" namespace="path_to_url"/> <!-- Managed Developer Page Types --> <!-- Managed Overload --> <element name="overload" type="managed:overloadType"> <annotation> <documentation>Root element of managedOverload page type.</documentation> </annotation> </element> <complexType name="overloadType"> <sequence> <element ref="maml:title"/> <element ref="maml:introduction"/> <element ref="managed:overloads"/> <element ref="dev:remarks" minOccurs="0"/> <element ref="dev:examples" minOccurs="0"/> <element ref="maml:relatedLinks" minOccurs="0"/> </sequence> </complexType> <element name="overloads" type="managed:overloadsType"/> <complexType name="overloadsType"> <sequence> <element name="overload" type="managed:memberType" maxOccurs="unbounded"/> </sequence> <attributeGroup ref="maml:contentIdentificationSharingAndConditionGroup"/> </complexType> </schema> ```
/content/code_sandbox/src/Schemas/PSMaml/developerManagedOverload.xsd
xml
2016-01-13T23:41:35
2024-08-16T19:59:07
PowerShell
PowerShell/PowerShell
44,388
508
```xml /* * IOSDebug.mm * */ #include "../Debug.h" #include <stdio.h> #import <Foundation/Foundation.h> namespace LLGL { LLGL_EXPORT void DebugPuts(const char* text) { #ifdef LLGL_DEBUG /* Print to Xcode debug console */ NSLog(@"%@\n", @(text)); #else /* Print to standard error stream */ ::fprintf(stderr, "%s\n", text); #endif } } // /namespace LLGL // ================================================================================ ```
/content/code_sandbox/sources/Platform/IOS/IOSDebug.mm
xml
2016-07-09T19:10:46
2024-08-16T15:42:24
LLGL
LukasBanana/LLGL
2,007
107
```xml import type { CompatibleString, StorybookConfig as StorybookConfigBase, } from 'storybook/internal/types'; import type { BuilderOptions, StorybookConfigVite } from '@storybook/builder-vite'; import type { ComponentMeta } from 'vue-component-meta'; import type { ComponentDoc } from 'vue-docgen-api'; type FrameworkName = CompatibleString<'@storybook/vue3-vite'>; type BuilderName = CompatibleString<'@storybook/builder-vite'>; /** Available docgen plugins for vue. */ export type VueDocgenPlugin = 'vue-docgen-api' | 'vue-component-meta'; export type FrameworkOptions = { builder?: BuilderOptions; /** * Plugin to use for generation docs for component props, events, slots and exposes. Since * Storybook 8, the official vue plugin "vue-component-meta" (Volar) can be used which supports * more complex types, better type docs, support for js(x)/ts(x) components and more. * * "vue-component-meta" will become the new default in the future and "vue-docgen-api" will be * removed. * * @default 'vue-docgen-api' */ docgen?: | VueDocgenPlugin | { plugin: 'vue-component-meta'; /** * Tsconfig filename to use. Should be set if your main `tsconfig.json` includes references * to other tsconfig files like `tsconfig.app.json`. Otherwise docgen might not be generated * correctly (e.g. import aliases are not resolved). * * For further information, see our * [docs](path_to_url#override-the-default-configuration). * * @default 'tsconfig.json' */ tsconfig: `tsconfig${string}.json`; }; }; type StorybookConfigFramework = { framework: | FrameworkName | { name: FrameworkName; options: FrameworkOptions; }; core?: StorybookConfigBase['core'] & { builder?: | BuilderName | { name: BuilderName; options: BuilderOptions; }; }; }; /** The interface for Storybook configuration in `main.ts` files. */ export type StorybookConfig = Omit< StorybookConfigBase, keyof StorybookConfigVite | keyof StorybookConfigFramework > & StorybookConfigVite & StorybookConfigFramework; /** Gets the type of a single array element. */ type ArrayElement<T> = T extends readonly (infer A)[] ? A : never; /** Type of "__docgenInfo" depending on the used docgenPlugin. */ export type VueDocgenInfo<T extends VueDocgenPlugin> = T extends 'vue-component-meta' ? ComponentMeta : ComponentDoc; /** * Single prop/event/slot/exposed entry of "__docgenInfo" depending on the used docgenPlugin. * * @example * * ```ts * type PropInfo = VueDocgenInfoEntry<'vue-component-meta', 'props'>; * ``` */ export type VueDocgenInfoEntry< T extends VueDocgenPlugin, TKey extends 'props' | 'events' | 'slots' | 'exposed' | 'expose' = | 'props' | 'events' | 'slots' | 'exposed' | 'expose', > = ArrayElement< T extends 'vue-component-meta' ? VueDocgenInfo<'vue-component-meta'>[Exclude<TKey, 'expose'>] : VueDocgenInfo<'vue-docgen-api'>[Exclude<TKey, 'exposed'>] >; ```
/content/code_sandbox/code/frameworks/vue3-vite/src/types.ts
xml
2016-03-18T04:23:44
2024-08-16T19:22:08
storybook
storybookjs/storybook
83,755
780
```xml import { isDeinitable } from './isDeinitable' function isNotUndefined<T>(val: T | undefined | null): val is T { return val != undefined } export class DependencyContainer { private factory = new Map<symbol, () => unknown>() private dependencies = new Map<symbol, unknown>() public deinit() { this.factory.clear() const deps = this.getAll() for (const dep of deps) { if (isDeinitable(dep)) { dep.deinit() } } this.dependencies.clear() } public getAll(): unknown[] { return Array.from(this.dependencies.values()).filter(isNotUndefined) } public bind<T>(sym: symbol, maker: () => T) { this.factory.set(sym, maker) } public get<T>(sym: symbol): T { const dep = this.dependencies.get(sym) if (dep) { return dep as T } const maker = this.factory.get(sym) if (!maker) { throw new Error(`No dependency maker found for ${sym.toString()}`) } const instance = maker() if (!instance) { /** Could be optional */ return undefined as T } this.dependencies.set(sym, instance) return instance as T } } ```
/content/code_sandbox/packages/docs-shared/lib/Dependency/DependencyContainer.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
279
```xml import PATHS from "config/constants/sub/paths"; import { DraftSessionScreen } from "features/sessionBook"; import { SessionsListScreenContainer } from "features/sessionBook/screens/SessionsListScreen/SessionsListScreenContainer"; import { Navigate, RouteObject } from "react-router-dom"; import { DesktopSessionsContainer } from "views/containers/DesktopSessionsContainer"; import { SavedSessionViewer } from "views/features/sessions/SessionViewer"; import NetworkSessionsIndexPage from "views/features/sessions/SessionsIndexPageContainer/NetworkSessions"; import NetworkSessionViewer from "views/features/sessions/SessionsIndexPageContainer/NetworkSessions/NetworkSessionViewer"; export const desktopSessionsRoutes: RouteObject[] = [ { path: PATHS.SESSIONS.DESKTOP.INDEX, element: <DesktopSessionsContainer />, children: [ { path: "", element: <Navigate to={PATHS.SESSIONS.DESKTOP.SAVED_LOGS.RELATIVE} />, }, { index: true, path: PATHS.SESSIONS.DESKTOP.SAVED_LOGS.RELATIVE, element: <NetworkSessionsIndexPage />, }, { path: PATHS.SESSIONS.DESKTOP.WEB_SESSIONS.ABSOLUTE + "/imported", element: <DraftSessionScreen desktopMode={true} />, }, { path: PATHS.SESSIONS.DESKTOP.WEB_SESSIONS_WRAPPER.RELATIVE, element: <SessionsListScreenContainer />, }, { path: PATHS.SESSIONS.DESKTOP.SAVED_WEB_SESSION_VIEWER.ABSOLUTE + "/:id", element: <SavedSessionViewer />, }, { path: PATHS.SESSIONS.DESKTOP.NETWORK.ABSOLUTE + "/:id", element: <NetworkSessionViewer />, }, { path: PATHS.SESSIONS.DESKTOP.NETWORK.ABSOLUTE, element: <NetworkSessionViewer />, }, ], }, ]; ```
/content/code_sandbox/app/src/routes/desktopSessionRoutes.tsx
xml
2016-12-01T04:36:06
2024-08-16T19:12:19
requestly
requestly/requestly
2,121
427
```xml import { Operator } from '../Operator'; import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { OuterSubscriber } from '../OuterSubscriber'; import { InnerSubscriber } from '../InnerSubscriber'; import { subscribeToResult } from '../util/subscribeToResult'; import { MonoTypeOperatorFunction, TeardownLogic } from '../types'; /** * Emits the values emitted by the source Observable until a `notifier` * Observable emits a value. * * <span class="informal">Lets values pass until a second Observable, * `notifier`, emits a value. Then, it completes.</span> * * ![](takeUntil.png) * * `takeUntil` subscribes and begins mirroring the source Observable. It also * monitors a second Observable, `notifier` that you provide. If the `notifier` * emits a value, the output Observable stops mirroring the source Observable * and completes. If the `notifier` doesn't emit any value and completes * then `takeUntil` will pass all values. * * ## Example * Tick every second until the first click happens * ```javascript * const interval = interval(1000); * const clicks = fromEvent(document, 'click'); * const result = interval.pipe(takeUntil(clicks)); * result.subscribe(x => console.log(x)); * ``` * * @see {@link take} * @see {@link takeLast} * @see {@link takeWhile} * @see {@link skip} * * @param {Observable} notifier The Observable whose first emitted value will * cause the output Observable of `takeUntil` to stop emitting values from the * source Observable. * @return {Observable<T>} An Observable that emits the values from the source * Observable until such time as `notifier` emits its first value. * @method takeUntil * @owner Observable */ export function takeUntil<T>(notifier: Observable<any>): MonoTypeOperatorFunction<T> { return (source: Observable<T>) => source.lift(new TakeUntilOperator(notifier)); } class TakeUntilOperator<T> implements Operator<T, T> { constructor(private notifier: Observable<any>) { } call(subscriber: Subscriber<T>, source: any): TeardownLogic { const takeUntilSubscriber = new TakeUntilSubscriber(subscriber); const notifierSubscription = subscribeToResult(takeUntilSubscriber, this.notifier); if (notifierSubscription && !takeUntilSubscriber.seenValue) { takeUntilSubscriber.add(notifierSubscription); return source.subscribe(takeUntilSubscriber); } return takeUntilSubscriber; } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ class TakeUntilSubscriber<T, R> extends OuterSubscriber<T, R> { seenValue = false; constructor(destination: Subscriber<any>, ) { super(destination); } notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number, innerSub: InnerSubscriber<T, R>): void { this.seenValue = true; this.complete(); } notifyComplete(): void { // noop } } ```
/content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/src/internal/operators/takeUntil.ts
xml
2016-09-05T10:18:44
2024-08-11T13:21:40
LiquidCore
LiquidPlayer/LiquidCore
1,010
676
```xml <?xml version="1.0" encoding="UTF-8"?> <phpunit backupGlobals="false" backupStaticAttributes="false" bootstrap="bootstrap/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false"> <testsuites> <testsuite name="Application Test Suite"> <directory>./tests/</directory> </testsuite> </testsuites> <filter> <whitelist> <directory suffix=".php">app/</directory> </whitelist> </filter> <php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="file"/> <env name="DB_CONNECTION" value="sqlite" /> <env name="DB_DATABASE" value=":memory:"/> <env name="SESSION_DRIVER" value="file"/> <env name="QUEUE_DRIVER" value="sync"/> </php> </phpunit> ```
/content/code_sandbox/phpunit.xml
xml
2016-02-08T02:14:29
2024-08-12T19:21:18
laravel-hackathon-starter
unicodeveloper/laravel-hackathon-starter
1,630
235
```xml import { Observable } from '../Observable'; import { ConnectableObservable } from '../observable/ConnectableObservable'; import { UnaryFunction } from '../types'; /** * Returns a connectable observable sequence that shares a single subscription to the * underlying sequence containing only the last notification. * * ![](publishLast.png) * * Similar to {@link publish}, but it waits until the source observable completes and stores * the last emitted value. * Similarly to {@link publishReplay} and {@link publishBehavior}, this keeps storing the last * value even if it has no more subscribers. If subsequent subscriptions happen, they will * immediately get that last stored value and complete. * * ## Example * * ```js * const connectable = * interval(1000) * .pipe( * tap(x => console.log("side effect", x)), * take(3), * publishLast()); * * connectable.subscribe( * x => console.log( "Sub. A", x), * err => console.log("Sub. A Error", err), * () => console.log( "Sub. A Complete")); * * connectable.subscribe( * x => console.log( "Sub. B", x), * err => console.log("Sub. B Error", err), * () => console.log( "Sub. B Complete")); * * connectable.connect(); * * // Results: * // "side effect 0" * // "side effect 1" * // "side effect 2" * // "Sub. A 2" * // "Sub. B 2" * // "Sub. A Complete" * // "Sub. B Complete" * ``` * * @see {@link ConnectableObservable} * @see {@link publish} * @see {@link publishReplay} * @see {@link publishBehavior} * * @return {ConnectableObservable} An observable sequence that contains the elements of a * sequence produced by multicasting the source sequence. * @method publishLast * @owner Observable */ export declare function publishLast<T>(): UnaryFunction<Observable<T>, ConnectableObservable<T>>; ```
/content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/internal/operators/publishLast.d.ts
xml
2016-09-05T10:18:44
2024-08-11T13:21:40
LiquidCore
LiquidPlayer/LiquidCore
1,010
458
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> <key>CFBundleIdentifier</key> <string>${PRODUCT_BUNDLE_IDENTIFIER}</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>1.8.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>${CURRENT_PROJECT_VERSION}</string> <key>NSPrincipalClass</key> <string></string> </dict> </plist> ```
/content/code_sandbox/Example/Pods/Target Support Files/EasyPeasy-iOS/Info.plist
xml
2016-03-25T17:51:31
2024-07-22T09:31:52
EasyPeasy
nakiostudio/EasyPeasy
1,939
244
```xml import {NOTIFICATION_MESSAGE, NOTIFICATION_DISMISS} from '../../typings/constants/notifications'; import type {HyperActions} from '../../typings/hyper'; export function dismissNotification(id: string): HyperActions { return { type: NOTIFICATION_DISMISS, id }; } export function addNotificationMessage(text: string, url: string | null = null, dismissable = true): HyperActions { return { type: NOTIFICATION_MESSAGE, text, url, dismissable }; } ```
/content/code_sandbox/lib/actions/notifications.ts
xml
2016-07-01T06:01:21
2024-08-16T16:05:22
hyper
vercel/hyper
43,095
107
```xml /** * A time interface just for documentation purpose */ export interface TimeInterface { /** * @example * interface property */ zone: string; /** * @example * interface method */ foo?(): string; } ```
/content/code_sandbox/test/fixtures/todomvc-ng2/src/app/shared/interfaces/time.interface.ts
xml
2016-10-17T07:09:28
2024-08-14T16:30:10
compodoc
compodoc/compodoc
3,980
57
```xml // See LICENSE.txt for license information. // ******************************************************************* // - [#] indicates a test step (e.g. # Go to a screen) // - [*] indicates an assertion (e.g. * Check the title) // - Use element testID when selecting an element. Create one if none. // ******************************************************************* import {Setup} from '@support/server_api'; import { serverOneUrl, siteOneUrl, } from '@support/test_config'; import { AboutScreen, AccountScreen, AdvancedSettingsScreen, DisplaySettingsScreen, HomeScreen, NotificationSettingsScreen, LoginScreen, ServerScreen, SettingsScreen, } from '@support/ui/screen'; import {expect} from 'detox'; describe('Account - Settings', () => { const serverOneDisplayName = 'Server 1'; let testUser: any; beforeAll(async () => { const {user} = await Setup.apiInit(siteOneUrl); testUser = user; // # Log in to server, open account screen, and go to settings screen await ServerScreen.connectToServer(serverOneUrl, serverOneDisplayName); await LoginScreen.login(testUser); await AccountScreen.open(); await SettingsScreen.open(); }); beforeEach(async () => { // * Verify on settings screen await SettingsScreen.toBeVisible(); }); afterAll(async () => { // # Log out await SettingsScreen.close(); await HomeScreen.logout(); }); it('MM-T4991_1 - should match elements on settings screen', async () => { // * Verify basic elements on settings screen await expect(SettingsScreen.notificationsOption).toBeVisible(); await expect(SettingsScreen.displayOption).toBeVisible(); await expect(SettingsScreen.advancedSettingsOption).toBeVisible(); await expect(SettingsScreen.aboutOption).toBeVisible(); await expect(SettingsScreen.helpOption).toBeVisible(); await expect(SettingsScreen.reportProblemOption).toBeVisible(); }); it('MM-T4991_2 - should be able to go to notification settings screen', async () => { // # Tap on notifications option await SettingsScreen.notificationsOption.tap(); // * Verify on notification settings screen await NotificationSettingsScreen.toBeVisible(); // # Go back to settings screen await NotificationSettingsScreen.back(); }); it('MM-T4991_3 - should be able to go to display settings screen', async () => { // # Tap on display option await SettingsScreen.displayOption.tap(); // * Verify on display settings screen await DisplaySettingsScreen.toBeVisible(); // # Go back to settings screen await DisplaySettingsScreen.back(); }); it('MM-T4991_4 - should be able to go to advanced settings screen', async () => { // # Tap on advanced settings option await SettingsScreen.advancedSettingsOption.tap(); // * Verify on advanced settings screen await AdvancedSettingsScreen.toBeVisible(); // # Go back to settings screen await AdvancedSettingsScreen.back(); }); it('MM-T4991_5 - should be able to go to about screen', async () => { // # Tap on about option await SettingsScreen.aboutOption.tap(); // * Verify on about screen await AboutScreen.toBeVisible(); // # Go back to settings screen await AboutScreen.back(); }); }); ```
/content/code_sandbox/detox/e2e/test/account/settings.e2e.ts
xml
2016-10-07T16:52:32
2024-08-16T12:08:38
mattermost-mobile
mattermost/mattermost-mobile
2,155
712
```xml /*your_sha256_hash----------------------------- *your_sha256_hash----------------------------*/ 'use strict'; import assert, { doesNotReject } from 'assert'; import path from 'path'; import { DebugProtocol } from 'vscode-debugprotocol'; import { DebugClient } from 'vscode-debugadapter-testsupport'; const DATA_ROOT = path.join(__dirname, 'data'); const DEBUG_ADAPTER = path.join(__dirname, '..', 'dist', 'main.js'); const PROGRAM = path.join(DATA_ROOT, 'basic.rb'); describe('vscode-ruby-debugger', () => { let dc: DebugClient; before(() => { dc = new DebugClient('node', DEBUG_ADAPTER, 'node'); dc.start(); }); after(() => { dc.stop(); }); describe('basic', () => { it('unknown request should produce error', done => { dc.send('illegal_request') .then(() => { done(new Error('does not report error on unknown request')); }) .catch(() => { done(); }); }); }); describe('initialize', () => { it('should return supported features', () => { return dc.initializeRequest().then(response => { assert.equal(response.body.supportsConfigurationDoneRequest, true); }); }); it("should produce error for invalid 'pathFormat'", done => { dc.initializeRequest({ adapterID: 'mock', linesStartAt1: true, columnsStartAt1: true, pathFormat: 'url', }) .then(response => { done(new Error("does not report error on invalid 'pathFormat' attribute")); }) .catch(err => { // error expected done(); }); }); }); describe('launch', () => { it('should run program to the end', () => { return Promise.all([ dc.configurationSequence(), dc.launch({ program: PROGRAM }), dc.waitForEvent('terminated'), ]); }); /* test('should stop on entry', () => { const PROGRAM = Path.join(DATA_ROOT, 'basic.rb'); const ENTRY_LINE = 1; return Promise.all([ dc.configurationSequence(), dc.launch({ program: PROGRAM, stopOnEntry: true }), dc.assertStoppedLocation('entry', { line: ENTRY_LINE } ) ]); }); */ }); describe('setBreakpoints', () => { // test('should stop on a breakpoint', () => { // const PROGRAM = Path.join(DATA_ROOT, 'basic.rb'); // const BREAKPOINT_LINE = 2; // return Promise.all<Promise<any>>([ // dc.hitBreakpoint( // { program: PROGRAM }, // { path: PROGRAM, line: BREAKPOINT_LINE } ), // dc.assertStoppedLocation('breakpoint', { line: BREAKPOINT_LINE }), // dc.waitForEvent('stopped').then(event => { // return dc.continueRequest({ // threadId: event.body.threadId // }); // }), // dc.waitForEvent('terminated')]); // }); it('should get correct variables on a breakpoint', async () => { const BREAKPOINT_LINE = 3; let response; dc.hitBreakpoint({ program: PROGRAM }, { path: PROGRAM, line: BREAKPOINT_LINE }); response = await dc.assertStoppedLocation('breakpoint', { line: BREAKPOINT_LINE }); response = await dc.scopesRequest({ frameId: response.body.stackFrames[0].id, }); response = await dc.variablesRequest({ variablesReference: response.body.scopes[0].variablesReference, }); assert.strictEqual(response.body.variables.length, 3); assert.strictEqual(response.body.variables[0].name, 'a'); assert.strictEqual(response.body.variables[0].value, '10'); assert.strictEqual(response.body.variables[1].name, 'b'); assert.strictEqual(response.body.variables[1].value, 'undefined'); assert.strictEqual(response.body.variables[2].name, 'c'); assert.strictEqual(response.body.variables[2].value, 'undefined'); dc.disconnectRequest({}); }); }); }); ```
/content/code_sandbox/packages/vscode-ruby-debugger/spec/adapter.test.ts
xml
2016-02-24T04:14:24
2024-08-12T08:08:29
vscode-ruby
rubyide/vscode-ruby
1,260
916
```xml import PageToolbar from './PageToolbar'; export default PageToolbar; ```
/content/code_sandbox/docs/components/PageToolbar/index.tsx
xml
2016-06-06T02:27:46
2024-08-16T16:41:54
rsuite
rsuite/rsuite
8,263
14
```xml export { Button } from './Button'; export { AddButton } from './AddButton'; export { ButtonGroup } from './ButtonGroup'; export { LoadingButton } from './LoadingButton'; export { CopyButton } from './CopyButton'; ```
/content/code_sandbox/app/react/components/buttons/index.ts
xml
2016-05-19T20:15:28
2024-08-16T19:15:14
portainer
portainer/portainer
30,083
49
```xml import "jsdom-global/register"; import React from "react"; // eslint-disable-line import { describe, it } from "mocha"; import { expect } from "chai"; import { SubAppDef, SubAppContainer, envHooks, SubAppFeatureResult } from "@xarc/subapp"; import { reactRouterFeature } from "../../src/node/index"; import { render, waitFor, screen } from "@testing-library/react"; import { _id, _subId } from "../../src/common"; const { createElement } = React; // eslint-disable-line describe("reactRouterFeature browser", () => { it("should return a feature factory", async () => { const factory = reactRouterFeature({ React }); expect(factory.id).equal(_id); expect(factory.subId).equal(_subId); expect(factory.add).to.be.a("function"); }); it("should add react-router feature to a subapp", async () => { const container = new SubAppContainer({}); envHooks.getContainer = () => container; const factory = reactRouterFeature({ React }); const def = { name: "test", getModule() { return Promise.resolve({}); }, _features: {} } as SubAppDef; container.declare("test", def); factory.add(def); expect(def._features.reactRouter).to.be.an("object"); expect(def._features.reactRouter.id).equal(_id); expect(def._features.reactRouter.subId).equal(_subId); expect(def._features.reactRouter.execute).to.be.a("function"); }); it("should render subapp with input component", async () => { const container = new SubAppContainer({}); envHooks.getContainer = () => container; const factory = reactRouterFeature({ React }); const def = { name: "test", getModule() { return Promise.resolve({}); }, _features: {} } as SubAppDef; container.declare("test", def); factory.add(def); const Component = (def._features.reactRouter.execute({ input: { Component: props => ( <div> test <p>{JSON.stringify(props)}</p> </div> ) }, ssrData: { context: { user: { routerContext: "test-context" } }, subapp: def, options: { name: "test-subapp-def-option" }, path: "test-path-1" } }) as SubAppFeatureResult).Component; render(<Component data="don't expect it be rendered" />); const element = await waitFor(() => screen.getByText("test"), { timeout: 500 }); expect(element.innerHTML).contains(`test <p>{}</p>`); }); it("should render subapp without input component", async () => { const container = new SubAppContainer({}); envHooks.getContainer = () => container; const factory = reactRouterFeature({ React }); const def = { name: "test", getModule() { return Promise.resolve({}); }, _features: {}, _getExport: () => { return { Component: props => ( <div> test <p>{JSON.stringify(props)}</p> </div> ) }; } } as SubAppDef; container.declare("test", def); factory.add(def); const Component = (def._features.reactRouter.execute({ input: { Component: undefined }, ssrData: { context: { user: { routerContext: "test-context" } }, subapp: def, options: { name: "test-subapp-def-option" }, path: "test-path-2" } }) as SubAppFeatureResult).Component; render(<Component data="don't expect it be rendered" />); const element = await waitFor(() => screen.getByText("test"), { timeout: 500 }); expect(element.innerHTML).contains(`test <p>{}</p>`); }); }); ```
/content/code_sandbox/packages/xarc-react-router/test/spec/node-index.spec.tsx
xml
2016-09-06T19:02:39
2024-08-11T11:43:11
electrode
electrode-io/electrode
2,103
871
```xml import * as React from 'react'; import { ItemLayout } from '@fluentui/react-northstar'; const ItemLayoutExampleContentMediaShorthand = () => ( <ItemLayout content="Program the sensor to the SAS alarm through the haptic SQL card!" contentMedia="7:26:56 AM" /> ); export default ItemLayoutExampleContentMediaShorthand; ```
/content/code_sandbox/packages/fluentui/docs/src/examples/components/ItemLayout/Content/ItemLayoutExampleContentMedia.shorthand.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
78
```xml import { joinURL } from 'ufo' import type { Plugin } from 'vite' import { isCSS } from '../utils' interface DevStyleSSRPluginOptions { srcDir: string buildAssetsURL: string } export function devStyleSSRPlugin (options: DevStyleSSRPluginOptions): Plugin { return { name: 'nuxt:dev-style-ssr', apply: 'serve', enforce: 'post', transform (code, id) { if (!isCSS(id) || !code.includes('import.meta.hot')) { return } let moduleId = id if (moduleId.startsWith(options.srcDir)) { moduleId = moduleId.slice(options.srcDir.length) } // When dev `<style>` is injected, remove the `<link>` styles from manifest const selectors = [joinURL(options.buildAssetsURL, moduleId), joinURL(options.buildAssetsURL, '@fs', moduleId)] return code + selectors.map(selector => `\ndocument.querySelectorAll(\`link[href="${selector}"]\`).forEach(i=>i.remove())`).join('') }, } } ```
/content/code_sandbox/packages/vite/src/plugins/dev-ssr-css.ts
xml
2016-10-26T11:18:47
2024-08-16T19:32:46
nuxt
nuxt/nuxt
53,705
238
```xml export interface Colors { chalky: string coral: string dark: string error: string fountainBlue: string green: string invalid: string lightDark: string lightWhite: string malibu: string purple: string whiskey: string } ```
/content/code_sandbox/src/interface/colors.ts
xml
2016-09-04T13:32:33
2024-08-14T22:14:04
OneDark-Pro
Binaryify/OneDark-Pro
1,485
71
```xml <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="media_bubble_max_width">350dp</dimen> <dimen name="media_bubble_max_height">300dp</dimen> </resources> ```
/content/code_sandbox/src/main/res/values-sw480dp/dimens.xml
xml
2016-07-03T07:32:36
2024-08-16T16:51:15
deltachat-android
deltachat/deltachat-android
1,082
57
```xml import { IUser } from '@erxes/ui/src/auth/types'; import EmptyState from '@erxes/ui/src/components/EmptyState'; import Spinner from '@erxes/ui/src/components/Spinner'; import { gql } from '@apollo/client'; import React from 'react'; import ClientPortalCompanyDetails from '../../components/detail/ClientPortalCompanyDetails'; import { queries } from '../../graphql'; import { ClientPoratlUserDetailQueryResponse } from '../../types'; import { useQuery } from '@apollo/client'; type Props = { id: string; }; type FinalProps = { currentUser: IUser; } & Props; function CompanyDetailsContainer(props: FinalProps) { const { id, currentUser } = props; const clientPortalUserDetailQuery = useQuery<ClientPoratlUserDetailQueryResponse>( gql(queries.clientPortalUserDetail), { variables: { _id: id, }, }, ); if (clientPortalUserDetailQuery.loading) { return <Spinner objective={true} />; } if ( clientPortalUserDetailQuery.data === undefined || !clientPortalUserDetailQuery.data.clientPortalUserDetail ) { return ( <EmptyState text="ClientPortal User not found" image="/images/actions/17.svg" /> ); } const updatedProps = { ...props, clientPortalUser: (clientPortalUserDetailQuery.data && clientPortalUserDetailQuery.data.clientPortalUserDetail) || ({} as any), currentUser, }; return <ClientPortalCompanyDetails {...updatedProps} />; } export default CompanyDetailsContainer; ```
/content/code_sandbox/packages/plugin-clientportal-ui/src/containers/details/ClientPortalCompanyDetails.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
342
```xml <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="path_to_url"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{4AA7C415-B0C8-4029-88FF-DB91D260AC3C}</ProjectGuid> <ProjectTypeGuids>{A3F8F2AB-B479-4A4A-A458-A89E7DC349F1};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <OutputType>Library</OutputType> <RootNamespace>macOSIntegration</RootNamespace> <AssemblyName>macOSIntegration</AssemblyName> <TargetFrameworkVersion>v2.0</TargetFrameworkVersion> <TargetFrameworkIdentifier>Xamarin.Mac</TargetFrameworkIdentifier> <MonoMacResourcePrefix>Resources</MonoMacResourcePrefix> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug</OutputPath> <DefineConstants>DEBUG;</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <EnableCodeSigning>false</EnableCodeSigning> <CreatePackage>false</CreatePackage> <EnablePackageSigning>false</EnablePackageSigning> <IncludeMonoRuntime>false</IncludeMonoRuntime> <UseSGen>false</UseSGen> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <Optimize>true</Optimize> <OutputPath>bin\Release</OutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <EnableCodeSigning>false</EnableCodeSigning> <CreatePackage>false</CreatePackage> <EnablePackageSigning>false</EnablePackageSigning> <IncludeMonoRuntime>false</IncludeMonoRuntime> <UseSGen>false</UseSGen> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="Xamarin.Mac" /> </ItemGroup> <ItemGroup> <Compile Include="IntegrationAPI.cs" /> </ItemGroup> <Import Project="$(MSBuildExtensionsPath)\Xamarin\Mac\Xamarin.Mac.CSharp.targets" /> </Project> ```
/content/code_sandbox/tools/nnyeah/integration/API/macOSIntegration.csproj
xml
2016-04-20T18:24:26
2024-08-16T13:29:19
xamarin-macios
xamarin/xamarin-macios
2,436
602
```xml import { ComponentFixture, TestBed, ComponentFixtureAutoDetect, } from '@angular/core/testing'; import { TranslateService } from '@ngx-translate/core'; import { ListProjectComponent } from './list-project.component'; import { CUSTOM_ELEMENTS_SCHEMA, ChangeDetectorRef } from '@angular/core'; import { SessionService } from '../../../../shared/services/session.service'; import { AppConfigService } from '../../../../services/app-config.service'; import { SearchTriggerService } from '../../../../shared/components/global-search/search-trigger.service'; import { MessageHandlerService } from '../../../../shared/services/message-handler.service'; import { StatisticHandler } from '../statictics/statistic-handler.service'; import { of } from 'rxjs'; import { delay } from 'rxjs/operators'; import { ProjectService } from '../../../../shared/services'; import { OperationService } from '../../../../shared/components/operation/operation.service'; import { ConfirmationDialogService } from '../../../global-confirmation-dialog/confirmation-dialog.service'; import { SharedTestingModule } from '../../../../shared/shared.module'; describe('ListProjectComponent', () => { let component: ListProjectComponent; let fixture: ComponentFixture<ListProjectComponent>; const mockProjectService = { listProjects: () => { return of({ body: [], }).pipe(delay(0)); }, }; const mockSessionService = { getCurrentUser: () => { return false; }, }; const mockAppConfigService = { getConfig: () => { return { project_creation_restriction: '', with_chartmuseum: '', }; }, }; const mockSearchTriggerService = { closeSearch: () => {}, }; const mockStatisticHandler = { handleError: () => {}, }; const mockMessageHandlerService = { refresh: () => {}, showSuccess: () => {}, }; const mockConfirmationDialogService = { confirmationConfirm$: of({ state: '', data: [], }), }; const mockOperationService = { publishInfo$: () => {}, }; beforeEach(() => { TestBed.configureTestingModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA], imports: [SharedTestingModule], declarations: [ListProjectComponent], providers: [ TranslateService, ChangeDetectorRef, { provide: ProjectService, useValue: mockProjectService }, { provide: SessionService, useValue: mockSessionService }, { provide: AppConfigService, useValue: mockAppConfigService }, { provide: SearchTriggerService, useValue: mockSearchTriggerService, }, { provide: MessageHandlerService, useValue: mockMessageHandlerService, }, { provide: StatisticHandler, useValue: mockStatisticHandler }, { provide: ConfirmationDialogService, useValue: mockConfirmationDialogService, }, { provide: OperationService, useValue: mockOperationService }, { provide: ComponentFixtureAutoDetect, useValue: true }, ], }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(ListProjectComponent); component = fixture.componentInstance; fixture.detectChanges(); }); let originalTimeout; beforeEach(function () { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000; }); afterEach(function () { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it('should create', () => { expect(component).toBeTruthy(); }); }); ```
/content/code_sandbox/src/portal/src/app/base/left-side-nav/projects/list-project/list-project.component.spec.ts
xml
2016-01-28T21:10:28
2024-08-16T15:28:34
harbor
goharbor/harbor
23,335
702
```xml <?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="path_to_url" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../Resources.resx"> <body> <trans-unit id=your_sha256_hashng"> <source>A list of relative file or folder paths to exclude from formatting.</source> <target state="translated">Liste des chemins relatifs de fichier ou de dossier exclure de la mise en forme.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hash_All_files_are_formatted_if_empty"> <source>A list of relative file or folder paths to include in formatting. All files are formatted if empty.</source> <target state="translated">Liste des chemins relatifs de fichier ou de dossier inclure dans la mise en forme. Si non renseign, tous les fichiers sont mis en forme.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashyour_sha256_hashurrent_directory_is_used"> <source>A path to a solution file, a project file, or a folder containing a solution or project file. If a path is not specified then the current directory is used.</source> <target state="translated">Chemin d'un fichier solution, d'un fichier projet ou d'un dossier contenant un fichier solution ou un fichier projet. Si aucun chemin n'est spcifi, le rpertoire actif est utilis.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashode_style_or_3rd_party_issues"> <source>A space separated list of diagnostic ids to ignore when fixing code style or 3rd party issues.</source> <target state="new">A space separated list of diagnostic ids to ignore when fixing code style or 3rd party issues.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hash_fixing_code_style_or_3rd_party_issues"> <source>A space separated list of diagnostic ids to use as a filter when fixing code style or 3rd party issues.</source> <target state="new">A space separated list of diagnostic ids to use as a filter when fixing code style or 3rd party issues.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashrt_json_file_in_the_given_directory"> <source>Accepts a file path, which if provided, will produce a json report in the given directory.</source> <target state="translated">Accepte un chemin de fichier, qui, s'il est fourni, produit un rapport JSON dans le rpertoire donn.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hash_in_the_given_directory"> <source>Accepts a file path which if provided will produce a json report in the given directory.</source> <target state="new">Accepts a file path which if provided will produce a json report in the given directory.</target> <note /> </trans-unit> <trans-unit id="Analysis_complete_in_0ms."> <source>Analysis complete in {0}ms.</source> <target state="translated">Analyse effectue en {0}ms.</target> <note /> </trans-unit> <trans-unit id="Analyzer_Reference"> <source>Analyzer Reference</source> <target state="translated">Rfrence de l'analyseur</target> <note /> </trans-unit> <trans-unit id=your_sha256_hash_which_to_use_with_the_workspace_argument"> <source>Both a MSBuild project file and solution file found in '{0}'. Specify which to use with the &lt;workspace&gt; argument.</source> <target state="translated">Fichier projet et fichier solution MSBuild trouvs dans '{0}'. Spcifiez celui qui doit tre utilis avec l'argument &lt;espace de travail&gt;.</target> <note /> </trans-unit> <trans-unit id="Cannot_specify_the_folder_option_when_fixing_style"> <source>Cannot specify the '--folder' option when fixing style.</source> <target state="new">Cannot specify the '--folder' option when fixing style.</target> <note /> </trans-unit> <trans-unit id="Cannot_specify_the_folder_option_when_running_analyzers"> <source>Cannot specify the '--folder' option when running analyzers.</source> <target state="new">Cannot specify the '--folder' option when running analyzers.</target> <note /> </trans-unit> <trans-unit id="Cannot_specify_the_folder_option_with_no_restore"> <source>Cannot specify the '--folder' option with '--no-restore'.</source> <target state="new">Cannot specify the '--folder' option with '--no-restore'.</target> <note /> </trans-unit> <trans-unit id="Cannot_specify_the_folder_option_when_writing_a_binary_log"> <source>Cannot specify the '--folder' option when writing a binary log.</source> <target state="new">Cannot specify the '--folder' option when writing a binary log.</target> <note /> </trans-unit> <trans-unit id="Code_Style"> <source>Code Style</source> <target state="translated">Style de code</target> <note /> </trans-unit> <trans-unit id="Complete_in_0_ms"> <source>Complete in {0}ms.</source> <target state="translated">Effectu en {0}ms.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashhich_to_use_with_the_workspace_argument"> <source>Could not find a MSBuild project file or solution file in '{0}'. Specify which to use with the &lt;workspace&gt; argument.</source> <target state="translated">Le fichier projet ou le fichier solution MSBuild est introuvable dans '{0}'. Spcifiez celui qui doit tre utilis avec l'argument &lt;espace de travail&gt;.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashual_Basic_projects"> <source>Could not format '{0}'. Format currently supports only C# and Visual Basic projects.</source> <target state="translated">Impossible de mettre en forme '{0}'. L'opration Mettre en forme prend uniquement en charge les projets C# et Visual Basic pour le moment.</target> <note /> </trans-unit> <trans-unit id="Delete_0_characters"> <source>Delete {0} characters.</source> <target state="new">Delete {0} characters.</target> <note /> </trans-unit> <trans-unit id="Determining_diagnostics"> <source>Determining diagnostics...</source> <target state="translated">Dtermination des diagnostics...</target> <note /> </trans-unit> <trans-unit id="Determining_formattable_files"> <source>Determining formattable files.</source> <target state="translated">Identification des fichiers pouvant tre mis en forme.</target> <note /> </trans-unit> <trans-unit id="Doesnt_execute_an_implicit_restore_before_formatting"> <source>Doesn't execute an implicit restore before formatting.</source> <target state="new">Doesn't execute an implicit restore before formatting.</target> <note /> </trans-unit> <trans-unit id="Failed_to_apply_code_fix_0_for_1_2"> <source>Failed to apply code fix {0} for {1}: {2}</source> <target state="translated">chec de l'application du correctif de code {0} pour {1}: {2}</target> <note /> </trans-unit> <trans-unit id="Failed_to_save_formatting_changes"> <source>Failed to save formatting changes.</source> <target state="translated">L'enregistrement des changements de mise en forme a chou.</target> <note /> </trans-unit> <trans-unit id="Fix_end_of_line_marker"> <source>Fix end of line marker.</source> <target state="translated">Corrigez le marqueur de fin de ligne.</target> <note /> </trans-unit> <trans-unit id="Fix_file_encoding"> <source>Fix file encoding.</source> <target state="translated">Corrigez l'encodage de fichier.</target> <note /> </trans-unit> <trans-unit id="Fix_final_newline"> <source>Fix final newline.</source> <target state="translated">Corrigez la nouvelle ligne de fin.</target> <note /> </trans-unit> <trans-unit id="Fix_imports_ordering"> <source>Fix imports ordering.</source> <target state="translated">Corrigez le classement des importations.</target> <note /> </trans-unit> <trans-unit id="Fix_whitespace_formatting"> <source>Fix whitespace formatting.</source> <target state="translated">Corrigez la mise en forme des espaces blancs.</target> <note /> </trans-unit> <trans-unit id="Fixing_diagnostics"> <source>Fixing diagnostics...</source> <target state="translated">Correction des diagnostics...</target> <note /> </trans-unit> <trans-unit id="Format_complete_in_0_ms"> <source>Format complete in {0}ms.</source> <target state="translated">Mise en forme effectue en {0}ms.</target> <note /> </trans-unit> <trans-unit id="Format_files_generated_by_the_SDK"> <source>Format files generated by the SDK.</source> <target state="new">Format files generated by the SDK.</target> <note /> </trans-unit> <trans-unit id="Formats_code_to_match_editorconfig_settings"> <source>Formats code to match editorconfig settings.</source> <target state="new">Formats code to match editorconfig settings.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashon_zero_exit_code_if_any_files_were_formatted"> <source>Formats files without saving changes to disk. Terminates with a non-zero exit code if any files were formatted.</source> <target state="translated">Met en forme les fichiers sans enregistrer les changements sur le disque. Se termine par un code de sortie non nul si des fichiers ont t mis en forme.</target> <note /> </trans-unit> <trans-unit id="Formatted_0_of_1_files"> <source>Formatted {0} of {1} files.</source> <target state="translated">{0}fichiers mis en forme sur{1}.</target> <note /> </trans-unit> <trans-unit id="Formatting_code_file_0"> <source>Formatting code file '{0}'.</source> <target state="translated">Mise en forme du fichier de code '{0}'.</target> <note /> </trans-unit> <trans-unit id="Formatting_code_files_in_workspace_0"> <source>Formatting code files in workspace '{0}'.</source> <target state="translated">Mise en forme des fichiers de code dans l'espace de travail '{0}'.</target> <note /> </trans-unit> <trans-unit id="Include_generated_code_files_in_formatting_operations"> <source>Include generated code files in formatting operations.</source> <target state="translated">Ajoutez des fichiers de code gnrs dans les oprations de mise en forme.</target> <note /> </trans-unit> <trans-unit id="Insert_0"> <source>Insert '{0}'.</source> <target state="new">Insert '{0}'.</target> <note /> </trans-unit> <trans-unit id="Loading_workspace"> <source>Loading workspace.</source> <target state="translated">Chargement de l'espace de travail.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashe"> <source>Log all project or solution load information to a binary log file.</source> <target state="new">Log all project or solution load information to a binary log file.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashith_the_workspace_argument"> <source>Multiple MSBuild project files found in '{0}'. Specify which to use with the &lt;workspace&gt; argument.</source> <target state="translated">Plusieurs fichiers projet MSBuild trouvs dans '{0}'. Spcifiez celui qui doit tre utilis avec l'argument &lt;espace de travail&gt;.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashwith_the_workspace_argument"> <source>Multiple MSBuild solution files found in '{0}'. Specify which to use with the &lt;workspace&gt; argument.</source> <target state="translated">Plusieurs fichiers solution MSBuild trouvs dans '{0}'. Spcifiez celui qui doit tre utilis avec l'argument &lt;espace de travail&gt;.</target> <note /> </trans-unit> <trans-unit id="Project_0_is_using_configuration_from_1"> <source>Project {0} is using configuration from '{1}'.</source> <target state="new">Project {0} is using configuration from '{1}'.</target> <note /> </trans-unit> <trans-unit id="Replace_0_characters_with_1"> <source>Replace {0} characters with '{1}'.</source> <target state="new">Replace {0} characters with '{1}'.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hash_dotnet_restore_prior_to_formatting"> <source>Required references did not load for {0} or referenced project. Run `dotnet restore` prior to formatting.</source> <target state="new">Required references did not load for {0} or referenced project. Run `dotnet restore` prior to formatting.</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_import"> <source>Remove unnecessary import.</source> <target state="new">Remove unnecessary import.</target> <note /> </trans-unit> <trans-unit id="Run_3rd_party_analyzers__and_apply_fixes"> <source>Run 3rd party analyzers and apply fixes.</source> <target state="new">Run 3rd party analyzers and apply fixes.</target> <note /> </trans-unit> <trans-unit id="Run_3rd_party_analyzers_and_apply_fixes"> <source>Run 3rd party analyzers and apply fixes.</source> <target state="translated">Excutez des analyseurs tiers et appliquez des correctifs.</target> <note /> </trans-unit> <trans-unit id="Run_code_style_analyzers_and_apply_fixes"> <source>Run code style analyzers and apply fixes.</source> <target state="translated">Excutez des analyseurs de style de code et appliquez des correctifs.</target> <note /> </trans-unit> <trans-unit id="Run_whitespace_formatting"> <source>Run whitespace formatting.</source> <target state="new">Run whitespace formatting.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hash> <source>Run whitespace formatting. Run by default when not applying fixes.</source> <target state="new">Run whitespace formatting. Run by default when not applying fixes.</target> <note /> </trans-unit> <trans-unit id="Running_0_analysis"> <source>Running {0} analysis.</source> <target state="translated">Excution de l'analyse de {0}.</target> <note /> </trans-unit> <trans-unit id="Running_0_analyzers_on_1"> <source>Running {0} analyzers on {1}.</source> <target state="new">Running {0} analyzers on {1}.</target> <note /> </trans-unit> <trans-unit id="Running_formatters"> <source>Running formatters.</source> <target state="translated">Excution des formateurs.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashdetailed_and_diagnostic"> <source>Set the verbosity level. Allowed values are q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]</source> <target state="translated">Dfinissez le niveau de dtail. Les valeurs autorises sont q[uiet], m[inimal], n[ormal], d[etailed] et diag[nostic]</target> <note /> </trans-unit> <trans-unit id="Skipping_referenced_project_0"> <source>Skipping referenced project '{0}'.</source> <target state="translated">Saut du projet rfrenc '{0}'.</target> <note /> </trans-unit> <trans-unit id="SolutionOrProjectArgumentDescription"> <source>The project or solution file to operate on. If a file is not specified, the command will search the current directory for one.</source> <target state="translated">Fichier projet ou solution utiliser. Si vous ne spcifiez pas de fichier, la commande en recherche un dans le rpertoire actuel.</target> <note /> </trans-unit> <trans-unit id="SolutionOrProjectArgumentName"> <source>PROJECT | SOLUTION</source> <target state="translated">PROJECT | SOLUTION</target> <note /> </trans-unit> <trans-unit id="Solution_0_has_ no_projects"> <source>Solution {0} has no projects</source> <target state="translated">La solution {0} n'a aucun projet</target> <note /> </trans-unit> <trans-unit id="Standard_input_used_multiple_times"> <source>Standard input markers ('/dev/stdin', '-') can only be used either with `--include` or `--exclude`, but not both.</source> <target state="new">Standard input markers ('/dev/stdin', '-') can only be used either with `--include` or `--exclude`, but not both.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hash_analyzers"> <source>The '--diagnostics' option only applies when fixing style or running analyzers.</source> <target state="new">The '--diagnostics' option only applies when fixing style or running analyzers.</target> <note /> </trans-unit> <trans-unit id="The_dotnet_CLI_version_is_0"> <source>The dotnet CLI version is '{0}'.</source> <target state="translated">La version de l'interface CLI dotnet est '{0}'.</target> <note /> </trans-unit> <trans-unit id="The_dotnet_format_version_is_0"> <source>The dotnet format version is '{0}'.</source> <target state="new">The dotnet format version is '{0}'.</target> <note /> </trans-unit> <trans-unit id="The_dotnet_runtime_version_is_0"> <source>The dotnet runtime version is '{0}'.</source> <target state="new">The dotnet runtime version is '{0}'.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashe"> <source>The file '{0}' does not appear to be a valid project or solution file.</source> <target state="translated">Le fichier '{0}' ne semble pas tre un fichier projet ou solution valide.</target> <note /> </trans-unit> <trans-unit id="The_project_file_0_does_not_exist"> <source>The project file '{0}' does not exist.</source> <target state="translated">Le fichier projet '{0}' n'existe pas.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashand_error"> <source>The severity of diagnostics to fix. Allowed values are info, warn, and error.</source> <target state="new">The severity of diagnostics to fix. Allowed values are info, warn, and error.</target> <note /> </trans-unit> <trans-unit id="The_solution_file_0_does_not_exist"> <source>The solution file '{0}' does not exist.</source> <target state="translated">Le fichier solution '{0}' n'existe pas.</target> <note /> </trans-unit> <trans-unit id="Formatted_code_file_0"> <source>Formatted code file '{0}'.</source> <target state="translated">Fichier de code '{0}' mis en forme.</target> <note /> </trans-unit> <trans-unit id="Unable_to_fix_0_Code_fix_1_didnt_return_a_Fix_All_action"> <source>Unable to fix {0}. Code fix {1} didn't return a Fix All action.</source> <target state="new">Unable to fix {0}. Code fix {1} didn't return a Fix All action.</target> <note /> </trans-unit> <trans-unit id="Unable_to_fix_0_Code_fix_1_doesnt_support_Fix_All_in_Solution"> <source>Unable to fix {0}. Code fix {1} doesn't support Fix All in Solution.</source> <target state="translated">Impossible de corriger {0}. Le correctif de code {1} ne prend pas en charge la fonctionnalit Tout corriger dans la solution.</target> <note /> </trans-unit> <trans-unit id="Unable_to_fix_0_Code_fix_1_returned_an_unexpected_operation"> <source>Unable to fix {0}. Code fix {1} returned an unexpected operation.</source> <target state="new">Unable to fix {0}. Code fix {1} returned an unexpected operation.</target> <note /> </trans-unit> <trans-unit id="Unable_to_fix_0_No_associated_code_fix_found"> <source>Unable to fix {0}. No associated code fix found.</source> <target state="new">Unable to fix {0}. No associated code fix found.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashhe_official_installer"> <source>Unable to locate MSBuild. Ensure the .NET SDK was installed with the official installer.</source> <target state="translated">Impossible de localiser MSBuild. Vrifiez que le SDK .NET a t install avec le programme d'installation officiel.</target> <note /> </trans-unit> <trans-unit id="Unable_to_locate_dotnet_CLI_Ensure_that_it_is_on_the_PATH"> <source>Unable to locate dotnet CLI. Ensure that it is on the PATH.</source> <target state="translated">Impossible de localiser l'interface CLI dotnet. Vrifiez qu'elle est dans le chemin.</target> <note /> </trans-unit> <trans-unit id="Unable_to_organize_imports_for_0_The_document_is_too_complex"> <source>Unable to organize imports for '{0}'. The document is too complex.</source> <target state="translated">Impossible d'organiser les importations pour '{0}'. Le document est trop complexe.</target> <note /> </trans-unit> <trans-unit id="Using_msbuildexe_located_in_0"> <source>Using MSBuild.exe located in '{0}'.</source> <target state="translated">Utilisation de MSBuild.exe dans '{0}'.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hasha_non_zero_exit_code_if_any_files_would_have_been_formatted"> <source>Verify no formatting changes would be performed. Terminates with a non-zero exit code if any files would have been formatted.</source> <target state="new">Verify no formatting changes would be performed. Terminates with a non-zero exit code if any files would have been formatted.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashrbosity_option_to_the_diagnostic_level_to_log_warnings"> <source>Warnings were encountered while loading the workspace. Set the verbosity option to the 'diagnostic' level to log warnings.</source> <target state="translated">Des avertissements ont t rencontrs pendant le chargement de l'espace de travail. Dfinissez l'option verbosity sur le niveau diagnostic pour journaliser les avertissements.</target> <note /> </trans-unit> <trans-unit id=your_sha256_hashles"> <source>Whether to treat the `&lt;workspace&gt;` argument as a simple folder of files.</source> <target state="translated">Indique si l'argument '&lt;espace de travail&gt;' doit tre trait en tant que simple dossier de fichiers.</target> <note /> </trans-unit> <trans-unit id="Writing_formatting_report_to_0"> <source>Writing formatting report to: '{0}'.</source> <target state="translated">criture du rapport de mise en forme dans '{0}'.</target> <note /> </trans-unit> </body> </file> </xliff> ```
/content/code_sandbox/src/BuiltInTools/dotnet-format/xlf/Resources.fr.xlf
xml
2016-07-22T21:26:02
2024-08-16T17:23:58
sdk
dotnet/sdk
2,627
5,730