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 range from 'lodash/range'
import random from 'lodash/random'
import shuffle from 'lodash/shuffle'
import { timeDays } from 'd3-time'
import { timeFormat } from 'd3-time-format'
import * as color from './color'
import * as sets from './sets'
export { sets }
export const randColor = color.randColor
export const generateProgrammingLanguageStats = (shouldShuffle = true, limit = -1) => {
let langs = sets.programmingLanguages
if (shouldShuffle) {
langs = shuffle(langs)
}
if (limit < 1) {
limit = 1 + Math.round(Math.random() * (sets.programmingLanguages.length - 1))
}
return langs.slice(0, limit).map(language => ({
label: language,
value: Math.round(Math.random() * 600),
color: randColor(),
}))
}
export const uniqRand = <T>(generator: (...args: unknown[]) => T) => {
const used: T[] = []
return (...args: unknown[]) => {
let value
do {
value = generator(...args)
} while (used.includes(value))
used.push(value)
return value
}
}
export const randCountryCode = () => shuffle(sets.countryCodes)[0]
type DrinkDatum = {
id: string
color: string
data: Array<{
color: string
x: string
y: number
}>
}
export const generateDrinkStats = (xSize = 16) => {
const rand = () => random(0, 60)
const types = ['whisky', 'rhum', 'gin', 'vodka', 'cognac']
const country = uniqRand(randCountryCode)
const data: DrinkDatum[] = types.map(id => ({
id,
color: randColor(),
data: [],
}))
range(xSize).forEach(() => {
const x = country()
types.forEach(id => {
data.find(d => d.id === id)?.data.push({
color: randColor(),
x,
y: rand(),
})
})
})
return data
}
export const generateSerie = (xSize = 20) => {
const max = 100 + Math.random() * (Math.random() * 600)
return range(xSize).map(() => Math.round(Math.random() * max))
}
export const generateSeries = (ids: string[], xKeys: string[]) =>
ids.map(id => ({
id,
color: randColor(),
data: xKeys.map(x => ({ x, y: Math.round(Math.random() * 300) })),
}))
export const generateStackData = (size = 3) => {
const length = 16
return range(size).map(() => generateSerie(length).map((v, i) => ({ x: i, y: v })))
}
export const generateCountriesPopulation = (size: number) => {
const countryCode = uniqRand(randCountryCode)
return range(size).map(() => ({
country: countryCode(),
population: 200 + Math.round(Math.random() * Math.random() * 1000000),
}))
}
export const generateOrderedDayCounts = (from: Date, to: Date) => {
const days = timeDays(from, to)
const dayFormat = timeFormat('%Y-%m-%d')
return days.map(day => {
return {
value: Math.round(Math.random() * 400),
day: dayFormat(day),
}
})
}
export const generateDayCounts = (from: Date, to: Date, maxSize = 0.9) => {
const days = generateOrderedDayCounts(from, to)
const size =
Math.round(days.length * (maxSize * 0.4)) +
Math.round(Math.random() * (days.length * (maxSize * 0.6)))
return shuffle(days).slice(0, size)
}
export const generateCountriesData = (
keys: string[],
{ size = 12, min = 0, max = 200, withColors = true } = {}
) =>
sets.countryCodes.slice(0, size).map(country => {
const d: Record<string, unknown> = {
country,
}
keys.forEach(key => {
d[key] = random(min, max)
if (withColors === true) {
d[`${key}Color`] = randColor()
}
})
return d
})
const libTreeItems = [
[
'viz',
[
['stack', [['cchart'], ['xAxis'], ['yAxis'], ['layers']]],
[
'ppie',
[
['chart', [['pie', [['outline'], ['slices'], ['bbox']]], ['donut'], ['gauge']]],
['legends'],
],
],
],
],
['colors', [['rgb'], ['hsl']]],
[
'utils',
[['randomize'], ['resetClock'], ['noop'], ['tick'], ['forceGC'], ['stackTrace'], ['dbg']],
],
['generators', [['address'], ['city'], ['animal'], ['movie'], ['user']]],
[
'set',
[
['clone'],
['intersect'],
['merge'],
['reverse'],
['toArray'],
['toObject'],
['fromCSV'],
['slice'],
['append'],
['prepend'],
['shuffle'],
['pick'],
['plouc'],
],
],
[
'text',
[
['trim'],
['slugify'],
['snakeCase'],
['camelCase'],
['repeat'],
['padLeft'],
['padRight'],
['sanitize'],
['ploucify'],
],
],
[
'misc',
[
['greetings', [['hey'], ['HOWDY'], ['aloha'], ['AHOY']]],
['other'],
[
'path',
[
['pathA'],
['pathB', [['pathB1'], ['pathB2'], ['pathB3'], ['pathB4']]],
[
'pathC',
[
['pathC1'],
['pathC2'],
['pathC3'],
['pathC4'],
['pathC5'],
['pathC6'],
['pathC7'],
['pathC8'],
['pathC9'],
],
],
],
],
],
],
]
interface LibTreeDatum {
name: string
loc?: number
color: string
children?: LibTreeDatum[]
}
export const generateLibTree = (
name = 'nivo',
limit?: number | null,
children = libTreeItems
): LibTreeDatum => {
limit = limit || children.length
if (limit > children.length) {
limit = children.length
}
const tree: LibTreeDatum = {
name,
color: randColor(),
}
if (children?.length > 0) {
tree.children = range(limit).map((_, i) => {
const leaf = children[i]
// full path `${name}.${leaf[0]}`
return generateLibTree(leaf[0] as string, null, (leaf[1] ?? []) as any)
})
} else {
tree.loc = Math.round(Math.random() * 200000)
}
return tree
}
const wines = ['chardonay', 'carmenere', 'syrah']
const wineTastes = ['fruity', 'bitter', 'heavy', 'strong', 'sunny']
export const generateWinesTastes = ({ randMin = 20, randMax = 120 } = {}) => {
const data = wineTastes.map(taste => {
const d: Record<string, unknown> = { taste }
wines.forEach(wine => {
d[wine] = random(randMin, randMax)
})
return d
})
return { data, keys: wines }
}
export * from './boxplot'
export * from './bullet'
export * from './chord'
export * from './network'
export * from './parallelCoordinates'
export * from './sankey'
export * from './swarmplot'
export * from './waffle'
export * from './xySeries'
``` | /content/code_sandbox/packages/generators/src/index.ts | xml | 2016-04-16T03:27:56 | 2024-08-16T03:38:37 | nivo | plouc/nivo | 13,010 | 1,782 |
```xml
var logger: {
log(val: any, val2: any),
error(val: any)
};
``` | /content/code_sandbox/tests/format/typescript/conformance/types/methodSignature/methodSignature.ts | xml | 2016-11-29T17:13:37 | 2024-08-16T17:29:57 | prettier | prettier/prettier | 48,913 | 23 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
import {Column, Grid, Link} from '@carbon/react';
import CheckImage from 'modules/images/orange-check-mark.svg';
import {getStateLocally} from 'modules/utils/localStorage';
import {Restricted} from 'modules/components/Restricted';
import {useTasks} from 'modules/queries/useTasks';
import {useTaskFilters} from 'modules/hooks/useTaskFilters';
import {useEffect} from 'react';
import {useTranslation, Trans} from 'react-i18next';
import {decodeTaskEmptyPageRef} from 'modules/utils/reftags';
import {useSearchParams} from 'react-router-dom';
import {tracking} from 'modules/tracking';
import styles from './styles.module.scss';
const EmptyPage: React.FC = () => {
const filters = useTaskFilters();
const {isPending, data} = useTasks(filters);
const tasks = data?.pages.flat() ?? [];
const hasNoTasks = tasks.length === 0;
const isOldUser = getStateLocally('hasCompletedTask') === true;
const [searchParams, setSearchParams] = useSearchParams();
const {t} = useTranslation();
useEffect(() => {
const ref = searchParams.get('ref');
if (ref !== null) {
searchParams.delete('ref');
setSearchParams(searchParams, {replace: true});
}
const taskEmptyPageOpenedRef = decodeTaskEmptyPageRef(ref);
tracking.track({
eventName: 'task-empty-page-opened',
...(taskEmptyPageOpenedRef ?? {}),
});
}, [searchParams, setSearchParams]);
if (isPending) {
return <span data-testid="loading-state" />;
}
if (hasNoTasks && isOldUser) {
return null;
}
return (
<Grid className={styles.container} condensed>
<Column
className={styles.imageContainer}
sm={1}
md={{
span: 2,
offset: 1,
}}
lg={{
span: 2,
offset: 4,
}}
xlg={{
span: 1,
offset: 5,
}}
>
<img className={styles.image} src={CheckImage} alt="" />
</Column>
<Column
className={isOldUser ? styles.oldUserText : styles.newUserText}
sm={3}
md={5}
lg={10}
xlg={10}
>
{isOldUser ? (
<Restricted
fallback={<h3>{t('taskEmptyPickPromptRestricted')}</h3>}
scopes={['write']}
>
<h3>{t('taskEmptyPickPrompt')}</h3>
</Restricted>
) : (
<>
<h3>{t('taskEmptyHeader')}</h3>
<p data-testid="first-paragraph">
{t('taskEmptyDetail1')}
<br />
{t('taskEmptyDetail2')}
</p>
{!hasNoTasks && <p>{t('taskEmptyTaskAvailablePrompt')}</p>}
<p data-testid="tutorial-paragraph">
<Trans i18nKey="taskEmptyTutorial">
Follow our tutorial to{' '}
<Link
href="path_to_url"
target="_blank"
rel="noreferrer"
inline
>
learn how to create tasks.
</Link>
</Trans>
</p>
</>
)}
</Column>
</Grid>
);
};
EmptyPage.displayName = 'EmptyPage';
export {EmptyPage as Component};
``` | /content/code_sandbox/tasklist/client/src/Tasks/EmptyPage/index.tsx | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 777 |
```xml
import { Directive, EventEmitter, Input, Output } from '@angular/core';
@Directive()
export abstract class BaseDirective {
@Input() testPropertyInBase = false;
@Output() testEventInBase = new EventEmitter<void>();
}
``` | /content/code_sandbox/test/fixtures/todomvc-ng2/src/app/shared/directives/base.directive.ts | xml | 2016-10-17T07:09:28 | 2024-08-14T16:30:10 | compodoc | compodoc/compodoc | 3,980 | 50 |
```xml
import { GridsterItemComponentInterface } from './gridsterItem.interface';
import { GridsterComponentInterface } from './gridster.interface';
export class GridsterSwap {
private swapedItem: GridsterItemComponentInterface | undefined;
private gridsterItem: GridsterItemComponentInterface;
private gridster: GridsterComponentInterface;
constructor(gridsterItem: GridsterItemComponentInterface) {
this.gridsterItem = gridsterItem;
this.gridster = gridsterItem.gridster;
}
destroy(): void {
this.gridster = this.gridsterItem = this.swapedItem = null!;
}
swapItems(): void {
if (this.gridster.$options.swap) {
this.checkSwapBack();
this.checkSwap(this.gridsterItem);
}
}
checkSwapBack(): void {
if (this.swapedItem) {
const x: number = this.swapedItem.$item.x;
const y: number = this.swapedItem.$item.y;
this.swapedItem.$item.x = this.swapedItem.item.x || 0;
this.swapedItem.$item.y = this.swapedItem.item.y || 0;
if (this.gridster.checkCollision(this.swapedItem.$item)) {
this.swapedItem.$item.x = x;
this.swapedItem.$item.y = y;
} else {
this.swapedItem.setSize();
this.gridsterItem.$item.x = this.gridsterItem.item.x || 0;
this.gridsterItem.$item.y = this.gridsterItem.item.y || 0;
this.swapedItem = undefined;
}
}
}
restoreSwapItem(): void {
if (this.swapedItem) {
this.swapedItem.$item.x = this.swapedItem.item.x || 0;
this.swapedItem.$item.y = this.swapedItem.item.y || 0;
this.swapedItem.setSize();
this.swapedItem = undefined;
}
}
setSwapItem(): void {
if (this.swapedItem) {
this.swapedItem.checkItemChanges(
this.swapedItem.$item,
this.swapedItem.item
);
this.swapedItem = undefined;
}
}
checkSwap(pushedBy: GridsterItemComponentInterface): void {
let gridsterItemCollision;
if (this.gridster.$options.swapWhileDragging) {
gridsterItemCollision = this.gridster.checkCollisionForSwaping(
pushedBy.$item
);
} else {
gridsterItemCollision = this.gridster.checkCollision(pushedBy.$item);
}
if (
gridsterItemCollision &&
gridsterItemCollision !== true &&
gridsterItemCollision.canBeDragged()
) {
const gridsterItemCollide: GridsterItemComponentInterface =
gridsterItemCollision;
const copyCollisionX = gridsterItemCollide.$item.x;
const copyCollisionY = gridsterItemCollide.$item.y;
const copyX = pushedBy.$item.x;
const copyY = pushedBy.$item.y;
const diffX = copyX - copyCollisionX;
const diffY = copyY - copyCollisionY;
gridsterItemCollide.$item.x = pushedBy.item.x - diffX;
gridsterItemCollide.$item.y = pushedBy.item.y - diffY;
pushedBy.$item.x = gridsterItemCollide.item.x + diffX;
pushedBy.$item.y = gridsterItemCollide.item.y + diffY;
if (
this.gridster.checkCollision(gridsterItemCollide.$item) ||
this.gridster.checkCollision(pushedBy.$item)
) {
pushedBy.$item.x = copyX;
pushedBy.$item.y = copyY;
gridsterItemCollide.$item.x = copyCollisionX;
gridsterItemCollide.$item.y = copyCollisionY;
} else {
gridsterItemCollide.setSize();
this.swapedItem = gridsterItemCollide;
if (this.gridster.$options.swapWhileDragging) {
this.gridsterItem.checkItemChanges(
this.gridsterItem.$item,
this.gridsterItem.item
);
this.setSwapItem();
}
}
}
}
}
``` | /content/code_sandbox/projects/angular-gridster2/src/lib/gridsterSwap.service.ts | xml | 2016-01-13T10:43:19 | 2024-08-14T12:20:18 | angular-gridster2 | tiberiuzuld/angular-gridster2 | 1,267 | 915 |
```xml
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import * as strings from 'SiteProvisioningManagerWebPartStrings';
import SiteProvisioningWebPart from './components/App/App';
import { IAppProps } from './components/App/IAppProps';
import { AadHttpClient } from '@microsoft/sp-http';
import AppService from '../../services/appService';
export interface ISiteProvisioningManagerWebPartProps {
ApplicationId: string;
GetTemplateFunctionUrl: string;
ApplyTemplateFunctionUrl: string;
}
export default class SiteProvisioningManagerWebPart extends BaseClientSideWebPart<ISiteProvisioningManagerWebPartProps> {
private appService: AppService;
private aadClient: AadHttpClient;
public onInit(): Promise<void> {
return super.onInit().then(async _ => {
const { GetTemplateFunctionUrl, ApplyTemplateFunctionUrl } = this.properties;
const clientId: string = this.properties.ApplicationId;
this.aadClient = await this.context.aadHttpClientFactory.getClient(clientId);
this.appService = new AppService(this.context, this.aadClient, GetTemplateFunctionUrl, ApplyTemplateFunctionUrl);
});
}
public render(): void {
const element: React.ReactElement<IAppProps> = React.createElement(
SiteProvisioningWebPart,
{
appService: this.appService,
webUrl: this.context.pageContext.web.absoluteUrl
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('ApplicationId', {
label: strings.ClientIdFieldLabel
}),
PropertyPaneTextField('GetTemplateFunctionUrl', {
label: strings.GetProvisioningUrlFieldLabel
}),
PropertyPaneTextField('ApplyTemplateFunctionUrl', {
label: strings.ApplyProvisioningUrlFieldLabel
})
]
}
]
}
]
};
}
}
``` | /content/code_sandbox/samples/react-site-provisioning-manager/webpart/src/webparts/siteProvisioningManager/SiteProvisioningManagerWebPart.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 543 |
```xml
import * as routerUtils from "@erxes/ui/src/utils/router";
import { BarItems, HeaderContent } from "@erxes/ui/src/layout/styles";
import React, { useState } from "react";
import { CustomRangeContainer } from "@erxes/ui-forms/src/forms/styles";
import DataWithLoader from "@erxes/ui/src/components/DataWithLoader";
import DateControl from "@erxes/ui/src/components/form/DateControl";
import EmptyContent from "@erxes/ui/src/components/empty/EmptyContent";
import FormControl from "@erxes/ui/src/components/form/Control";
import { IGolomtBankStatement } from "../../../types/ITransactions";
import Pagination from "@erxes/ui/src/components/pagination/Pagination";
import Row from "./Row";
import Table from "@erxes/ui/src/components/table";
import { __ } from "@erxes/ui/src/utils/core";
import dayjs from "dayjs";
import { useLocation, useNavigate } from "react-router-dom";
type Props = {
statement: IGolomtBankStatement;
queryParams: any;
loading: boolean;
showLatest?: boolean;
};
const List = (props: Props) => {
const { queryParams, loading, statement } = props;
const location = useLocation();
const navigate = useNavigate();
const [type, setType] = useState(queryParams.type || "all");
const [transactions, setTransactions] = useState(
(statement && statement.statements) || []
);
const totalCount = statement?.statements?.length || 0;
const incomes = statement?.statements?.filter((t) => t.tranAmount > 0) || [];
const outcomes = statement?.statements?.filter((t) => t.tranAmount < 0) || [];
React.useEffect(() => {
switch (type) {
case "income":
setTransactions(incomes);
break;
case "outcome":
setTransactions(outcomes);
break;
default:
setTransactions(statement.statements || []);
break;
}
}, [type]);
const headingText =
totalCount > 0 ? `${statement.accountId}` : __("No transactions");
const renderRow = () => {
return transactions.map((transaction) => (
<Row key={transaction.requestId} transaction={transaction} />
));
};
queryParams.loadingMainQuery = loading;
const content = (
<Table $whiteSpace="nowrap" $hover={true}>
<thead>
<tr>
<th>{__("Date")}</th>
<th>{__("Description")}</th>
<th>{__("Begin balance")}</th>
<th>{__("End balance")}</th>
<th>{__("Amount")}</th>
</tr>
</thead>
<tbody>{renderRow()}</tbody>
</Table>
);
const rightActionBar = (
<BarItems>
<CustomRangeContainer>
<FormControl
id="type"
name="type"
componentclass="select"
required={true}
defaultValue={type}
onChange={(e: any) => {
setType(e.currentTarget.value);
routerUtils.setParams(navigate, location, {
type: e.currentTarget.value,
});
}}
>
{["all", "income", "outcome"].map((t) => (
<option key={t} value={t}>
{__(t)}
</option>
))}
</FormControl>
<DateControl
value={queryParams.startDate}
required={false}
name="startDate"
onChange={(date: any) => {
routerUtils.setParams(navigate, location, {
startDate: dayjs(date).format("YYYY-MM-DD"),
});
}}
placeholder={"Start date"}
dateFormat={"YYYY-MM-DD"}
/>
<DateControl
value={queryParams.endDate}
required={false}
name="endDate"
placeholder={"End date"}
onChange={(date: any) => {
routerUtils.setParams(navigate, location, {
endDate: dayjs(date).format("YYYY-MM-DD"),
});
}}
dateFormat={"YYYY-MM-DD"}
/>
</CustomRangeContainer>
</BarItems>
);
return (
<>
{!props.showLatest && (
<HeaderContent>
<h3>{headingText}</h3>
{rightActionBar}
</HeaderContent>
)}
<DataWithLoader
data={content}
loading={loading}
count={totalCount}
emptyContent={
<EmptyContent
content={{
title: __("No data found"),
description: __("No transactions found for this period"),
steps: [],
}}
maxItemWidth="360px"
/>
}
/>
{!props.showLatest && <Pagination count={totalCount} />}
</>
);
};
export default List;
``` | /content/code_sandbox/packages/plugin-golomtbank-ui/src/corporateGateway/transactions/components/List.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,016 |
```xml
// Utilities
import { computed } from 'vue'
import { deepEqual, getPropertyFromItem, omit, propsFactory } from '@/util'
// Types
import type { PropType } from 'vue'
import type { InternalItem } from '@/composables/filter'
import type { SelectItemKey } from '@/util'
export interface ListItem<T = any> extends InternalItem<T> {
title: string
props: {
[key: string]: any
title: string
value: any
}
children?: ListItem<T>[]
}
export interface ItemProps {
items: any[]
itemTitle: SelectItemKey
itemValue: SelectItemKey
itemChildren: SelectItemKey
itemProps: SelectItemKey
returnObject: boolean
valueComparator: typeof deepEqual
}
// Composables
export const makeItemsProps = propsFactory({
items: {
type: Array as PropType<ItemProps['items']>,
default: () => ([]),
},
itemTitle: {
type: [String, Array, Function] as PropType<SelectItemKey>,
default: 'title',
},
itemValue: {
type: [String, Array, Function] as PropType<SelectItemKey>,
default: 'value',
},
itemChildren: {
type: [Boolean, String, Array, Function] as PropType<SelectItemKey>,
default: 'children',
},
itemProps: {
type: [Boolean, String, Array, Function] as PropType<SelectItemKey>,
default: 'props',
},
returnObject: Boolean,
valueComparator: {
type: Function as PropType<typeof deepEqual>,
default: deepEqual,
},
}, 'list-items')
export function transformItem (props: Omit<ItemProps, 'items'>, item: any): ListItem {
const title = getPropertyFromItem(item, props.itemTitle, item)
const value = getPropertyFromItem(item, props.itemValue, title)
const children = getPropertyFromItem(item, props.itemChildren)
const itemProps = props.itemProps === true
? typeof item === 'object' && item != null && !Array.isArray(item)
? 'children' in item
? omit(item, ['children'])
: item
: undefined
: getPropertyFromItem(item, props.itemProps)
const _props = {
title,
value,
...itemProps,
}
return {
title: String(_props.title ?? ''),
value: _props.value,
props: _props,
children: Array.isArray(children) ? transformItems(props, children) : undefined,
raw: item,
}
}
export function transformItems (props: Omit<ItemProps, 'items'>, items: ItemProps['items']) {
const array: ListItem[] = []
for (const item of items) {
array.push(transformItem(props, item))
}
return array
}
export function useItems (props: ItemProps) {
const items = computed(() => transformItems(props, props.items))
const hasNullItem = computed(() => items.value.some(item => item.value === null))
function transformIn (value: any[]): ListItem[] {
if (!hasNullItem.value) {
// When the model value is null, return an InternalItem
// based on null only if null is one of the items
value = value.filter(v => v !== null)
}
return value.map(v => {
if (props.returnObject && typeof v === 'string') {
// String model value means value is a custom input value from combobox
// Don't look up existing items if the model value is a string
return transformItem(props, v)
}
return items.value.find(item => props.valueComparator(v, item.value)) || transformItem(props, v)
})
}
function transformOut (value: ListItem[]): any[] {
return props.returnObject
? value.map(({ raw }) => raw)
: value.map(({ value }) => value)
}
return { items, transformIn, transformOut }
}
``` | /content/code_sandbox/packages/vuetify/src/composables/list-items.ts | xml | 2016-09-12T00:39:35 | 2024-08-16T20:06:39 | vuetify | vuetifyjs/vuetify | 39,539 | 873 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="22505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="nhT-TJ-YvX">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="22504"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Activity-->
<scene sceneID="bVi-HG-3eX">
<objects>
<viewController storyboardIdentifier="NCActivity.storyboard" extendedLayoutIncludesOpaqueBars="YES" id="nhT-TJ-YvX" customClass="NCActivity" customModule="Nextcloud" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="vOO-VC-ekK">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="20" sectionFooterHeight="1" translatesAutoresizingMaskIntoConstraints="NO" id="X49-xg-JXO">
<rect key="frame" x="0.0" y="48" width="414" height="848"/>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="tableCell" rowHeight="35" id="ggj-aE-fnh" customClass="NCActivityTableViewCell" customModule="Nextcloud" customModuleProvider="target">
<rect key="frame" x="0.0" y="50" width="414" height="35"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="ggj-aE-fnh" id="i35-U4-bEk">
<rect key="frame" x="0.0" y="0.0" width="414" height="35"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="252" text="Label" lineBreakMode="tailTruncation" numberOfLines="3" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="fcO-YL-MuT">
<rect key="frame" x="100" y="0.0" width="304" height="18"/>
<fontDescription key="fontDescription" name=".AppleSystemUIFont" family=".AppleSystemUIFont" pointSize="15"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<imageView contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="LQ8-cO-794" userLabel="avatar">
<rect key="frame" x="50" y="0.0" width="35" height="35"/>
<constraints>
<constraint firstAttribute="width" constant="35" id="OKz-e8-DzD"/>
<constraint firstAttribute="height" constant="35" id="fwd-J4-5uY"/>
</constraints>
</imageView>
<imageView userInteractionEnabled="NO" alpha="0.59999999999999998" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="xNG-sf-PnA">
<rect key="frame" x="20" y="8" width="20" height="20"/>
<constraints>
<constraint firstAttribute="width" constant="20" id="Lbv-yi-vAh"/>
<constraint firstAttribute="height" constant="20" id="TML-VJ-2i3"/>
</constraints>
</imageView>
</subviews>
<constraints>
<constraint firstAttribute="trailing" secondItem="fcO-YL-MuT" secondAttribute="trailing" constant="10" id="1pG-qk-inI"/>
<constraint firstItem="LQ8-cO-794" firstAttribute="top" secondItem="i35-U4-bEk" secondAttribute="top" id="3fU-rp-D7s"/>
<constraint firstItem="xNG-sf-PnA" firstAttribute="top" secondItem="i35-U4-bEk" secondAttribute="top" constant="8" id="4EB-59-y1Y"/>
<constraint firstItem="xNG-sf-PnA" firstAttribute="leading" secondItem="i35-U4-bEk" secondAttribute="leading" constant="20" id="CRN-18-SeU"/>
<constraint firstItem="fcO-YL-MuT" firstAttribute="leading" secondItem="LQ8-cO-794" secondAttribute="trailing" constant="15" id="am5-CT-0kZ" userLabel="Subject.leading = Icon.trailing + 50"/>
<constraint firstItem="LQ8-cO-794" firstAttribute="leading" secondItem="xNG-sf-PnA" secondAttribute="trailing" constant="10" id="aqp-Wu-9Hk"/>
<constraint firstItem="fcO-YL-MuT" firstAttribute="top" secondItem="i35-U4-bEk" secondAttribute="top" id="faC-by-km5"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="avatar" destination="LQ8-cO-794" id="2PE-uD-pug"/>
<outlet property="icon" destination="xNG-sf-PnA" id="hxb-Vr-oQX"/>
<outlet property="subject" destination="fcO-YL-MuT" id="L4q-rj-l04"/>
<outlet property="subjectLeadingConstraint" destination="am5-CT-0kZ" id="J7c-Hb-2V2"/>
</connections>
</tableViewCell>
</prototypes>
<connections>
<outlet property="dataSource" destination="nhT-TJ-YvX" id="4jS-6C-FKt"/>
<outlet property="delegate" destination="nhT-TJ-YvX" id="ab1-4g-bMH"/>
<outlet property="prefetchDataSource" destination="nhT-TJ-YvX" id="317-AD-uQe"/>
</connections>
</tableView>
</subviews>
<viewLayoutGuide key="safeArea" id="USa-eR-a1s"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="X49-xg-JXO" firstAttribute="trailing" secondItem="USa-eR-a1s" secondAttribute="trailing" id="5we-Fh-GVu"/>
<constraint firstItem="X49-xg-JXO" firstAttribute="top" secondItem="USa-eR-a1s" secondAttribute="top" id="E1U-4Q-6uu"/>
<constraint firstAttribute="bottom" secondItem="X49-xg-JXO" secondAttribute="bottom" id="aHq-g4-dUG"/>
<constraint firstItem="X49-xg-JXO" firstAttribute="leading" secondItem="USa-eR-a1s" secondAttribute="leading" id="pfF-ag-f7x"/>
</constraints>
</view>
<connections>
<outlet property="tableView" destination="X49-xg-JXO" id="GUb-8b-mIS"/>
<outlet property="viewContainerConstraint" destination="E1U-4Q-6uu" id="NpJ-Iz-DtL"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="UOE-pW-DRy" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-330.43478260869568" y="139.28571428571428"/>
</scene>
</scenes>
</document>
``` | /content/code_sandbox/iOSClient/Activity/NCActivity.storyboard | xml | 2016-12-01T11:50:14 | 2024-08-16T18:43:54 | ios | nextcloud/ios | 1,920 | 2,085 |
```xml
// This is Fluent-style icon
import * as React from 'react';
import cx from 'classnames';
import { createSvgIcon } from '../utils/createSvgIcon';
import { iconClassNames } from '../utils/iconClassNames';
export const ImageLibraryIcon = createSvgIcon({
svg: ({ classes }) => (
<svg role="presentation" focusable="false" viewBox="0 0 20 20" className={classes.svg}>
<path
className={cx(iconClassNames.outline, classes.outlinePart)}
d="M16,5.76392 C16.6138,6.31324 17,7.11152 17,8.00002 L17,12.5 C17,14.9853 14.9853,17 12.5,17 L8.00002,17 C7.11152,17 6.31324,16.6138 5.76392,16 L12.5,16 C14.3122,16 15.8027,14.6228 15.982,12.8579 C15.9939,12.7402 16,12.6208 16,12.5 L16,5.76392 Z M12,3 C13.6569,3 15,4.34315 15,6 L15,12 C15,13.6569 13.6569,15 12,15 L6,15 C4.34315,15 3,13.6569 3,12 L3,6 C3,4.34315 4.34315,3 6,3 L12,3 Z M8.3870765,10.3310166 L8.29287,10.4142 L4.98401,13.7231 C5.23214333,13.8696833 5.51469333,13.9642528 5.81663106,13.9917042 L6,14 L12,14 C12.3090833,14 12.6017778,13.9298611 12.8630949,13.8046875 L13.016,13.7231 L9.70708,10.4142 C9.3466,10.0537385 8.77936497,10.0260107 8.3870765,10.3310166 Z M12,4 L6,4 C4.94563773,4 4.08183483,4.81587733 4.00548573,5.85073759 L4,6 L4,12 C4,12.3090833 4.07011111,12.6017778 4.1953044,12.8630949 L4.27691,13.016 L7.58576,9.70712 C8.32570211,8.96718737 9.50118637,8.92824355 10.2869835,9.59028853 L10.4142,9.70712 L13.7231,13.016 C13.8696833,12.7678333 13.9642528,12.4852917 13.9917042,12.1833634 L14,12 L14,6 C14,4.94563773 13.18415,4.08183483 12.1492661,4.00548573 L12,4 Z M11.5,5.5 C12.0523,5.5 12.5,5.94772 12.5,6.5 C12.5,7.05228 12.0523,7.5 11.5,7.5 C10.9477,7.5 10.5,7.05228 10.5,6.5 C10.5,5.94772 10.9477,5.5 11.5,5.5 Z"
/>
<path
className={cx(iconClassNames.filled, classes.filledPart)}
d="M16,5.76392 C16.5665846,6.27098462 16.9392379,6.99018083 16.9932166,7.79665533 L17,8.00002 L17,12.5 C17,14.9142914 15.0987811,16.8844901 12.7118372,16.9951021 L12.5,17 L8.00002,17 C7.17986615,17 6.43658615,16.6709302 5.89503331,16.1375337 L5.76392,16 L12.5,16 C14.3122,16 15.8027,14.6228 15.982,12.8579 L15.9954625,12.6801125 L16,12.5 L16,5.76392 Z M9.6128735,10.3310166 L9.70708,10.4142 L13.7382,14.4454 C13.3022889,14.7558 12.7798593,14.9525802 12.2141045,14.9924771 L12,15 L6,15 C5.42407111,15 4.88605235,14.8377086 4.42917224,14.5563896 L4.26173,14.4454 L8.29287,10.4142 C8.65335,10.0537385 9.22058503,10.0260107 9.6128735,10.3310166 Z M12,3 C13.597725,3 14.903664,4.24892392 14.9949075,5.82372764 L15,6 L15,12 C15,12.5759111 14.8377086,13.1139753 14.5563896,13.5708587 L14.4454,13.7383 L10.4142,9.70712 C9.67424842,8.96718737 8.49876366,8.92824355 7.71297498,9.59028853 L7.58576,9.70712 L3.55462,13.7383 C3.24419333,13.3023889 3.04741802,12.7798802 3.00752261,12.214108 L3,12 L3,6 C3,4.40232321 4.24892392,3.09633941 5.82372764,3.00509271 L6,3 L12,3 Z M11.5,5.5 C10.9477,5.5 10.5,5.94772 10.5,6.5 C10.5,7.05228 10.9477,7.5 11.5,7.5 C12.0523,7.5 12.5,7.05228 12.5,6.5 C12.5,5.94772 12.0523,5.5 11.5,5.5 Z"
/>
</svg>
),
displayName: 'ImageLibraryIcon',
});
``` | /content/code_sandbox/packages/fluentui/react-icons-northstar/src/components/ImageLibraryIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 1,620 |
```xml
import Constants, { ExecutionEnvironment } from 'expo-constants';
import * as Linking from 'expo-linking';
import { Platform } from 'expo-modules-core';
export class SessionUrlProvider {
private static readonly BASE_URL = `path_to_url`;
private static readonly SESSION_PATH = 'expo-auth-session';
getDefaultReturnUrl(
urlPath?: string,
options?: Omit<Linking.CreateURLOptions, 'queryParams'>
): string {
const queryParams = SessionUrlProvider.getHostAddressQueryParams();
let path = SessionUrlProvider.SESSION_PATH;
if (urlPath) {
path = [path, SessionUrlProvider.removeLeadingSlash(urlPath)].filter(Boolean).join('/');
}
return Linking.createURL(path, {
// The redirect URL doesn't matter for the proxy as long as it's valid, so silence warnings if needed.
scheme: options?.scheme ?? Linking.resolveScheme({ isSilent: true }),
queryParams,
isTripleSlashed: options?.isTripleSlashed,
});
}
getStartUrl(authUrl: string, returnUrl: string, projectNameForProxy: string | undefined): string {
if (Platform.OS === 'web' && !Platform.isDOMAvailable) {
// Return nothing in SSR envs
return '';
}
const queryString = new URLSearchParams({
authUrl,
returnUrl,
});
return `${this.getRedirectUrl({ projectNameForProxy })}/start?${queryString}`;
}
getRedirectUrl(options: { projectNameForProxy?: string; urlPath?: string }): string {
if (Platform.OS === 'web') {
if (Platform.isDOMAvailable) {
return [window.location.origin, options.urlPath].filter(Boolean).join('/');
} else {
// Return nothing in SSR envs
return '';
}
}
const legacyExpoProjectFullName =
options.projectNameForProxy || Constants.expoConfig?.originalFullName;
if (!legacyExpoProjectFullName) {
let nextSteps = '';
if (__DEV__) {
if (Constants.executionEnvironment === ExecutionEnvironment.Bare) {
nextSteps =
' Please ensure you have the latest version of expo-constants installed and rebuild your native app. You can verify that originalFullName is defined by running `expo config --type public` and inspecting the output.';
} else if (Constants.executionEnvironment === ExecutionEnvironment.StoreClient) {
nextSteps =
' Please report this as a bug with the contents of `expo config --type public`.';
}
}
if (Constants.manifest2) {
nextSteps =
' Prefer AuthRequest in combination with an Expo Development Client build of your application.' +
' To continue using the AuthSession proxy, specify the project full name (@owner/slug) using the projectNameForProxy option.';
}
throw new Error(
'Cannot use the AuthSession proxy because the project full name is not defined.' + nextSteps
);
}
const redirectUrl = `${SessionUrlProvider.BASE_URL}/${legacyExpoProjectFullName}`;
if (__DEV__) {
SessionUrlProvider.warnIfAnonymous(legacyExpoProjectFullName, redirectUrl);
// TODO: Verify with the dev server that the manifest is up to date.
}
return redirectUrl;
}
private static getHostAddressQueryParams(): Record<string, string> | undefined {
let hostUri: string | undefined = Constants.expoConfig?.hostUri;
if (
!hostUri &&
(ExecutionEnvironment.StoreClient === Constants.executionEnvironment ||
Linking.resolveScheme({}))
) {
if (!Constants.linkingUri) {
hostUri = '';
} else {
// we're probably not using up-to-date xdl, so just fake it for now
// we have to remove the /--/ on the end since this will be inserted again later
hostUri = SessionUrlProvider.removeScheme(Constants.linkingUri).replace(/\/--(\/.*)?$/, '');
}
}
if (!hostUri) {
return undefined;
}
const uriParts = hostUri?.split('?');
try {
return Object.fromEntries(
// @ts-ignore: [Symbol.iterator] is indeed, available on every platform.
new URLSearchParams(uriParts?.[1])
);
} catch {}
return undefined;
}
private static warnIfAnonymous(id, url): void {
if (id.startsWith('@anonymous/')) {
console.warn(
`You are not currently signed in to Expo on your development machine. As a result, the redirect URL for AuthSession will be "${url}". If you are using an OAuth provider that requires adding redirect URLs to an allow list, we recommend that you do not add this URL -- instead, you should sign in to Expo to acquire a unique redirect URL. Additionally, if you do decide to publish this app using Expo, you will need to register an account to do it.`
);
}
}
private static removeScheme(url: string) {
return url.replace(/^[a-zA-Z0-9+.-]+:\/\//, '');
}
private static removeLeadingSlash(url: string) {
return url.replace(/^\//, '');
}
}
export default new SessionUrlProvider();
``` | /content/code_sandbox/packages/expo-auth-session/src/SessionUrlProvider.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 1,103 |
```xml
import { Component, OnInit } from "@angular/core";
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
import { NoItemsModule, SearchModule } from "@bitwarden/components";
import { HeaderModule } from "../../layouts/header/header.module";
import { SharedModule } from "../../shared/shared.module";
@Component({
selector: "app-sm-landing",
standalone: true,
imports: [SharedModule, SearchModule, NoItemsModule, HeaderModule],
templateUrl: "sm-landing.component.html",
})
export class SMLandingComponent implements OnInit {
tryItNowUrl: string;
learnMoreUrl: string = "path_to_url";
imageSrc: string = "../images/sm.webp";
showSecretsManagerInformation: boolean = true;
showGiveMembersAccessInstructions: boolean = false;
constructor(private organizationService: OrganizationService) {}
async ngOnInit() {
const enabledOrganizations = (await this.organizationService.getAll()).filter((e) => e.enabled);
if (enabledOrganizations.length > 0) {
this.handleEnabledOrganizations(enabledOrganizations);
} else {
// Person is not part of any orgs they need to be in an organization in order to use SM
this.tryItNowUrl = "/create-organization";
}
}
private handleEnabledOrganizations(enabledOrganizations: Organization[]) {
// People get to this page because SM (Secrets Manager) isn't enabled for them (or the Organization they are a part of)
// 1 - SM is enabled for the Organization but not that user
//1a - person is Admin+ (Admin or higher) and just needs instructions on how to enable it for themselves
//1b - person is beneath admin status and needs to request SM access from Administrators/Owners
// 2 - SM is not enabled for the organization yet
//2a - person is Owner/Provider - Direct them to the subscription/billing page
//2b - person is Admin - Direct them to request access page where an email is sent to owner/admins
//2c - person is user - Direct them to request access page where an email is sent to owner/admins
// We use useSecretsManager because we want to get the first org the person is a part of where SM is enabled but they don't have access enabled yet
const adminPlusNeedsInstructionsToEnableSM = enabledOrganizations.find(
(o) => o.isAdmin && o.useSecretsManager,
);
const ownerNeedsToEnableSM = enabledOrganizations.find(
(o) => o.isOwner && !o.useSecretsManager,
);
// 1a If Organization has SM Enabled, but this logged in person does not have it enabled, but they are admin+ then give them instructions to enable.
if (adminPlusNeedsInstructionsToEnableSM != undefined) {
this.showHowToEnableSMForMembers(adminPlusNeedsInstructionsToEnableSM.id);
}
// 2a Owners can enable SM in the subscription area of Admin Console.
else if (ownerNeedsToEnableSM != undefined) {
this.tryItNowUrl = `/organizations/${ownerNeedsToEnableSM.id}/billing/subscription`;
}
// 1b and 2b 2c, they must be lower than an Owner, and they need access, or want their org to have access to SM.
else {
this.tryItNowUrl = "/request-sm-access";
}
}
private showHowToEnableSMForMembers(orgId: string) {
this.showGiveMembersAccessInstructions = true;
this.showSecretsManagerInformation = false;
this.learnMoreUrl =
"path_to_url#give-members-access";
this.imageSrc = "../images/sm-give-access.png";
this.tryItNowUrl = `/organizations/${orgId}/members`;
}
}
``` | /content/code_sandbox/apps/web/src/app/secrets-manager/secrets-manager-landing/sm-landing.component.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 844 |
```xml
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import type { FlightSegmentPath } from '../../../server/app-render/types'
import { createRouterCacheKey } from './create-router-cache-key'
/**
* Fill cache up to the end of the flightSegmentPath, invalidating anything below it.
*/
export function invalidateCacheBelowFlightSegmentPath(
newCache: CacheNode,
existingCache: CacheNode,
flightSegmentPath: FlightSegmentPath
): void {
const isLastEntry = flightSegmentPath.length <= 2
const [parallelRouteKey, segment] = flightSegmentPath
const cacheKey = createRouterCacheKey(segment)
const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey)
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap)
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
}
// In case of last entry don't copy further down.
if (isLastEntry) {
childSegmentMap.delete(cacheKey)
return
}
const existingChildCacheNode = existingChildSegmentMap.get(cacheKey)
let childCacheNode = childSegmentMap.get(cacheKey)
if (!childCacheNode || !existingChildCacheNode) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
lazyData: childCacheNode.lazyData,
rsc: childCacheNode.rsc,
prefetchRsc: childCacheNode.prefetchRsc,
head: childCacheNode.head,
prefetchHead: childCacheNode.prefetchHead,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
} as CacheNode
childSegmentMap.set(cacheKey, childCacheNode)
}
invalidateCacheBelowFlightSegmentPath(
childCacheNode,
existingChildCacheNode,
flightSegmentPath.slice(2)
)
}
``` | /content/code_sandbox/packages/next/src/client/components/router-reducer/invalidate-cache-below-flight-segmentpath.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 512 |
```xml
import * as React from 'react';
import type { IStyle, ITheme } from '../../Styling';
import type { IPositioningContainerProps } from './PositioningContainer/PositioningContainer.types';
import type { IRefObject, IStyleFunctionOrObject } from '../../Utilities';
import type { ITeachingBubble } from '../../TeachingBubble';
import type { Target } from '@fluentui/react-hooks';
/**
* {@docCategory Coachmark}
*/
export interface ICoachmark {
/**
* Forces the Coachmark to dismiss
*/
dismiss?: (ev?: Event | React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>) => void;
}
/**
* Coachmark component props
* {@docCategory Coachmark}
*/
export interface ICoachmarkProps extends React.RefAttributes<HTMLDivElement> {
/**
* Optional callback to access the `ICoachmark` interface. Use this instead of `ref` for accessing
* the public methods and properties of the component.
*/
componentRef?: IRefObject<ICoachmark>;
/**
* If provided, additional class name to provide on the root element.
*/
className?: string;
/**
* Call to provide customized styling that will layer on top of the variant rules
*/
styles?: IStyleFunctionOrObject<ICoachmarkStyleProps, ICoachmarkStyles>;
/**
* The target that the Coachmark should try to position itself based on.
*/
target: Target;
/**
* Props to pass to the PositioningContainer component. Specify the `directionalHint` to indicate
* on which edge the Coachmark/TeachingBubble should be positioned.
* @defaultvalue `{ directionalHint: DirectionalHint.bottomAutoEdge }`
*/
positioningContainerProps?: IPositioningContainerProps;
/**
* Whether or not to force the Coachmark/TeachingBubble content to fit within the window bounds.
* @defaultvalue true
*/
isPositionForced?: boolean;
/**
* The starting collapsed state for the Coachmark.
* @defaultvalue true
* @deprecated Use `isCollapsed` instead.
*/
collapsed?: boolean;
/**
* The starting collapsed state for the Coachmark.
* @defaultvalue true
*/
isCollapsed?: boolean;
/**
* The distance in pixels the mouse is located before opening up the Coachmark.
* @defaultvalue 10
*/
mouseProximityOffset?: number;
/**
* Callback when the opening animation begins.
*/
onAnimationOpenStart?: () => void;
/**
* Callback when the opening animation completes.
*/
onAnimationOpenEnd?: () => void;
/**
* @deprecated No longer used.
*/
beakWidth?: number;
/**
* @deprecated No longer used.
*/
beakHeight?: number;
/**
* Delay before allowing mouse movements to open the Coachmark.
* @defaultvalue 3600
*/
delayBeforeMouseOpen?: number;
/**
* Delay in milliseconds before Coachmark animation appears.
* @defaultvalue 0
*/
delayBeforeCoachmarkAnimation?: number;
/**
* Callback to run when the mouse moves.
*/
onMouseMove?: (e: MouseEvent) => void;
/**
* @deprecated No longer used.
*/
width?: number;
/**
* @deprecated No longer used.
*/
height?: number;
/**
* Color of the Coachmark/TeachingBubble.
*/
color?: string;
/**
* Beacon color one.
*/
beaconColorOne?: string;
/**
* Beacon color two.
*/
beaconColorTwo?: string;
/**
* Text for screen reader to announce when Coachmark is displayed
*/
ariaAlertText?: string;
/**
* @deprecated Not used. Coachmark uses `focusFirstChild` utility instead to focus on TeachingBubbleContent.
*/
teachingBubbleRef?: ITeachingBubble;
/**
* ID used for the internal element which contains label text for the Coachmark
* (don't render an element with this ID yourself).
*/
ariaLabelledBy?: string;
/**
* ID used for the internal element which contains description text for the Coachmark
* (don't render an element with this ID yourself).
*/
ariaDescribedBy?: string;
/**
* Defines the text content for the `ariaLabelledBy` element.
* Not used unless `ariaLabelledBy` is also provided.
*/
ariaLabelledByText?: string;
/**
* Defines the text content for the `ariaDescribedBy` element
* Not used unless `ariaDescribedBy` is also provided.
*/
ariaDescribedByText?: string;
/**
* If true then the Coachmark will not dismiss when it loses focus
* @defaultvalue false
*/
preventDismissOnLostFocus?: boolean;
/**
* If true then the Coachmark beak (arrow pointing towards target) will always be visible as long as
* Coachmark is visible
* @defaultvalue false
*/
persistentBeak?: boolean;
/**
* If true then focus will not be set to the Coachmark when it mounts. Useful in cases where focus on coachmark
* is causing other components in page to dismiss upon losing focus.
* @defaultvalue false
*/
preventFocusOnMount?: boolean;
/**
* Callback when the Coachmark tries to close.
*/
onDismiss?: (ev?: Event | React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>) => void;
/**
* Theme provided by higher order component.
*/
theme?: ITheme;
/**
* Child nodes to render inside the Coachmark dialog
*/
children?: React.ReactNode;
}
/**
* The props needed to construct styles.
* {@docCategory Coachmark}
*/
export interface ICoachmarkStyleProps {
/**
* ClassName to provide on the root style area.
*/
className?: string;
/**
* Current theme.
*/
theme?: ITheme;
/**
* Is the Coachmark collapsed.
* @deprecated Use `isCollapsed` instead.
*/
collapsed?: boolean;
/**
* Is the Coachmark collapsed
*/
isCollapsed: boolean;
/**
* Is the component taking measurements
*/
isMeasuring: boolean;
/**
* The height measured before the component has been mounted in pixels
*/
entityHostHeight?: string;
/**
* The width measured in pixels
*/
entityHostWidth?: string;
/**
* Width of the coachmark
*/
width?: string;
/**
* Height of the coachmark
*/
height?: string;
/**
* Color
*/
color?: string;
/**
* Beacon color one
*/
beaconColorOne?: string;
/**
* Beacon color two
*/
beaconColorTwo?: string;
/**
* Transform origin for teaching bubble content
*/
transformOrigin?: string;
/**
* Delay time for the animation to start
*/
delayBeforeCoachmarkAnimation?: string;
}
/**
* Represents the stylable areas of the control.
* {@docCategory Coachmark}
*/
export interface ICoachmarkStyles {
/**
* Style for the root element in the default enabled/unchecked state.
*/
root?: IStyle;
/**
* The pulsing beacon that animates when the Coachmark is collapsed.
*/
pulsingBeacon?: IStyle;
/**
* The layer, or div, that the translate animation will be applied to.
*/
translateAnimationContainer?: IStyle;
/**
* The layer the Scale animation will be applied to.
*/
scaleAnimationLayer?: IStyle;
/**
* The layer the Rotate animation will be applied to.
*/
rotateAnimationLayer?: IStyle;
/**
* The layer that content/components/elements will be hosted in.
*/
entityHost?: IStyle;
/**
* The inner layer that components will be hosted in
* (primary purpose is scaling the layer down while the Coachmark collapses)
*/
entityInnerHost: IStyle;
/**
* The layer that directly contains the TeachingBubbleContent
*/
childrenContainer: IStyle;
/**
* The styles applied when the Coachmark has collapsed.
*/
collapsed?: IStyle;
/**
* The styles applied to the ARIA attribute container
*/
ariaContainer?: IStyle;
}
/**
* @deprecated No longer used.
* {@docCategory Coachmark}
*/
export type ICoachmarkTypes = ICoachmarkProps;
``` | /content/code_sandbox/packages/react/src/components/Coachmark/Coachmark.types.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 1,859 |
```xml
<?xml version="1.0" encoding="utf-8"?>
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. -->
<!-- The toolbar containing the URL bar, back button, and NTP button.
-->
<merge xmlns:android="path_to_url"
xmlns:chrome="path_to_url">
<org.chromium.chrome.browser.widget.newtab.NewTabButton
android:id="@+id/new_tab_button"
style="@style/ToolbarButton"
android:layout_width="wrap_content"
android:layout_gravity="start|top"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:visibility="invisible"
android:background="?attr/selectableItemBackground"
android:contentDescription="@string/accessibility_toolbar_btn_new_tab" />
<org.chromium.chrome.browser.toolbar.HomePageButton
android:id="@+id/home_button"
style="@style/ToolbarButton"
android:src="@drawable/btn_toolbar_home"
android:contentDescription="@string/accessibility_toolbar_btn_home"
android:visibility="gone" />
<org.chromium.chrome.browser.omnibox.LocationBarPhone
android:id="@+id/location_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="top" />
<LinearLayout android:id="@+id/toolbar_buttons"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|end" >
<Space
android:layout_width="4dp"
android:layout_height="match_parent" />
<ImageButton android:id="@+id/tab_switcher_button"
style="@style/ToolbarButton"
android:layout_gravity="top"
android:contentDescription="@string/accessibility_toolbar_btn_tabswitcher_toggle_default" />
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/menu_button_wrapper" >
<org.chromium.chrome.browser.widget.TintedImageButton
android:id="@+id/menu_button"
style="@style/ToolbarMenuButtonPhone"
android:src="@drawable/btn_menu"
android:contentDescription="@string/accessibility_toolbar_btn_menu" />
<ImageView
android:id="@+id/menu_badge"
style="@style/ToolbarMenuButtonPhone"
android:src="@drawable/badge_update_dark"
android:contentDescription="@null"
android:importantForAccessibility="no"
android:visibility="invisible" />
</FrameLayout>
</LinearLayout>
<org.chromium.chrome.browser.widget.ToolbarProgressBar
android:id="@+id/progress"
android:layout_width="match_parent"
android:layout_height="@dimen/toolbar_progress_bar_height"
chrome:progressBarColor="@color/progress_bar_foreground"
chrome:backgroundColor="@color/progress_bar_background" />
</merge>
``` | /content/code_sandbox/libraries_res/chrome_res/src/main/res/layout/toolbar_phone_common.xml | xml | 2016-07-04T07:28:36 | 2024-08-15T05:20:42 | AndroidChromium | JackyAndroid/AndroidChromium | 3,090 | 642 |
```xml
import * as React from 'react';
import createSvgIcon from '../utils/createSvgIcon';
const CityNext2Icon = createSvgIcon({
svg: ({ classes }) => (
<svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false">
<path d="M512 1024H384V768h128v256zm256 0H640V768h128v256zm256 0H896V768h128v256zm-512 384H384v-256h128v256zm256 0H640v-256h128v256zm256 0H896v-256h128v256zm384-640q106 0 199 40t163 109 110 163 40 your_sha256_hashyour_sha256_hashzM640 256h128V128H640v128zM384 512h640V384H384v128zm768 128H256v1280h256v-384h384v384h256V640zm256 512h256v128h-256v-128zm0 256h256v128h-256v-128zm0 256h256v128h-256v-128zm0 256h256v128h-256v-128z" />
</svg>
),
displayName: 'CityNext2Icon',
});
export default CityNext2Icon;
``` | /content/code_sandbox/packages/react-icons-mdl2/src/components/CityNext2Icon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 309 |
```xml
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
import { print } from 'graphql';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { parseSelectionSet } from '@graphql-tools/utils';
import { stitchingDirectives } from '../src/index.js';
describe('type merging directives', () => {
const { allStitchingDirectivesTypeDefs, stitchingDirectivesTransformer } = stitchingDirectives();
test('adds type selection sets', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): User @merge
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
expect(transformedSubschemaConfig.merge?.['User'].selectionSet).toEqual(
print(parseSelectionSet('{ id }')),
);
expect(transformedSubschemaConfig.merge?.['User'].fieldName).toEqual('_user');
});
test('adds type selection sets when returns union', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
union Entity = User
type Query {
_entity(key: _Key): Entity @merge
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
expect(transformedSubschemaConfig.merge?.['User'].selectionSet).toEqual(
print(parseSelectionSet('{ id }')),
);
expect(transformedSubschemaConfig.merge?.['User'].fieldName).toEqual('_entity');
});
test('adds type selection sets when returns interface', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
interface Entity {
id: ID
}
type Query {
_entity(key: _Key): Entity @merge
}
type User implements Entity @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
expect(transformedSubschemaConfig.merge?.['User'].selectionSet).toEqual(
print(parseSelectionSet('{ id }')),
);
expect(transformedSubschemaConfig.merge?.['User'].fieldName).toEqual('_entity');
});
test('adds type selection sets when returns list', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type User @key(selectionSet: "{ relations { id } }") {
relationIds: [String!]!
}
type Query {
_user(key: _Key): User @merge
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult = {
relations: [
{
id: 2,
},
{
id: 3,
},
],
};
const args = argsFn(originalResult);
expect(args).toEqual({
key: {
relations: [
{
id: 2,
},
{
id: 3,
},
],
},
});
});
test('adds type selection sets when returns multi-layered list', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type User @key(selectionSet: "{ relationSets { id } }") {
relationIds: [[String!]!]!
}
type Query {
_user(key: _Key): User @merge
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult = {
relationSets: [
[
{
id: 2,
},
{
id: 3,
},
],
[
{
id: 4,
},
],
],
};
const args = argsFn(originalResult);
expect(args).toEqual({
key: {
relationSets: [
[
{
id: 2,
},
{
id: 3,
},
],
[
{
id: 4,
},
],
],
},
});
});
test('adds type selection sets when returns null', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type User @key(selectionSet: "{ nestedField { id } }") {
nestedId: [String!]!
}
type Query {
_user(key: _Key): User @merge
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult: { nestedField: null } = {
nestedField: null,
};
const args = argsFn(originalResult);
expect(args).toEqual({
key: {
nestedField: null,
},
});
});
test('adds computed selection sets', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): User @merge
}
type User {
id: ID
name: String @computed(selectionSet: "{ id }")
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
expect(transformedSubschemaConfig.merge?.['User']?.fields?.['name']?.selectionSet).toEqual(
print(parseSelectionSet('{ id }')),
);
expect(transformedSubschemaConfig.merge?.['User']?.fields?.['name']?.computed).toEqual(true);
expect(transformedSubschemaConfig.merge?.['User'].fieldName).toEqual('_user');
});
test('adds args function when used without arguments', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): User @merge
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const args = argsFn(originalResult);
expect(args).toEqual({
key: {
id: '5',
},
});
});
test('adds args function when used with argsExpr argument using an unqualified key', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): User @merge(argsExpr: "key: $key")
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const args = argsFn(originalResult);
expect(args).toEqual({
key: {
id: '5',
},
});
});
test('adds args function when used with argsExpr argument using a fully qualified key', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): User @merge(argsExpr: "key: { id: $key.id }")
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const args = argsFn(originalResult);
expect(args).toEqual({
key: {
id: '5',
},
});
});
test('adds args function when used with keyArg argument', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): User @merge(keyArg: "key")
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const args = argsFn(originalResult);
expect(args).toEqual({
key: {
id: '5',
},
});
});
test('adds args function when used with nested keyArg argument', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
input UserInput {
key: _Key
}
type Query {
_user(input: UserInput, scope: String): User
@merge(
keyArg: "input.key"
additionalArgs: """
scope: "full"
"""
)
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const args = argsFn(originalResult);
expect(args).toEqual({
input: {
key: {
id: '5',
},
},
scope: 'full',
});
});
test('adds args function when used with keyArg and additionalArgs arguments', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key, scope: String): User
@merge(
keyArg: "key"
additionalArgs: """
scope: "full"
"""
)
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const args = argsFn(originalResult);
expect(args).toEqual({
key: {
id: '5',
},
scope: 'full',
});
});
test('adds key and args function when @merge is used with keyField argument', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
type Query {
_user(id: ID): User @merge(keyField: "id")
}
type User {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
expect(transformedSubschemaConfig.merge?.['User']?.selectionSet).toEqual(`{\n id\n}`);
const argsFn = transformedSubschemaConfig.merge?.['User']?.args;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const args = argsFn?.(originalResult);
expect(args).toEqual({
id: '5',
});
});
test('adds args function when used with key argument', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): User @merge(key: ["id", "outer.inner.firstName:name.firstName"])
}
type User @key(selectionSet: "{ id name { firstName } }") {
id: ID
email: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const argsFn = transformedSubschemaConfig.merge?.['User'].args!;
const originalResult = {
id: '5',
name: {
firstName: 'Tester',
},
};
const args = argsFn(originalResult);
expect(args).toEqual({
key: {
id: '5',
outer: {
inner: {
firstName: 'Tester',
},
},
},
});
});
test('adds key and argsFromKeys functions when used without arguments', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): [User] @merge
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const keyFn = transformedSubschemaConfig.merge?.['User'].key!;
const argsFromKeysFn = transformedSubschemaConfig.merge?.['User'].argsFromKeys!;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const key = keyFn(originalResult);
const args = argsFromKeysFn([key]);
expect(key).toEqual({
id: '5',
});
expect(args).toEqual({
key: [
{
id: '5',
},
],
});
});
test('adds key and argsFromKeys functions when used without arguments and returns union', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
union Entity = User
type Query {
_entity(key: _Key): [Entity] @merge
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const keyFn = transformedSubschemaConfig.merge?.['User'].key!;
const argsFromKeysFn = transformedSubschemaConfig.merge?.['User'].argsFromKeys!;
const originalResult = {
__typename: 'User',
id: '5',
email: 'email@email.com',
};
const key = keyFn(originalResult);
const args = argsFromKeysFn([key]);
expect(key).toEqual({
__typename: 'User',
id: '5',
});
expect(args).toEqual({
key: [
{
__typename: 'User',
id: '5',
},
],
});
});
test('adds key and argsFromKeys functions when used without arguments and returns interface', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
interface Entity {
id: ID
}
type Query {
_entity(key: _Key): [Entity] @merge
}
type User implements Entity @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const keyFn = transformedSubschemaConfig.merge?.['User'].key!;
const argsFromKeysFn = transformedSubschemaConfig.merge?.['User'].argsFromKeys!;
const originalResult = {
__typename: 'User',
id: '5',
email: 'email@email.com',
};
const key = keyFn(originalResult);
const args = argsFromKeysFn([key]);
expect(key).toEqual({
__typename: 'User',
id: '5',
});
expect(args).toEqual({
key: [
{
__typename: 'User',
id: '5',
},
],
});
});
test('adds key and argsFromKeys functions with argsExpr argument using an unqualified key', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): [User] @merge(argsExpr: "key: [[$key]]")
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const keyFn = transformedSubschemaConfig.merge?.['User'].key!;
const argsFromKeysFn = transformedSubschemaConfig.merge?.['User'].argsFromKeys!;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const key = keyFn(originalResult);
const args = argsFromKeysFn([key]);
expect(key).toEqual({
id: '5',
});
expect(args).toEqual({
key: [
{
id: '5',
},
],
});
});
test('adds key and argsFromKeys functions with argsExpr argument using a fully qualified key', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
scalar _Key
type Query {
_user(key: _Key): [User] @merge(argsExpr: "key: [[{ id: $key.id }]]")
}
type User @key(selectionSet: "{ id }") {
id: ID
name: String
}
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = {
schema,
};
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
const keyFn = transformedSubschemaConfig.merge?.['User'].key!;
const argsFromKeysFn = transformedSubschemaConfig.merge?.['User'].argsFromKeys!;
const originalResult = {
id: '5',
email: 'email@email.com',
};
const key = keyFn(originalResult);
const args = argsFromKeysFn([key]);
expect(key).toEqual({
id: '5',
});
expect(args).toEqual({
key: [
{
id: '5',
},
],
});
});
test('applies canonical merge attributions', () => {
const typeDefs = /* GraphQL */ `
${allStitchingDirectivesTypeDefs}
type User implements IUser @canonical {
id: ID
name: String @canonical
}
interface IUser @canonical {
id: ID
name: String @canonical
}
input UserInput @canonical {
id: ID
name: String @canonical
}
enum UserEnum @canonical {
VALUE
}
union UserUnion @canonical = User
scalar Key @canonical
`;
const schema = makeExecutableSchema({ typeDefs });
const subschemaConfig = { schema };
const transformedSubschemaConfig = stitchingDirectivesTransformer(subschemaConfig);
expect(transformedSubschemaConfig.merge).toEqual({
User: {
canonical: true,
fields: {
name: { canonical: true },
},
},
IUser: {
canonical: true,
fields: {
name: { canonical: true },
},
},
UserInput: {
canonical: true,
fields: {
name: { canonical: true },
},
},
UserEnum: {
canonical: true,
},
UserUnion: {
canonical: true,
},
Key: {
canonical: true,
},
});
});
});
``` | /content/code_sandbox/packages/stitching-directives/tests/stitchingDirectivesTransformer.test.ts | xml | 2016-03-22T00:14:38 | 2024-08-16T02:02:06 | graphql-tools | ardatan/graphql-tools | 5,331 | 4,875 |
```xml
import { useCallback } from "react"
import { cartAtom } from "@/store/cart.store"
import { paymentTypesAtom } from "@/store/config.store"
import {
cashAmountAtom,
mobileAmountAtom,
orderTotalAmountAtom,
paidAmountsAtom,
} from "@/store/order.store"
import { useAtomValue } from "jotai"
import { cn, formatNum, getSumsOfAmount } from "@/lib/utils"
const Amount = () => {
const cash = useAtomValue(cashAmountAtom)
const mobile = useAtomValue(mobileAmountAtom)
const total = useAtomValue(orderTotalAmountAtom)
const items = useAtomValue(cartAtom)
const paymentTypes = useAtomValue(paymentTypesAtom)
const paidAmounts = useAtomValue(paidAmountsAtom)
const discountAmounts = useCallback(() => {
return (items || []).reduce(
(totalDiscount, item) => totalDiscount + (item.discountAmount || 0),
0
)
}, [items])
return (
<div className="font-base text-[11px]">
<div className="flex items-center justify-between border-t font-semibold">
<p> </p>
<p>{formatNum(total)}</p>
</div>
<Field text="" val={discountAmounts()} />
<Field text="" val={cash} />
<Field text="" val={mobile} />
{Object.values(getSumsOfAmount(paidAmounts, paymentTypes)).map(
(i: any) => (
<Field text={i.title} val={i.value} key={i.title} />
)
)}
</div>
)
}
const Field = ({
text,
val,
className,
}: {
text: string
val: number
className?: string
}) => {
if (!val) {
return null
}
return (
<div className={cn("flex items-center justify-between", className)}>
<p>{text}</p>
<p>{formatNum(val)}</p>
</div>
)
}
export default Amount
``` | /content/code_sandbox/pos/app/reciept/components/Amount.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"?>
<menu xmlns:android="path_to_url"
xmlns:app="path_to_url">
<item
android:id="@+id/action_like"
android:icon="@drawable/selector_toolbar_like"
android:title="@string/action_like"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_share"
android:icon="@mipmap/ic_toolbar_share"
android:title="@string/action_share"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_save"
android:icon="@mipmap/ic_toolbar_save"
android:title="@string/action_save"
app:showAsAction="ifRoom" />
</menu>
``` | /content/code_sandbox/app/src/main/res/menu/girl_menu.xml | xml | 2016-08-07T14:56:56 | 2024-08-13T01:11:07 | GeekNews | codeestX/GeekNews | 3,498 | 166 |
```xml
import type { PDFDocumentProxy } from 'pdfjs-dist';
export default {
_pdfInfo: {
fingerprint: 'a62067476e69734bb8eb60122615dfbf',
numPages: 4,
},
getDestination: () => new Promise((_resolve, reject) => reject(new Error())),
getOutline: () => new Promise((_resolve, reject) => reject(new Error())),
getPage: () => new Promise((_resolve, reject) => reject(new Error())),
numPages: 4,
} as unknown as PDFDocumentProxy;
``` | /content/code_sandbox/__mocks__/_failing_pdf.ts | xml | 2016-08-01T13:46:02 | 2024-08-16T16:54:44 | react-pdf | wojtekmaj/react-pdf | 9,159 | 120 |
```xml
import '@testing-library/jest-dom/extend-expect';
``` | /content/code_sandbox/scripts/setupMatchers.ts | xml | 2016-05-10T13:08:50 | 2024-08-13T11:27:18 | uniforms | vazco/uniforms | 1,934 | 13 |
```xml
import clsx from 'clsx';
export type BadgeVariant =
| 'danger'
| 'info'
| 'primary'
| 'success'
| 'warning';
type Props = Readonly<{
endAddOn?: React.ComponentType<React.ComponentProps<'svg'>>;
label: string;
startAddOn?: React.ComponentType<React.ComponentProps<'svg'>>;
variant: BadgeVariant;
}>;
const classes: Record<
BadgeVariant,
Readonly<{
backgroundClass: string;
textClass: string;
}>
> = {
danger: {
backgroundClass: 'bg-danger-100',
textClass: 'text-danger-800',
},
info: {
backgroundClass: 'bg-info-100',
textClass: 'text-info-800',
},
primary: {
backgroundClass: 'bg-primary-100',
textClass: 'text-primary-800',
},
success: {
backgroundClass: 'bg-success-100',
textClass: 'text-success-800',
},
warning: {
backgroundClass: 'bg-warning-100',
textClass: 'text-warning-800',
},
};
export default function Badge({
endAddOn: EndAddOn,
label,
startAddOn: StartAddOn,
variant,
}: Props) {
const { backgroundClass, textClass } = classes[variant];
return (
<span
className={clsx(
'inline-flex items-center rounded-full px-3 py-1 text-xs font-medium',
backgroundClass,
textClass,
)}>
{StartAddOn && <StartAddOn aria-hidden="true" className="mr-1 h-4 w-4" />}
<span>{label}</span>
{EndAddOn && <EndAddOn aria-hidden="true" className="ml-1 h-4 w-4" />}
</span>
);
}
``` | /content/code_sandbox/apps/portal/src/ui/Badge/Badge.tsx | xml | 2016-07-05T05:00:48 | 2024-08-16T19:01:19 | tech-interview-handbook | yangshun/tech-interview-handbook | 115,302 | 410 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="about_android">%1$s-Android-sovellus</string>
<string name="about_title">Tietoja</string>
<string name="about_version">versio %1$s</string>
<string name="about_version_with_build">versio %1$s, koontiversio #%2$s</string>
<string name="account_creation_failed">Tilin luonti eponnistui</string>
<string name="account_icon">Tilikuvake</string>
<string name="account_not_found">Tili ei lydy!</string>
<string name="action_edit">Muokkaa</string>
<string name="action_empty_notifications">Hylk kaikki ilmoitukset</string>
<string name="action_empty_trashbin">Tyhjenn roskakori</string>
<string name="action_send_share">Lhet/jaa</string>
<string name="action_switch_grid_view">Ruudukkonkym</string>
<string name="action_switch_list_view">Luettelonkym</string>
<string name="actionbar_calendar_contacts_restore">Palauta yhteystiedot ja kalenteri</string>
<string name="actionbar_mkdir">Uusi kansio</string>
<string name="actionbar_move_or_copy">Siirr tai kopioi</string>
<string name="actionbar_open_with">Avaa sovelluksella</string>
<string name="actionbar_search">Etsi</string>
<string name="actionbar_see_details">Tiedot</string>
<string name="actionbar_send_file">Lhet</string>
<string name="actionbar_settings">Asetukset</string>
<string name="actionbar_sort">Lajittele</string>
<string name="active_user">Aktiivinen kyttj</string>
<string name="activities_no_results_headline">Ei viel toimia</string>
<string name="activities_no_results_message">Ei viel tapahtumia kuten lisyksi, muutoksia tai jakoja.</string>
<string name="activity_chooser_send_file_title">Lhet</string>
<string name="activity_chooser_title">Lhet linkki</string>
<string name="activity_icon">Aktiviteetti</string>
<string name="add_another_public_share_link">Lis toinen linkki</string>
<string name="add_new_public_share">Lis uusi julkinen jakolinkki</string>
<string name="add_to_cloud">Lis kohteeseen %1$s</string>
<string name="advanced_settings">Lisasetukset</string>
<string name="allow_resharing">Salli uudelleenjakaminen</string>
<string name="app_config_proxy_port_title">Vlityspalvelimen portti</string>
<string name="app_widget_description">Nytt yhden pienoissovelluksen konsolista</string>
<string name="appbar_search_in">Etsi kohteesta %s</string>
<string name="assistant_screen_all_task_type">Kaikki</string>
<string name="assistant_screen_delete_task_alert_dialog_description">Haluatko varmasti poistaa tmn tehtvn?</string>
<string name="assistant_screen_delete_task_alert_dialog_title">Poista tehtv</string>
<string name="assistant_screen_failed_task_text">Eponnistui</string>
<string name="assistant_screen_scheduled_task_status_text">Aikataulutettu</string>
<string name="assistant_screen_successful_task_text">Valmistui</string>
<string name="assistant_screen_task_create_success_message">Tehtv luotu</string>
<string name="assistant_screen_task_delete_success_message">Tehtv poistettu</string>
<string name="assistant_screen_task_more_actions_bottom_sheet_delete_action">Poista tehtv</string>
<string name="assistant_screen_unknown_task_status_text">Tuntematon</string>
<string name="associated_account_not_found">Liitetty tili ei lydy!</string>
<string name="auth_access_failed">Psy eponnistui: %1$s</string>
<string name="auth_account_does_not_exist">Tlle laitteelle ei ole viel asennettu tili.</string>
<string name="auth_account_not_new">Tili samalle kyttjlle ja palvelimelle on jo olemassa laitteella</string>
<string name="auth_account_not_the_same">Sytetty kyttj ei tsm tmn tilin kyttjn kanssa</string>
<string name="auth_bad_oc_version_title">Tuntematon palvelimen versio</string>
<string name="auth_connection_established">Yhteys muodostettu</string>
<string name="auth_fail_get_user_name">Palvelin ei palauta oikeaa kyttjtunnusta, ota yhteys yllpitoon.</string>
<string name="auth_host_url">Palvelimen osoite https://</string>
<string name="auth_incorrect_address_title">Palvelimen osoitteen muoto on virheellinen</string>
<string name="auth_incorrect_path_title">Palvelinta ei lytynyt</string>
<string name="auth_no_net_conn_title">Ei verkkoyhteytt</string>
<string name="auth_nossl_plain_ok_title">Salattu yhteys ei ole kytettviss.</string>
<string name="auth_not_configured_title">Vrin tehdyt palvelin-asetukset</string>
<string name="auth_oauth_error">Eponnistunut valtuutus</string>
<string name="auth_oauth_error_access_denied">Valtuutuspalvelun esti kytn</string>
<string name="auth_redirect_non_secure_connection_title">Salattu yhteys on ohjattu salaamatonta reitti pitkin.</string>
<string name="auth_secure_connection">Salattu yhteys muodostettu</string>
<string name="auth_ssl_general_error_title">SSL:n alustus eponnistui</string>
<string name="auth_ssl_unverified_server_title">SSL-palvelimen identiteetti ei voitu vahvistaa</string>
<string name="auth_testing_connection">Testataan yhteytt</string>
<string name="auth_timeout_title">Palvelimen vastaus viipyy liian kauan</string>
<string name="auth_trying_to_login">Yritetn kirjautua</string>
<string name="auth_unauthorized">Vr kyttjtunnus tai salasana</string>
<string name="auth_unknown_error_exception_title">Tuntematon virhe: %1$s</string>
<string name="auth_unknown_error_http_title">Tapahtui tuntematon HTTP-virhe!</string>
<string name="auth_unknown_error_title">Tuntematon virhe</string>
<string name="auth_unknown_host_title">Palvelinta ei lytynyt</string>
<string name="auth_unsupported_multiaccount">%1$s ei tue useita tilej</string>
<string name="auth_wrong_connection_title">Yhteyden muodostaminen ei onnistunut</string>
<string name="auto_upload_file_behaviour_kept_in_folder">Silytetty alkuperisess kansiossa, koska se on vain luku</string>
<string name="auto_upload_on_wifi">Lhet vain Wi-Fi-yhteydell</string>
<string name="auto_upload_path">/AutoUpload</string>
<string name="autoupload_configure">Asetukset</string>
<string name="autoupload_create_new_custom_folder">Luo uusi kansioasetus</string>
<string name="autoupload_custom_folder">Mrit oma kansio</string>
<string name="autoupload_disable_power_save_check">Poista virransstvalinta kytst</string>
<string name="autoupload_hide_folder">Piilota kansio</string>
<string name="avatar">Profiilikuva</string>
<string name="away">Poissa</string>
<string name="backup_settings">Varmuuskopioinnin asetukset</string>
<string name="battery_optimization_close">Sulje</string>
<string name="battery_optimization_disable">Poista kytst</string>
<string name="battery_optimization_message">Laitteellasi on ehk pll akun optimisointi tlle sovellukselle. AutoUpload ei vlttmtt toimi oikein ellet poista sovellusta optimisointilistalta.</string>
<string name="battery_optimization_title">Akun optimointi</string>
<string name="brute_force_delay">Viivstetty liian monen eponnistuneen yrityksen takia</string>
<string name="calendar">Kalenteri</string>
<string name="calendars">Kalenterit</string>
<string name="certificate_load_problem">Varmennetta ladatessa ilmeni ongelmia.</string>
<string name="changelog_dev_version">Muutosloki kehitysversiolle</string>
<string name="check_back_later_or_reload">Lataa uudelleen tai yrit myhemmin uudelleen.</string>
<string name="checkbox">Valintaruutu</string>
<string name="choose_local_folder">Valitse paikallinen kansio</string>
<string name="choose_remote_folder">Valitse etkansio</string>
<string name="choose_template_helper_text">Valitse mallipohja ja anna tiedostonimi</string>
<string name="choose_which_file">Valitse silytettv tiedosto!</string>
<string name="choose_widget">Valitse pienoissovellus</string>
<string name="clear_notifications_failed">Ilmoituksia ei voitu tyhjent</string>
<string name="clear_status_message">Tyhjenn tilaviesti</string>
<string name="clear_status_message_after">Tyhjenn tilaviesti, kun on kulunut</string>
<string name="clipboard_label">Teksti kopioitu %1$s</string>
<string name="clipboard_no_text_to_copy">Leikepydlle ei kopioitunut mitn</string>
<string name="clipboard_text_copied">Linkki kopioitu</string>
<string name="clipboard_unexpected_error">Odottamaton virhe kopioitaessa leikepydlle</string>
<string name="common_back">Takaisin</string>
<string name="common_cancel">Peru</string>
<string name="common_cancel_sync">Peru synkronointi</string>
<string name="common_choose_account">Valitse tili</string>
<string name="common_confirm">Vahvista</string>
<string name="common_copy">Kopioi</string>
<string name="common_delete">Poista</string>
<string name="common_error">Virhe</string>
<string name="common_error_out_memory">Muistia ei ole riittvsti</string>
<string name="common_error_unknown">Tuntematon virhe</string>
<string name="common_loading">Ladataan</string>
<string name="common_next">Seuraava</string>
<string name="common_no">Ei</string>
<string name="common_ok">OK</string>
<string name="common_pending">Odottaa</string>
<string name="common_remove">Poista</string>
<string name="common_rename">Nime uudelleen</string>
<string name="common_save">Tallenna</string>
<string name="common_send">Lhet</string>
<string name="common_share">Jaa</string>
<string name="common_skip">Ohita</string>
<string name="common_switch_account">Vaihda kyttj</string>
<string name="common_switch_to_account">Vaihda kyttjn</string>
<string name="common_yes">Kyll</string>
<string name="community_beta_headline">Testaa kehitysversiota</string>
<string name="community_beta_text">Tm ksitt kaikki tulevat ominaisuudet ja sislt tysin uutta, jopa testaamatonta, koodia. Bugeja ja virheit voi lyty. Jos ja kun niin ky, muista raportoida niist, jotta ne korjattaisiin. </string>
<string name="community_contribute_forum_forum">keskustelupalsta</string>
<string name="community_contribute_forum_text">Auta muita. Avaa</string>
<string name="community_contribute_github_text">Tutki, muokkaa ja luo ohjelmia. Katso listietoja %1$s</string>
<string name="community_contribute_headline">Osallistu kehittmiseen</string>
<string name="community_contribute_translate_text">sovellus</string>
<string name="community_contribute_translate_translate">Knn</string>
<string name="community_dev_direct_download">Lataa kehitysjulkaisu suoraan</string>
<string name="community_dev_fdroid">Lataa kehitysjulkaisu F-Droidin pill.</string>
<string name="community_rc_fdroid">Lataa julkaisuehdokas F-Droidin pill.</string>
<string name="community_rc_play_store">Lataa julkaisuehdokas Googlen Play storesta.</string>
<string name="community_release_candidate_headline">Julkaisuehdokas</string>
<string name="community_release_candidate_text">Julkaisuehdokas (RC) on lhes valmis versio virallisesti julkaistavasta versiosta ja on yleens tysin toimiva. Testaa omat asetukset ja varmista niiden toimivuus. Kirjaudu siis testaajaksi Play storessa tai katso \"Version\" valikosta F-Droid piss.</string>
<string name="community_testing_bug_text">Lysitk bugin tai jotain muuta outoa?</string>
<string name="community_testing_headline">Auta testaamalla</string>
<string name="community_testing_report_text">Ilmoita ongelmasta GitHubissa</string>
<string name="configure_new_media_folder_detection_notifications">Asetukset</string>
<string name="confirm_removal">Poista paikallinen salaus</string>
<string name="confirmation_remove_file_alert">Haluatko varmasti poistaa kohteen %1$s?</string>
<string name="confirmation_remove_files_alert">Haluatko varmasti poistaa valitut kohteet?</string>
<string name="confirmation_remove_folder_alert">Haluatko varmasti poistaa kohteen %1$s ja sen sislln?</string>
<string name="confirmation_remove_folders_alert">Haluatko varmasti poistaa valitut kohteet ja niiden sislln?</string>
<string name="confirmation_remove_local">Vain paikallisen</string>
<string name="conflict_file_headline">Ristiriitainen kohde %1$s</string>
<string name="conflict_local_file">Paikallinen tiedosto</string>
<string name="conflict_message_description">Jos valitset molemmat versiot, paikallisen tiedoston nimeen listn numero.</string>
<string name="conflict_server_file">Palvelintiedosto</string>
<string name="contactlist_item_icon">Kyttjkuvake yhteystietoihin</string>
<string name="contactlist_no_permission">Oikeutta ei mynnetty, mitn ei tuotu.</string>
<string name="contacts">Yhteystiedot</string>
<string name="contacts_backup_button">Varmuuskopioi nyt</string>
<string name="contacts_preferences_backup_scheduled">Varmuuskopiointi on ajastettu ja se alkaa pian</string>
<string name="contacts_preferences_import_scheduled">Tuonti on ajastettu ja se alkaa pian</string>
<string name="contacts_preferences_no_file_found">Tiedostoa ei lytynyt</string>
<string name="contacts_preferences_something_strange_happened">Viimeisint varmuuskopiota ei lytynyt!</string>
<string name="copied_to_clipboard">Kopioitu leikepydlle</string>
<string name="copy_file_error">Tt tiedostoa tai kansiota kopioitaessa tapahtui virhe</string>
<string name="copy_file_invalid_into_descendent">Ei ole mahdollista kopioida kansiota yhteen sen alikansiosta.</string>
<string name="copy_file_invalid_overwrite">Tiedosto on jo olemassa kohdekansiossa</string>
<string name="copy_file_not_found">Kopiointi eponnistui. Tarkista onko tiedostoa olemassa.</string>
<string name="copy_link">Kopioi linkki</string>
<string name="copy_move_to_encrypted_folder_not_supported">Kopiointi/siirto salattuun kansioon ei ole mahdollista.</string>
<string name="could_not_download_image">Koko kuvan lataaminen eponnistui</string>
<string name="could_not_retrieve_shares">Jakojen nouto ei onnistunut</string>
<string name="could_not_retrieve_url">URL:n palautus epnnistui</string>
<string name="create">Luo</string>
<string name="create_dir_fail_msg">Kansion luominen ei onnistunut</string>
<string name="create_new">Uusi</string>
<string name="create_new_document">Uusi dokumentti</string>
<string name="create_new_folder">Uusi kansio</string>
<string name="create_new_presentation">Uusi esitys</string>
<string name="create_new_spreadsheet">Uusi laskentataulukko</string>
<string name="create_rich_workspace">Lisn kansion kuvaus</string>
<string name="credentials_disabled">Kirjautumistiedot poistettu kytst</string>
<string name="daily_backup">Pivittinen varmuuskopio</string>
<string name="data_to_back_up">Varmuuskopioitavat tiedot</string>
<string name="default_credentials_wrong">Virheelliset kirjautumistiedot</string>
<string name="delete_account">Poista tili</string>
<string name="delete_entries">Poista merkinnt</string>
<string name="delete_link">Poista linkki</string>
<string name="deselect_all">Poista valinnat</string>
<string name="destination_filename">Kohdetiedoston nimi</string>
<string name="dev_version_new_version_available">Uusi versio saatavilla</string>
<string name="dev_version_no_information_available">Ei tietoja saatavilla.</string>
<string name="dev_version_no_new_version_available">Ei uutta versiota saatavilla.</string>
<string name="dialog_close">Sulje</string>
<string name="did_not_check_for_dupes">Kaksoiskappaleita ei tarkistettu.</string>
<string name="digest_algorithm_not_available">Tm digest-algoritmi ei ole kytettviss puhelimellasi</string>
<string name="direct_login_failed">Kirjautuminen suoran linkin kautta eponnistui!</string>
<string name="disable_new_media_folder_detection_notifications">Poista kytst</string>
<string name="dismiss">Hylk</string>
<string name="dismiss_notification_description">Hylk ilmoitus</string>
<string name="displays_mnemonic">Nytt 12-sanaisen tunnuslauseen</string>
<string name="dnd">l hiritse</string>
<string name="document_scan_export_dialog_images">Useita kuvia</string>
<string name="document_scan_export_dialog_pdf">PDF-tiedosto</string>
<string name="document_scan_export_dialog_title">Valitse viennin tyyppi</string>
<string name="document_scan_pdf_generation_failed">PDF:n luominen eponnistui</string>
<string name="document_scan_pdf_generation_in_progress">Luodaan PDF:</string>
<string name="done">Valmis</string>
<string name="dontClear">l tyhjenn</string>
<string name="download_cannot_create_file">Paikallista tiedostoa ei voi luoda</string>
<string name="download_latest_dev_version">Lataa viimeisin kehitysversio</string>
<string name="downloader_download_failed_content">Ei voitu ladata %1$s</string>
<string name="downloader_download_failed_credentials_error">Lataus eponnistui, kirjaudu sisn uudelleen</string>
<string name="downloader_download_failed_ticker">Lataus eponnistui</string>
<string name="downloader_download_file_not_found">Tm tiedosto ei ole en palvelimella kytettviss</string>
<string name="downloader_download_in_progress_content">%1$d%% ladataan palvelimelta %2$s</string>
<string name="downloader_download_in_progress_ticker">Ladataan</string>
<string name="downloader_download_succeeded_content">%1$s ladattu</string>
<string name="downloader_download_succeeded_ticker">Ladattu</string>
<string name="downloader_not_downloaded_yet">Ei viel ladattu</string>
<string name="drawer_close">Sulje valikko</string>
<string name="drawer_community">Yhteis</string>
<string name="drawer_header_background">Taustakuva \"Drawer\":in ylosassa</string>
<string name="drawer_item_activities">Viimeisimmt tapahtumat</string>
<string name="drawer_item_all_files">Kaikki tiedostot</string>
<string name="drawer_item_favorites">Suosikit</string>
<string name="drawer_item_gallery">Media</string>
<string name="drawer_item_groupfolders">Ryhmkansiot</string>
<string name="drawer_item_home">Koti</string>
<string name="drawer_item_notifications">Ilmoitukset</string>
<string name="drawer_item_on_device">Laitteessa</string>
<string name="drawer_item_recently_modified">skettin muokatut</string>
<string name="drawer_item_shared">Jaot</string>
<string name="drawer_item_trashbin">Poistetut tiedostot</string>
<string name="drawer_item_uploads_list">Lhetykset</string>
<string name="drawer_logout">Kirjaudu ulos</string>
<string name="drawer_open">Avaa valikko</string>
<string name="drawer_quota">%1$s / %2$s kytetty</string>
<string name="drawer_quota_unlimited">%1$s kytetty</string>
<string name="drawer_synced_folders">Automaattinen lhetys</string>
<string name="ecosystem_apps_display_more">Lis</string>
<string name="ecosystem_apps_display_talk">Talk</string>
<string name="ecosystem_apps_notes">Nextcloud Notes</string>
<string name="encrypted">Salaa</string>
<string name="end_to_end_encryption_confirm_button">Aseta salaus</string>
<string name="end_to_end_encryption_decrypting">Puretaan salausta</string>
<string name="end_to_end_encryption_dialog_close">Sulje</string>
<string name="end_to_end_encryption_enter_password">Anna salasana yksityisen avaimen salauksen purkuun.</string>
<string name="end_to_end_encryption_folder_not_empty">Kansio ei ole tyhj.</string>
<string name="end_to_end_encryption_generating_keys">Luodaan uusia avaimia</string>
<string name="end_to_end_encryption_keywords_description">Kaikki 12 sanaa yhdess on hyvin vahva salasana, jonka avulla pystyy katselemaan ja kyttmn salattuja tiedostoja. Ota ne talteen ja silyt turvallisessa paikassa. l jt pydlle!</string>
<string name="end_to_end_encryption_not_enabled">Pst phn -salaus poistettu kytst palvelimella.</string>
<string name="end_to_end_encryption_passphrase_title">Laita muistiin sinun 12 symboolinen salauksen avain</string>
<string name="end_to_end_encryption_password">Salasana</string>
<string name="end_to_end_encryption_retrieving_keys">Noudetaan avaimia</string>
<string name="end_to_end_encryption_storing_keys">Avainten silyttminen</string>
<string name="end_to_end_encryption_title">Aseta salaus</string>
<string name="end_to_end_encryption_unsuccessful">Avaimia ei voitu tallentaa, yrit uudelleen.</string>
<string name="end_to_end_encryption_wrong_password">Virhe salausta purkaessa. Oliko salasana vr?</string>
<string name="enter_destination_filename">Syt kohdetiedoston nimi</string>
<string name="enter_filename">Anna tiedostonimi</string>
<string name="error__upload__local_file_not_copied">%1$s ei voitu kopioida paikalliskansioon %2$s</string>
<string name="error_cant_bind_to_operations_service">Kriittinen virhe: toimenpiteiden suorittaminen ei onnistu</string>
<string name="error_choosing_date">Virhe piv valitessa</string>
<string name="error_comment_file">Virhe tiedostoa kommentoidessa</string>
<string name="error_crash_title">%1$s kaatunut</string>
<string name="error_creating_file_from_template">Virhe tiedostoa mallipohjasta luodessa</string>
<string name="error_file_actions">Virhe nytettess tiedostotoimintoja</string>
<string name="error_file_lock">Virhe tiedoston lukituksen muutoksessa</string>
<string name="error_report_issue_action">Raportti</string>
<string name="error_report_issue_text">Haluatko ilmoittaa ongelmasta? (tarvitset GitHub-tilin)</string>
<string name="error_retrieving_file">Tiedoston noudossa tapahtui virhe</string>
<string name="error_retrieving_templates">Tapahtui virhe mallien lataamisessa</string>
<string name="error_starting_direct_camera_upload">Virhe kameraa kynnistess</string>
<string name="etm_accounts">Tilit</string>
<string name="etm_background_job_created">Luonut</string>
<string name="etm_background_job_name">Tyn nimi</string>
<string name="etm_background_job_progress">Edistyminen</string>
<string name="etm_background_job_state">Tila</string>
<string name="etm_background_job_user">Kyttj</string>
<string name="etm_background_job_uuid">UUID</string>
<string name="etm_background_jobs">Taustatyt</string>
<string name="etm_background_jobs_cancel_all">Peruuta kaikki tyt</string>
<string name="etm_background_jobs_prune">Karsi ei aktiivisia suoritteita</string>
<string name="etm_background_jobs_schedule_test_job">Ajoita testity</string>
<string name="etm_background_jobs_start_test_job">Kynnist testity</string>
<string name="etm_background_jobs_stop_test_job">Pysyt testity</string>
<string name="etm_migrations">Yhdistminen (sovelluksen pivitys)</string>
<string name="etm_preferences">Asetukset</string>
<string name="etm_title">Kehittjn testitila</string>
<string name="etm_transfer">Tiedoston siirto</string>
<string name="etm_transfer_enqueue_test_download">Jonota testilataus</string>
<string name="etm_transfer_enqueue_test_upload">Jonota testilhetys</string>
<string name="etm_transfer_remote_path">Etpolku</string>
<string name="etm_transfer_type">Siirr</string>
<string name="etm_transfer_type_download">Lataa</string>
<string name="etm_transfer_type_upload">Lhet</string>
<string name="fab_label">Lis tai lhet</string>
<string name="failed_to_download">Tiedoston vlittminen latausmanagerille eponnistui</string>
<string name="failed_to_print">Tiedoston tulostaminen eponnistui</string>
<string name="failed_to_start_editor">Editorin kaynnistminen eponnistui</string>
<string name="failed_update_ui">Kyttliittymn pivitys eponnistui</string>
<string name="favorite">Lis suosikkeihin</string>
<string name="favorite_icon">Suosikki</string>
<string name="file_already_exists">Tmn niminen tiedosto on jo olemassa</string>
<string name="file_delete">Poista</string>
<string name="file_detail_activity_error">Toimintojen palauttaminen tiedostolle eponnistui</string>
<string name="file_details_no_content">Listietoja ei voitu lataa.</string>
<string name="file_icon">Tiedosto</string>
<string name="file_keep">Pid</string>
<string name="file_list_empty">Lhet sislt tai synkronisoi laitteidesi kanssa</string>
<string name="file_list_empty_favorite_headline">Ei viel suosikkeja</string>
<string name="file_list_empty_favorites_filter_list">Suosikeiksi merkitsemsi tiedostot ja kansiot nkyvt tss.</string>
<string name="file_list_empty_gallery">Kuvia tai videoita ei lytynyt</string>
<string name="file_list_empty_headline">Ei tiedostoja</string>
<string name="file_list_empty_headline_search">Ei kohteita tss kansiossa</string>
<string name="file_list_empty_headline_server_search">Ei tuloksia</string>
<string name="file_list_empty_moving">Tll ei ole mitn. Voit list kansion.</string>
<string name="file_list_empty_on_device">Ladatut tiedostot ja kansiot nkyvt tll.</string>
<string name="file_list_empty_recently_modified">Viimeisen 7 pivn aikana muokattuja tiedostoja ei lytynyt</string>
<string name="file_list_empty_search">Ehk se on toisessa kansiossa?</string>
<string name="file_list_empty_shared">Jakamasi tiedostot ja kansiot nkyvt tss.</string>
<string name="file_list_empty_shared_headline">Ei mitn jaettua</string>
<string name="file_list_empty_unified_search_no_results">Haulla ei lytynyt tuloksia</string>
<string name="file_list_folder">kansio</string>
<string name="file_list_loading">Ladataan</string>
<string name="file_list_no_app_for_file_type">Tlle tiedostotyypille ei lytynyt sovellusta.</string>
<string name="file_list_seconds_ago">sekuntia sitten</string>
<string name="file_management_permission">Kyttoikeus tarvitaan</string>
<string name="file_management_permission_optional">Tallennusoikeudet</string>
<string name="file_management_permission_optional_text">%1$s toimii parhaiten, kun sille on mynnetty kyttoikeus tallennustilan kyttn. Voit mynt tydet kyttoikeudet tai vain luku-oikeudet kuviin ja videoihin.</string>
<string name="file_management_permission_text">%1$s tarvitsee kyttoikeuden tallennustilan kyttn tiedostojen lhettmiseksi. Voit mynt tydet oikeudet kaikkiin tiedostoihin tai vain luku -oikeudet kuviin ja videoihin.</string>
<string name="file_migration_checking_destination">Tarkistetaan kohdetta</string>
<string name="file_migration_cleaning">Siivotaan</string>
<string name="file_migration_dialog_title">Pivitetn tietojen tallennuspolkua</string>
<string name="file_migration_directory_already_exists">Data-kansio on jo olemassa, Valitse yksi seuraavista:</string>
<string name="file_migration_failed_dir_already_exists">Nextcloud-kansio on jo olemassa</string>
<string name="file_migration_failed_not_enough_space">Tarvitaan enemmn tilaa</string>
<string name="file_migration_failed_not_readable">Lhdetiedostosta ei voinut lukea</string>
<string name="file_migration_failed_not_writable">Kohdetiedostoon ei voinut kirjoittaa</string>
<string name="file_migration_failed_while_coping">Virhe migraation aikana</string>
<string name="file_migration_failed_while_updating_index">Indeksin pivitys eponnistui</string>
<string name="file_migration_migrating">Siirretn tietoja</string>
<string name="file_migration_ok_finished">Valmistunut</string>
<string name="file_migration_override_data_folder">Korvaa</string>
<string name="file_migration_preparing">Valmistellaan migraatiota</string>
<string name="file_migration_restoring_accounts_configuration">Palautetaan tilin asetuksia</string>
<string name="file_migration_saving_accounts_configuration">Tallennetaan tilin asetuksia</string>
<string name="file_migration_source_not_readable">Haluatko yh vaihtaa tallennuspolun %1$s?\n\nHuomio: Kaikki data tytyy ladata uudestaan.</string>
<string name="file_migration_source_not_readable_title">Lhdekansio ei ole luettavissa</string>
<string name="file_migration_updating_index">Pivitetn indeksi</string>
<string name="file_migration_use_data_folder">Kyt</string>
<string name="file_migration_waiting_for_unfinished_sync">Odotetaan tytt synkronointia</string>
<string name="file_not_found">Tiedostoa ei lytynyt</string>
<string name="file_not_synced">Tiedostoa ei voitu synkronoida. Nytetn viimeisin saatavilla oleva versio.</string>
<string name="file_rename">Nime uudelleen</string>
<string name="file_version_restored_error">Virhe palauttaessa tiedostoversiota!</string>
<string name="file_version_restored_successfully">Tiedostoversio palautettu onnistuneesti.</string>
<string name="filedetails_details">Tiedot</string>
<string name="filedetails_download">Lataa</string>
<string name="filedetails_export">Vie</string>
<string name="filedetails_renamed_in_upload_msg">Tiedoston nimeksi muutettiin %1$s lhetyksen aikana</string>
<string name="filedetails_sync_file">Synkronoi</string>
<string name="filedisplay_no_file_selected">Tiedostoa ei ole valittu</string>
<string name="filename_empty">Tiedoston nimi ei voi olla tyhj</string>
<string name="filename_forbidden_characters">Kielletyt merkit: / \\ < > : \" | ? *</string>
<string name="filename_forbidden_charaters_from_server">Tiedoston nimi sislt ainakin yhden virheellisen merkin</string>
<string name="filename_hint">Tiedostonimi</string>
<string name="first_run_1_text">Pid tietosi turvassa ja omassa hallinnassa</string>
<string name="folder_already_exists">Kansio on jo olemassa</string>
<string name="folder_confirm_create">Luo</string>
<string name="folder_list_empty_headline">Ei kansioita tll</string>
<string name="folder_picker_choose_button_text">Valitse</string>
<string name="folder_picker_choose_caption_text">Valitse kohdekansio</string>
<string name="folder_picker_copy_button_text">Kopioi</string>
<string name="folder_picker_move_button_text">Siirr</string>
<string name="forbidden_permissions">Sinulla ei ole oikeutta %s</string>
<string name="forbidden_permissions_copy">kopioida tm tiedosto</string>
<string name="forbidden_permissions_create">luoda tt tiedostoa</string>
<string name="forbidden_permissions_delete">poistaa tiedostoa</string>
<string name="forbidden_permissions_move">siirt tm tiedosto</string>
<string name="forbidden_permissions_rename">nimet tiedostoa uudelleen</string>
<string name="foreground_service_upload">Lhetetn tiedostoja</string>
<string name="foreign_files_fail">Joitain tiedostoja ei voitu siirt</string>
<string name="foreign_files_local_text">Paikallinen: %1$s</string>
<string name="foreign_files_move">Siirr kaikki</string>
<string name="foreign_files_remote_text">Et: %1$s</string>
<string name="foreign_files_success">Kaikki tiedostot siirrettiin</string>
<string name="forward">Vlit</string>
<string name="fourHours">4 tuntia</string>
<string name="hidden_file_name_warning">Nimi johtaa piilotettuun tiedostoon</string>
<string name="hint_name">Nimi</string>
<string name="hint_note">Huomio</string>
<string name="hint_password">Salasana</string>
<string name="host_not_available">Ei yhteytt palvelimeen</string>
<string name="host_your_own_server">Yllpid oma palvelin</string>
<string name="icon_for_empty_list">Kuvake tyhjlle listalle</string>
<string name="icon_of_dashboard_widget">Pienoissovelluksen kuvake</string>
<string name="icon_of_widget_entry">Widgetin merkinnn kuvake</string>
<string name="image_editor_rotate_ccw">Kierr vastapivn</string>
<string name="image_editor_rotate_cw">Kierr mytpivn</string>
<string name="image_editor_unable_to_edit_image">Kuvaa ei voi muokata.</string>
<string name="image_preview_filedetails">Tiedoston yksityiskohdat</string>
<string name="image_preview_unit_fnumber">/%s</string>
<string name="image_preview_unit_iso">ISO %s</string>
<string name="image_preview_unit_megapixel">%s MP</string>
<string name="image_preview_unit_millimetres">%s mm</string>
<string name="image_preview_unit_seconds">%s s</string>
<string name="in_folder">kansiossa %1$s</string>
<string name="instant_upload_existing">Siirr mys olemassaolevat tiedostot palvelimelle</string>
<string name="instant_upload_on_charging">Lhet vain ladattaessa virtaa</string>
<string name="instant_upload_path">/InstantUpload</string>
<string name="invalid_url">Virheellinen URL</string>
<string name="invisible">Nkymtn</string>
<string name="label_empty">Nimike ei voi olla tyhj</string>
<string name="last_backup">Viimeisin varmuuskopio: %1$s</string>
<string name="link">Linkki</string>
<string name="link_name">Linkin nimi</string>
<string name="link_share_allow_upload_and_editing">Salli lhetys ja muokkaus</string>
<string name="link_share_editing">Muokataan</string>
<string name="link_share_file_drop">Tiedostojen pudotus (vain lhetys)</string>
<string name="link_share_view_only">Vain katselu</string>
<string name="list_layout">Luettelonkym</string>
<string name="load_more_results">Lataa lis tuloksia</string>
<string name="local_file_list_empty">Tss kansiossa ei ole tiedostoja</string>
<string name="local_file_not_found_message">Tiedostoa ei lytynyt paikallisesta tiedostojrjestelmst</string>
<string name="local_folder_friendly_path">%1$s/%2$s</string>
<string name="local_folder_list_empty">Kansioita ei ole enemp.</string>
<string name="locate_folder">Paikanna kansio</string>
<string name="lock_expiration_info">Vanhenee: %1$s</string>
<string name="lock_file">Lukitse tiedosto</string>
<string name="locked_by">Lukinnut %1$s</string>
<string name="locked_by_app">Lukinnut %1$s sovellus</string>
<string name="log_send_mail_subject">%1$sin Android-sovelluksen lokit</string>
<string name="log_send_no_mail_app">Sovellusta ei lytynyt lokien lhettmist varten. Asenna shkpostisovellus.</string>
<string name="logged_in_as">Kirjautuneena tilill %1$s</string>
<string name="login">Kirjaudu sisn</string>
<string name="login_url_helper_text">Linkki %1$s selainkyttliittymsi.</string>
<string name="logs_menu_delete">Poista lokitiedot</string>
<string name="logs_menu_refresh">Pivit</string>
<string name="logs_menu_search">Etsi lokitiedoista</string>
<string name="logs_menu_send">Lhet lokit shkpostilla</string>
<string name="logs_status_filtered">Lokit: %1$d kt, kysely vastasi %2$d / %3$d ajassa %4$d ms</string>
<string name="logs_status_loading">Ladataan</string>
<string name="logs_status_not_filtered">Lokit: %1$d kt, ei filtteri</string>
<string name="logs_title">Lokit</string>
<string name="maintenance_mode">Palvelin on huoltotilassa</string>
<string name="manage_space_clear_data">Tyhjenn tiedot</string>
<string name="manage_space_description">Asetukset, tietokanta ja palvelinsertifikaatit %1$s:n tiedoista poistetaan pysyvsti. \n\nLadatut tiedostot silyvt koskemattomina.\n\nTm voi kest jonkin aikaa.</string>
<string name="manage_space_title">Hallitse tilaa</string>
<string name="media_err_invalid_progressive_playback">Mediatiedostoa ei voida suoratoistaa</string>
<string name="media_err_io">Mediatiedostoa ei voitu lukea</string>
<string name="media_err_malformed">Mediatiedostoa ei ole koodattu kelvollisesti</string>
<string name="media_err_timeout">Tiedoston toisto aikakatkaistiin.</string>
<string name="media_err_unknown">Sisnrakennettu mediasoitin ei voi toistaa mediatiedostoa</string>
<string name="media_err_unsupported">Mediakoodekki ei ole tuettu</string>
<string name="media_forward_description">Eteenpin kelaus -painike</string>
<string name="media_notif_ticker">%1$s-musiikkisoitin</string>
<string name="media_play_pause_description">Toisto tai keskeytys -painike</string>
<string name="media_rewind_description">Taaksepin kelaus -painike</string>
<string name="media_state_playing">%1$s (toistetaan)</string>
<string name="menu_item_sort_by_date_newest_first">Uusin ensin</string>
<string name="menu_item_sort_by_date_oldest_first">Vanhin ensin</string>
<string name="menu_item_sort_by_name_a_z">A - </string>
<string name="menu_item_sort_by_name_z_a"> - A</string>
<string name="menu_item_sort_by_size_biggest_first">Suurin ensin</string>
<string name="menu_item_sort_by_size_smallest_first">Pienin ensin</string>
<string name="more">Lis</string>
<string name="move_file_error">Tmn tiedoston tai kansion siirtoa yrittess tapahtui virhe</string>
<string name="move_file_invalid_into_descendent">Ei ole mahdollista siirt kansiota yhteen sen alikansiosta.</string>
<string name="move_file_invalid_overwrite">Tiedosto on jo olemassa kohdekansiossa</string>
<string name="move_file_not_found">Tiedoston siirtminen ei onnistunut. Varmista ett tiedosto on olemassa.</string>
<string name="network_error_connect_timeout_exception">Palvelinta odottaessa tapahtui virhe. Toimenpidett ei voitu suorittaa loppuun.</string>
<string name="network_error_socket_exception">Palvelimeen yhdistess tapahtui virhe.</string>
<string name="network_error_socket_timeout_exception">Palvelinta odottaessa tapahtui virhe. Toimenpidett ei voitu suorittaa loppuun.</string>
<string name="network_host_not_available">Toimintoa ei voitu suorittaa loppuun. Palvelin ei ole kytettviss.</string>
<string name="new_comment">Uusi kommentti</string>
<string name="new_media_folder_detected">Uusi mediakansio %1$s lytynyt.</string>
<string name="new_media_folder_photos">kuva</string>
<string name="new_media_folder_videos">video</string>
<string name="new_notification">Uusi Ilmoitus</string>
<string name="new_version_was_created">Luotiin uusi versio</string>
<string name="no_actions">Ei tapahtumia tlle kyttjlle</string>
<string name="no_browser_available">Linkkien ksittelyyn ei ole sovellusta</string>
<string name="no_calendar_exists">Kalenteria ei ole olemassa</string>
<string name="no_email_app_available">Shkpostiosoitteiden ksittelyyn ei ole saatavilla sovellusta</string>
<string name="no_items">Ei kohteita</string>
<string name="no_mutliple_accounts_allowed">Vain yksi tili on sallittu</string>
<string name="no_pdf_app_available">PDF -sovellusta ei lydy</string>
<string name="no_send_app">Valittujen tiedostojen lhettmiseen ei ole sovellusta</string>
<string name="no_share_permission_selected">Valitse vhintn yksi kyttoikeus jakaaksesi.</string>
<string name="note_could_not_sent">Huomiota ei voitu lhett</string>
<string name="note_icon_hint">Note-kuvake</string>
<string name="notification_action_failed">Toimenpiteen suorittaminen eponnistui</string>
<string name="notification_channel_download_description">Nytt latauksen edistymisen</string>
<string name="notification_channel_download_name_short">Lataukset</string>
<string name="notification_channel_file_sync_description">Nytt tiedostojen synkronoinnin edistymisen ja tulokset</string>
<string name="notification_channel_file_sync_name">Tiedostojen synkronointi</string>
<string name="notification_channel_general_description">Nyt ilmoitukset uusia mediakansiota ja vastaavia varten</string>
<string name="notification_channel_general_name">Yleiset ilmoitukset</string>
<string name="notification_channel_media_description">Musiikin toiston edistyminen</string>
<string name="notification_channel_media_name">Mediasoitin</string>
<string name="notification_channel_push_description">Nyt palvelimen lhettmt push-ilmoitukset. Esimerkiksi kun sinut mainitaan kommenteissa, sinulle jaetaan etn tai kun yllpito julkaisee tiedotteen.</string>
<string name="notification_channel_push_name">Push-ilmoitukset</string>
<string name="notification_channel_upload_description">Nytt lhetyksen edistymisen</string>
<string name="notification_channel_upload_name_short">Lhetykset</string>
<string name="notification_icon">Ilmoituksen kuvake</string>
<string name="notifications_no_results_headline">Ei ilmoituksia</string>
<string name="notifications_no_results_message">Katso myhemmin uudestaan.</string>
<string name="offline_mode">Ei internetyhteytt</string>
<string name="oneHour">1 tunti</string>
<string name="online">Online</string>
<string name="online_status">Online-tila</string>
<string name="outdated_server">Palvelimen elinkaari on pttynyt, pivit!</string>
<string name="overflow_menu">Lis -valikko</string>
<string name="pass_code_configure_your_pass_code">Anna suojakoodisi</string>
<string name="pass_code_configure_your_pass_code_explanation">Suojakoodi kysytn joka kerta, kun sovellus kynnistetn</string>
<string name="pass_code_enter_pass_code">Anna suojakoodi</string>
<string name="pass_code_mismatch">Suojakoodit eivt tsm</string>
<string name="pass_code_reenter_your_pass_code">Anna suojakoodisi uudelleen</string>
<string name="pass_code_remove_your_pass_code">Poista suojakoodisi</string>
<string name="pass_code_removed">Suojakoodi poistettu</string>
<string name="pass_code_stored">Suojakoodi tallennettu</string>
<string name="pass_code_wrong">Virheellinen suojakoodi</string>
<string name="pdf_zoom_tip">Napauta sivua lhentksesi</string>
<string name="permission_allow">Salli</string>
<string name="permission_deny">Kiell</string>
<string name="permission_storage_access">Tiedostojen lhetys ja lataaminen vaatii lisoikeuksia.</string>
<string name="picture_set_as_no_app">Kuvan liittmiseksi ei lytynyt sovellusta</string>
<string name="pin_home">Kiinnit kotinyttn</string>
<string name="pin_shortcut_label">Avaa %1$s</string>
<string name="placeholder_fileSize">389 kt</string>
<string name="placeholder_filename">paikkamerkki.txt</string>
<string name="placeholder_media_time">12:23:45</string>
<string name="placeholder_sentence">Tm on paikkamerkki</string>
<string name="placeholder_timestamp">18.05.2012 12:23</string>
<string name="player_stop">pysyt</string>
<string name="player_toggle">vaihda</string>
<string name="power_save_check_dialog_message">Virranssttilan tarkistuksen poistaminen saattaa johtaa tiedostojen lhettmiseen alhaisella akun varauksella!</string>
<string name="pref_behaviour_entries_delete_file">Poistetaan</string>
<string name="pref_behaviour_entries_keep_file">Pidetn alkuperisess kansiossa</string>
<string name="pref_behaviour_entries_move">Siirretn sovelluskansioon</string>
<string name="pref_instant_name_collision_policy_dialogTitle">Mit tehdn, jos tiedosto on jo olemassa?</string>
<string name="pref_instant_name_collision_policy_entries_always_ask">Kysy minulta joka kerta</string>
<string name="pref_instant_name_collision_policy_entries_cancel">Ohita lhettminen</string>
<string name="pref_instant_name_collision_policy_entries_overwrite">Korvaa palvelimen versio</string>
<string name="pref_instant_name_collision_policy_entries_rename">Nime uusi versio uudelleen</string>
<string name="pref_instant_name_collision_policy_title">Mit tehdn, jos tiedosto on jo olemassa?</string>
<string name="prefs_add_account">Lis tili</string>
<string name="prefs_calendar_contacts">Synkronoi kalenteri ja yhteystiedot</string>
<string name="prefs_calendar_contacts_no_store_error">Sek F-Droid ett Google Play asentamatta</string>
<string name="prefs_calendar_contacts_summary">Aseta DAVx5 (tunnettu nimell DAVdroid) (v1.3.0+) nykyiselle tilille</string>
<string name="prefs_category_about">Tietoja</string>
<string name="prefs_category_details">Tiedot</string>
<string name="prefs_category_dev">Kehittj</string>
<string name="prefs_category_general">Yleiset</string>
<string name="prefs_category_more">Enemmn</string>
<string name="prefs_daily_contact_backup_summary">Pivittinen varmuuskopio yhteystiedoistasi</string>
<string name="prefs_davx5_setup_error">Odottamaton virhe mritettess DAVx5:t (aiemmin DAVdroid)</string>
<string name="prefs_e2e_active">Pst phn -salaus on mritetty!</string>
<string name="prefs_e2e_mnemonic">E2E-avainkoodi</string>
<string name="prefs_e2e_no_device_credentials">Jos haluat nytt avainkoodin, ota kyttn laitteen valtuudet.</string>
<string name="prefs_enable_media_scan_notifications">Nyt mediakartoituksen ilmoitukset</string>
<string name="prefs_enable_media_scan_notifications_summary">Ilmoita uusista lydetyist mediakansioista</string>
<string name="prefs_gpl_v2">
GNU yleinen lisenssi, versio 2</string>
<string name="prefs_help">Ohje</string>
<string name="prefs_imprint">Tiedot</string>
<string name="prefs_instant_behaviour_dialogTitle">Alkuperinen tiedosto</string>
<string name="prefs_instant_behaviour_title">Alkuperinen tiedosto</string>
<string name="prefs_instant_upload_path_use_subfolders_title">Kyt alikansioita</string>
<string name="prefs_keys_exist">Lis pst phn -salaus thn asiakasohjelmaan</string>
<string name="prefs_license">Lisenssi</string>
<string name="prefs_lock">Sovelluksen psykoodi</string>
<string name="prefs_lock_device_credentials_enabled">Laitteen kirjautumistiedot kytss</string>
<string name="prefs_lock_device_credentials_not_setup">Laitteelle ei ole mritelty kirjautumistietoja.</string>
<string name="prefs_lock_none">Ei mitn</string>
<string name="prefs_lock_title">Suojaa sovellus kytten</string>
<string name="prefs_lock_using_device_credentials">Laitteen kirjautumistiedot</string>
<string name="prefs_lock_using_passcode">Suojakoodi</string>
<string name="prefs_manage_accounts">Tilien hallinta</string>
<string name="prefs_recommend">Suosittele kaverille</string>
<string name="prefs_remove_e2e">Poista salaus paikallisesti</string>
<string name="prefs_setup_e2e">Mrit pst phn -salaus</string>
<string name="prefs_show_hidden_files">Nyt piilotetut tiedostot</string>
<string name="prefs_sourcecode">Hanki lhdekoodi</string>
<string name="prefs_storage_path">Tiedostojen tallennuskansio</string>
<string name="prefs_sycned_folders_summary">Hallinnoi kansioita automaattista latausta varten</string>
<string name="prefs_synced_folders_local_path_title">Paikallinen kansio</string>
<string name="prefs_synced_folders_remote_path_title">Etkansio</string>
<string name="prefs_theme_title">Teema</string>
<string name="prefs_value_theme_dark">Tumma</string>
<string name="prefs_value_theme_light">Vaalea</string>
<string name="prefs_value_theme_system">Seuraa jrjestelm</string>
<string name="preview_image_description">Kuvan esikatselu</string>
<string name="preview_image_error_no_local_file">Paikallista tiedostoa ei ole esikatselua varten</string>
<string name="preview_image_error_unknown_format">Kuvan nyttminen ei onnistunut</string>
<string name="preview_image_file_is_not_exist">Tiedostoa ei ole olemassa</string>
<string name="preview_sorry">Anteeksi</string>
<string name="privacy">Yksityisyys</string>
<string name="public_share_name">Uusi nimi</string>
<string name="push_notifications_not_implemented">Push-ilmoitukset ovat pois kytst, koska ne riippuvat suljetuista Google Play -palveluista.</string>
<string name="push_notifications_old_login">Ei puskusanomia johtuen vanhentuneesta kirjautumisistunnosta. Harkitse tilin uudelleenlismist.</string>
<string name="push_notifications_temp_error">Push-ilmoitukset eivt ole nyt kytettviss.</string>
<string name="qr_could_not_be_read">QR-koodia ei voitu lukea!</string>
<string name="recommend_subject">Kokeile %1$sia laitteellasi!</string>
<string name="recommend_text">Haluan, ett kokeilet %1$sia laitteellasi.\nLataa tst: %2$s</string>
<string name="recommend_urls">%1$s tai %2$s</string>
<string name="refresh_content">Pivit sislt</string>
<string name="reload">Lataa uudelleen</string>
<string name="remote">(et)</string>
<string name="remote_file_fetch_failed">Tiedostoa ei lytynyt!</string>
<string name="remove_e2e">Voit poistaa pst phn -salauksen paikallisesti tst asiakasohjelmasta</string>
<string name="remove_e2e_message">Voit poistaa pst phn -salauksen paikallisesti tst asiakasohjelmasta. Salatut tiedostot silyvt palvelimella, mutta niit ei synkronoida en thn tietokoneeseen.</string>
<string name="remove_fail_msg">Poistaminen eponnistui</string>
<string name="remove_local_account">Poista paikallinen tili</string>
<string name="remove_local_account_details">Poista tili laitteelta ja poista kaikki paikalliset tiedostot</string>
<string name="remove_notification_failed">Ilmoitusta ei voitu poistaa</string>
<string name="remove_push_notification">Poista</string>
<string name="remove_success_msg">Poistettu</string>
<string name="rename_dialog_title">Anna uusi nimi</string>
<string name="rename_local_fail_msg">Paikallisen kopion nime ei voitu muuttaa, yrit eri nime</string>
<string name="rename_server_fail_msg">Nimen muutos eponnistui, nimi on jo kytss</string>
<string name="request_account_deletion">Pyyd tilin poistoa</string>
<string name="reshare_not_allowed">Uudellenjako ei ole salluttu</string>
<string name="resharing_is_not_allowed">Uudelleenjakaminen ei ole sallittu</string>
<string name="resized_image_not_possible_download">Uuden kokoinen kuva ei ole saatavilla. Ladataanko tysikokoinen kuva?</string>
<string name="restore">Palauta tiedosto</string>
<string name="restore_backup">Palauta varmuuskopio</string>
<string name="restore_button_description">Palauta poistettu tiedosto</string>
<string name="restore_selected">Palauta valitut</string>
<string name="retrieving_file">Noudetaan tiedostoa</string>
<string name="richdocuments_failed_to_load_document">Asiakirjaa ei voitu lataa!</string>
<string name="scanQR_description">Kirjaudu QR-koodilla</string>
<string name="scan_page">Skannaa sivu</string>
<string name="screenshot_01_gridView_heading">Tietojasi suojaten</string>
<string name="screenshot_01_gridView_subline">itse-yllpidettv tuottavuus</string>
<string name="screenshot_02_listView_heading">Selaa ja jaa</string>
<string name="screenshot_02_listView_subline">kaikki toiminnot lhettyvill</string>
<string name="screenshot_03_drawer_heading">Tapahtumat, jaot, ...</string>
<string name="screenshot_03_drawer_subline">kaikki kytettviss nopeasti</string>
<string name="screenshot_04_accounts_heading">Kaikki tilisi</string>
<string name="screenshot_04_accounts_subline">yhdess paikassa</string>
<string name="screenshot_05_autoUpload_heading">Automaattinen lhetys</string>
<string name="screenshot_06_davdroid_heading">Kalenteri ja yhteystiedot</string>
<string name="screenshot_06_davdroid_subline">Synkronoi DAVx5:ll</string>
<string name="search_error">Virhe hakutulosten noutamisessa</string>
<string name="select_all">Valitse kaikki</string>
<string name="select_media_folder">Aseta kansio medialle</string>
<string name="select_one_template">Valitse yksi mallipohja</string>
<string name="select_template">Valitse mallipohja</string>
<string name="send">Lhet</string>
<string name="send_share">Lhet Jaa</string>
<string name="sendbutton_description">Lhet-painikkeen kuvake</string>
<string name="set_as">Aseta</string>
<string name="set_note">Aseta muistiinpano</string>
<string name="set_picture_as">Kyt kuvaa</string>
<string name="set_status">Aseta tilatieto</string>
<string name="set_status_message">Aseta tilaviesti</string>
<string name="share">Jaa</string>
<string name="share_copy_link">Jaa ja kopioi linkki</string>
<string name="share_dialog_title">Jakaminen</string>
<string name="share_expiration_date_format">%1$s</string>
<string name="share_expiration_date_label">Vanhenee %1$s</string>
<string name="share_file">Jaa %1$s</string>
<string name="share_group_clarification">%1$s (ryhm)</string>
<string name="share_internal_link">Jaa sisinen linkki</string>
<string name="share_internal_link_to_file_text">Sisinen jaettu linkki toimii vain kyttjill, joilla on oikeudet thn tiedostoon</string>
<string name="share_internal_link_to_folder_text">Sisinen jaettu linkki toimii vain kayttjill, joilla on oikeudet thn kansioon</string>
<string name="share_link">Jaa linkki</string>
<string name="share_link_empty_password">Salasana on pakko antaa</string>
<string name="share_link_file_error">Tiedoston tai kansion jakamisessa tapahtui virhe.</string>
<string name="share_link_file_no_exist">Jakaminen eponnistui. Ole hyv ja tarkasta onko tiedosto olemassa.</string>
<string name="share_link_forbidden_permissions">jakaa tiedostoa</string>
<string name="share_link_optional_password_title">Syt vaihtoehtoinen salasanan</string>
<string name="share_link_password_title">Anna salasana</string>
<string name="share_link_with_label">Jaa linkki (%1$s)</string>
<string name="share_no_expiration_date_label">Aseta vanhenemispiv</string>
<string name="share_no_password_title">Aseta salasana</string>
<string name="share_password_title">Salasanasuojattu</string>
<string name="share_permission_can_edit">Voi muokata</string>
<string name="share_permission_file_drop">Tiedoston pudotus</string>
<string name="share_permission_view_only">Vain katselu</string>
<string name="share_permissions">Jaon oikeudet</string>
<string name="share_remote_clarification">%1$s (et)</string>
<string name="share_room_clarification">%1$s (keskustelu)</string>
<string name="share_search">Nimi, Federoitu Cloud ID tai shkposti...</string>
<string name="share_send_new_email">Lhet uusi shkposti</string>
<string name="share_send_note">Huomio vastaanottajalle</string>
<string name="share_settings">Asetukset</string>
<string name="share_via_link_hide_download">Piilota lataus</string>
<string name="share_via_link_section_title">Jaa linkki</string>
<string name="share_via_link_send_link_label">Lhet linkki</string>
<string name="share_via_link_unset_password">Poista</string>
<string name="share_with_title">Jaa</string>
<string name="shared_avatar_desc">Kuvake jaetulta kyttjlt</string>
<string name="shared_icon_share">jaa</string>
<string name="shared_icon_shared">jaettu</string>
<string name="shared_icon_shared_via_link">jaettu linkin kautta</string>
<string name="shared_with_you_by">Jaettu sinulle kyttjlt %1$s</string>
<string name="sharee_add_failed">Jaon lisminen eponnistui</string>
<string name="show_images">Nyt kuvat</string>
<string name="show_video">Nyt videot</string>
<string name="signup_with_provider">Kirjaudu sisn palvelutarjoajan kautta</string>
<string name="single_sign_on_request_token" formatted="true">Salli kyttjlle %1$s psy Nextcloud -tilillesi %2$s?</string>
<string name="sort_by">Lajittelujrjestys</string>
<string name="ssl_validator_btn_details_hide">Piilota</string>
<string name="ssl_validator_btn_details_see">Tiedot</string>
<string name="ssl_validator_header">Palvelimen identiteetti ei voitu vahvistaa</string>
<string name="ssl_validator_label_C">Maa:</string>
<string name="ssl_validator_label_CN">Yleinen nimi:</string>
<string name="ssl_validator_label_L">Sijainti:</string>
<string name="ssl_validator_label_O">Organisaatio:</string>
<string name="ssl_validator_label_OU">Organisaatioyksikk:</string>
<string name="ssl_validator_label_ST">Osavaltio:</string>
<string name="ssl_validator_label_certificate_fingerprint">Sormenjlki:</string>
<string name="ssl_validator_label_issuer">Myntj:</string>
<string name="ssl_validator_label_signature">Allekirjoitus:</string>
<string name="ssl_validator_label_signature_algorithm">Algoritmi:</string>
<string name="ssl_validator_label_subject">Mynnetty kohteelle:</string>
<string name="ssl_validator_label_validity">Voimassaoloaika:</string>
<string name="ssl_validator_label_validity_from">Alkaen:</string>
<string name="ssl_validator_label_validity_to">Pttyen:</string>
<string name="ssl_validator_no_info_about_error">- Ei listietoja virheest</string>
<string name="ssl_validator_not_saved">Varmenteen tallennus eponnistui</string>
<string name="ssl_validator_null_cert">Varmennetta ei voi nytt.</string>
<string name="ssl_validator_question">Haluatko silti luottaa thn varmenteeseen?</string>
<string name="ssl_validator_reason_cert_expired">- Palvelimen varmenne on vanhentunut</string>
<string name="ssl_validator_reason_cert_not_trusted">- Palvelimen varmenteeseen ei luoteta</string>
<string name="ssl_validator_reason_cert_not_yet_valid">- Palvelimen varmenteen kelvolliset pivt ovat tulevaisuudessa</string>
<string name="ssl_validator_reason_hostname_not_verified">- Osoite ei vastaa sertifikaatissa mainittua isntnime</string>
<string name="status_message">Tilaviesti</string>
<string name="storage_camera">Kamera</string>
<string name="storage_choose_location">Valitse tallennustilan sijainti</string>
<string name="storage_description_default">Oletus</string>
<string name="storage_documents">Asiakirjat</string>
<string name="storage_downloads">Lataukset</string>
<string name="storage_internal_storage">Sisinen tallennustila</string>
<string name="storage_movies">Elokuvat</string>
<string name="storage_music">Musiikki</string>
<string name="storage_permission_full_access">Tysi psy</string>
<string name="storage_permission_media_read_only">Media vain luku-tilassa</string>
<string name="storage_pictures">Kuvat</string>
<string name="store_full_dev_desc">Itse yllpidetty tyalusta jota sin kontrolloit. \nTm on virallinen kehitysversio, sislten pvittin vaihtuvia uusia ja testaamattomia toimintoja, jotka voivat epvakauttaa ohjelmistoa ja aiheuttaa tietojen hvimist. Sovellus on tarkoitettu kyttjille jotka haluavat testata ja raportoida ohjelman virheit jos niit tapahtuu. l kyt sit ty ympristss!\n\nSek virallinen kehitysversio ett normaali versio ovat saatavilla F-droid:ssa ja ne voidaan asentaa samanaikaisesti. </string>
<string name="store_short_desc">Itse yllpidettv tuottavuusalusta, joka silytt kontrollin sinulla</string>
<string name="store_short_dev_desc">Itse yllpidettv tuottavuusalusta, joka silytt kontrollin sinulla (kehitysversio)</string>
<string name="stream">Suoratoista kyttmll...</string>
<string name="stream_not_possible_headline">Suoratoisto internetiin ei onnistu</string>
<string name="stream_not_possible_message">Ole hyv ja lataa media tai kyt ulkopuolista sovellusta.</string>
<string name="strict_mode">Strict-tila: HTTP-yhteyksi ei sallita!</string>
<string name="sub_folder_rule_day">Vuosi/kuukausi/piv</string>
<string name="sub_folder_rule_month">Vuosi/kuukausi</string>
<string name="sub_folder_rule_year">Vuosi</string>
<string name="subject_shared_with_you">\"%1$s\" on jaettu kanssasi</string>
<string name="subject_user_shared_with_you">%1$s jakoi kohteen \"%2$s\" kanssasi</string>
<string name="subtitle_photos_only">Vain kuvat</string>
<string name="subtitle_photos_videos">Kuvat ja videot</string>
<string name="subtitle_videos_only">Vain videot</string>
<string name="suggest">Ehdota</string>
<string name="sync_conflicts_in_favourites_ticker">Ristiriitoja lytynyt</string>
<string name="sync_current_folder_was_removed">Kansiota %1$s ei ole en olemassa</string>
<string name="sync_fail_content">Ei voitu synkronoida %1$s</string>
<string name="sync_fail_content_unauthorized">Vr salasana tilille %1$s</string>
<string name="sync_fail_in_favourites_ticker">\"Pid synkronoituna\" eponnistui</string>
<string name="sync_fail_ticker">Synkronointi eponnistui</string>
<string name="sync_fail_ticker_unauthorized">Synkronointi eponnistui, kirjaudu sisn uudelleen</string>
<string name="sync_file_nothing_to_do_msg">Tiedoston sislt on jo synkronoitu</string>
<string name="sync_folder_failed_content">Kansion %1$ssynkronointia ei voitu suorittaa loppuun</string>
<string name="sync_foreign_files_forgotten_explanation">Versiosta 1.3.16 lhtien, tst laitteesta lhetetyt tiedostot kopioidaan paikalliseen %1$s kansioon, jotta estetn datan hviminen synkronoitaessa yksittist tiedostoa usealle tilille.\n\nTst muutoksesta johtuen, kaikki aiemmilla versioilla lhetetyt tiedostot on kopioitu %2$s kansioon. Virhe esti tmn toiminnon viimeistelemisen synkronoinnin aikana. Voit joko jtt tiedostot kuten ne ovat ja poistaa linkin %3$s, tai siirt tiedostot %1$s kansioon ja silytt linkin %4$s. \n\nAlla on listattu paikalliset ja ulkoiset tiedostot %5$s:ssa, johon ne olivat linkitettyn. </string>
<string name="sync_foreign_files_forgotten_ticker">Jotkin paikalliset tiedostot unohtuivat</string>
<string name="sync_in_progress">Noudetaan tiedoston viimeisin versio.</string>
<string name="sync_not_enough_space_dialog_action_choose">Valitse synkronoitavat tiedot</string>
<string name="sync_not_enough_space_dialog_action_free_space">Vapauta tilaa</string>
<string name="sync_not_enough_space_dialog_placeholder">%1$s on %2$s, mutta vain %3$son kytettviss laitteessa.</string>
<string name="sync_not_enough_space_dialog_title">Ei tarpeeksi vapaata tilaa</string>
<string name="sync_status_button">Synkronoinnin tila -painike</string>
<string name="sync_string_files">Tiedostot</string>
<string name="synced_folder_settings_button">Asetukset-painike</string>
<string name="synced_folders_configure_folders">Mrit kansiot</string>
<string name="synced_folders_new_info">Heti lhetettvien tiedostojen lhetys on uudistettu tysin. Muuta automaattisen lhetyksen asetuksia pvalikossa vastaamaan nykyist toimintaa.\n\nNauti uudesta ja monipuolisemmasta toiminnosta.</string>
<string name="synced_folders_no_results">Mediakansioita ei lytynyt</string>
<string name="synced_folders_preferences_folder_path">%1$s varten</string>
<string name="synced_folders_type">Tyyppi</string>
<string name="synced_icon">Synkronoitu</string>
<string name="tags">Tunnisteet</string>
<string name="test_server_button">Testaa palvelinyhteys</string>
<string name="thirtyMinutes">30 minuuttia</string>
<string name="thisWeek">Tll viikolla</string>
<string name="thumbnail">Esikatselukuva</string>
<string name="thumbnail_for_existing_file_description">Esikatselu olemassa olevalle tiedostolle</string>
<string name="thumbnail_for_new_file_desc">Esikatselu uudelle tiedostolle</string>
<string name="today">Tnn</string>
<string name="trashbin_activity_title">Poistetut tiedostot</string>
<string name="trashbin_empty_headline">Ei poistettuja tiedostoja</string>
<string name="trashbin_empty_message">Voit palauttaa poistettuja tiedostoja tlt.</string>
<string name="trashbin_file_not_deleted">Tiedostoa %1$s ei voitu poistaa!</string>
<string name="trashbin_file_not_restored">Tiedostoa %1$s ei voitu palauttaa!</string>
<string name="trashbin_file_remove">Poista pysyvsti</string>
<string name="trashbin_loading_failed">Roskakorin lataaminen eponnistui!</string>
<string name="trashbin_not_emptied">Tiedostoja ei voitu poistaa pysyvsti!</string>
<string name="unlock_file">Vapauta tiedoston lukitus</string>
<string name="unread_comments">Lukemattomia kommentteja on olemassa</string>
<string name="unset_encrypted">Poista salaus</string>
<string name="unset_favorite">Poista suosikeista</string>
<string name="unshare_link_file_error">Tiedoston tai kansion jakamista lopetettaessa tapahtui virhe.</string>
<string name="unshare_link_file_no_exist">Jakamista ei voida lopettaa. Tarkasta onko tiedosto olemassa.</string>
<string name="unshare_link_forbidden_permissions">poistaa tiedoston jakamista</string>
<string name="unsharing_failed">Jakamisen peruuttaminen eponnistui</string>
<string name="untrusted_domain">Psy epluotettavan verkkotunnuksen kautta. Katso listietoja dokumentoinnista.</string>
<string name="update_link_file_error">Jakoa pivitettess tapahtui virhe.</string>
<string name="update_link_file_no_exist">Ei voida pivitt. Ole hyv ja tarkasta, onko tiedosto olemassa.</string>
<string name="update_link_forbidden_permissions">pivit tm jako</string>
<string name="updating_share_failed">Jaon pivitys eponnistui</string>
<string name="upload_action_failed_clear">Tyhjenn eponnistuneet lhetykset</string>
<string name="upload_action_failed_retry">Yrit lhetyst uudelleen</string>
<string name="upload_cannot_create_file">Paikallista tiedostoa ei voi luoda</string>
<string name="upload_chooser_title">Lhet</string>
<string name="upload_content_from_other_apps">Lhet sislt toisista sovelluksista</string>
<string name="upload_direct_camera_photo">Kuva</string>
<string name="upload_direct_camera_upload">Lhet kamerasta</string>
<string name="upload_file_dialog_filename">Tiedostonimi</string>
<string name="upload_file_dialog_filetype">Tiedostotyyppi</string>
<string name="upload_file_dialog_filetype_googlemap_shortcut">Google Maps -pikakuvaketiedosto(%s)</string>
<string name="upload_file_dialog_filetype_internet_shortcut">Internet-pikakuvaketiedosto(%s)</string>
<string name="upload_file_dialog_filetype_snippet_text">Lohkon tekstitiedosto (.txt)</string>
<string name="upload_file_dialog_title">Anna lhetettv tiedostonimi ja -tyyppi</string>
<string name="upload_files">Lhet tiedostoja</string>
<string name="upload_item_action_button">Lataa tiedosto nappi</string>
<string name="upload_list_delete">Poista</string>
<string name="upload_list_empty_headline">Ei lhetettvi saatavilla</string>
<string name="upload_list_empty_text_auto_upload">Lhet sislt tai aktivoi automaattinen lhetys.</string>
<string name="upload_list_resolve_conflict">Selvit virhetilanne</string>
<string name="upload_local_storage_full">Paikallinen tallennustila tynn</string>
<string name="upload_local_storage_not_copied">Tiedostoa ei voitu kopioida paikalliseen tallennustilaan</string>
<string name="upload_lock_failed">Kansion lukitseminen eponnistui</string>
<string name="upload_manually_cancelled">Kyttj peruutti latauksen</string>
<string name="upload_old_android">Salaus on mahdollista vain kun >= Android 5.0</string>
<string name="upload_query_move_foreign_files">Riittmtn tila est tiedostojen kopioinnin %1$s kansioon. Haluatko sen sijaan siirt ne sinne?</string>
<string name="upload_scan_doc_upload">Skannaa asiakirja kameralla</string>
<string name="upload_sync_conflict">Konflikti synkronoinnissa, ratkaise manuaalisesti</string>
<string name="upload_unknown_error">Tuntematon virhe</string>
<string name="uploader_btn_alternative_text">Valitse</string>
<string name="uploader_btn_upload_text">Lhet</string>
<string name="uploader_error_message_no_file_to_upload">Vastaanotettu data ei sisll kelvollista tiedostoa.</string>
<string name="uploader_error_message_read_permission_not_granted">%1$s ei saa lukea vastaanotettua tiedostoa</string>
<string name="uploader_error_message_source_file_not_copied">Virhe kopioitaessa tiedostoa vliaikaiseen kansioon. Yrit lhett se uudelleen.</string>
<string name="uploader_error_message_source_file_not_found">Lhetykseen valittua tiedostoa ei lytynyt. Varmista, ett tiedosto on olemassa.</string>
<string name="uploader_error_title_file_cannot_be_uploaded">Tt tiedostoa ei voida lhett</string>
<string name="uploader_error_title_no_file_to_upload">Ei lhetettv tiedostoa</string>
<string name="uploader_info_dirname">Kansion nimi</string>
<string name="uploader_top_message">Valitse lhetyskansio</string>
<string name="uploader_upload_failed_content_single">Ei voitu lhett %1$s</string>
<string name="uploader_upload_failed_credentials_error">Lhettminen eponnistui, kirjaudu sisn uudelleen</string>
<string name="uploader_upload_failed_sync_conflict_error">Tiedoston lhetyksen virhetilanne</string>
<string name="uploader_upload_failed_sync_conflict_error_content">Valitse mik nist versioista pidetn %1$s</string>
<string name="uploader_upload_failed_ticker">Lhetys eponnistui</string>
<string name="uploader_upload_files_behaviour">Lhetysasetus:</string>
<string name="uploader_upload_files_behaviour_move_to_nextcloud_folder">Siirr tiedosto %1$s kansioon</string>
<string name="uploader_upload_files_behaviour_not_writable">lhdekansio on vain lukuoikeus; tiedosto ladataan palvelimelle, ei muuta</string>
<string name="uploader_upload_files_behaviour_only_upload">Pid tiedosto lhdekansiossa</string>
<string name="uploader_upload_files_behaviour_upload_and_delete_from_source">Poista tiedosto lhdekansiosta</string>
<string name="uploader_upload_forbidden_permissions">lhett thn kansioon</string>
<string name="uploader_upload_in_progress_content">%1$d%% Lhetetn palvelimelle %2$s</string>
<string name="uploader_upload_in_progress_ticker">Lhetetn</string>
<string name="uploader_upload_succeeded_content_single">%1$s lhetetty</string>
<string name="uploader_wrn_no_account_quit_btn_text">Lopeta</string>
<string name="uploader_wrn_no_account_setup_btn_text">Asetukset</string>
<string name="uploader_wrn_no_account_text">Laitteellasi ei ole %1$s-tilej. Mrit tilin asetukset ensin.</string>
<string name="uploader_wrn_no_account_title">Tili ei lytynyt</string>
<string name="uploads_view_group_current_uploads">Nykyiset</string>
<string name="uploads_view_group_failed_uploads">Eponnistuneet/odottaa uudelleenlhetyst</string>
<string name="uploads_view_group_finished_uploads">Lhetetty</string>
<string name="uploads_view_group_manually_cancelled_uploads">Peruttu</string>
<string name="uploads_view_later_waiting_to_upload">Odottaa siirtoa</string>
<string name="uploads_view_title">Lhetykset</string>
<string name="uploads_view_upload_status_cancelled">Peruttu</string>
<string name="uploads_view_upload_status_conflict">Ristiriita</string>
<string name="uploads_view_upload_status_failed_connection_error">Yhteysvirhe</string>
<string name="uploads_view_upload_status_failed_credentials_error">Valtuutusvirhe</string>
<string name="uploads_view_upload_status_failed_file_error">Tiedostovirhe</string>
<string name="uploads_view_upload_status_failed_folder_error">Kansiovirhe</string>
<string name="uploads_view_upload_status_failed_localfile_error">Paikallista tiedostoa ei lydy</string>
<string name="uploads_view_upload_status_failed_permission_error">Oikeusvirhe</string>
<string name="uploads_view_upload_status_failed_ssl_certificate_not_trusted">Ei-luotettu palvelinvarmenne</string>
<string name="uploads_view_upload_status_fetching_server_version">Noudetaan palvelimen versiota</string>
<string name="uploads_view_upload_status_service_interrupted">Sovellus suljettiin</string>
<string name="uploads_view_upload_status_succeeded">Valmiina</string>
<string name="uploads_view_upload_status_unknown_fail">Tuntematon virhe</string>
<string name="uploads_view_upload_status_virus_detected">Virus havaittu. Lhetyst ei voi suorittaa loppuun!</string>
<string name="uploads_view_upload_status_waiting_exit_power_save_mode">Odotetaan virranssttilasta poistumista</string>
<string name="uploads_view_upload_status_waiting_for_charging">Odotetaan latausta</string>
<string name="uploads_view_upload_status_waiting_for_wifi">Odotetaan laskuttamatonta Wi-Fi-yhteytt</string>
<string name="user_icon">Kyttj</string>
<string name="user_info_address">Osoite</string>
<string name="user_info_email">Shkposti</string>
<string name="user_info_phone">Puhelinnumero</string>
<string name="user_info_twitter">Twitter</string>
<string name="user_info_website">Verkkosivusto</string>
<string name="user_information_retrieval_error">Virhe kyttjn tietoja haettaessa</string>
<string name="userinfo_no_info_headline">Henkilkohtaisia tietoja ei ole asetettu</string>
<string name="userinfo_no_info_text">Lis nimi, kuva ja yhteystiedot profiilisivullasi.</string>
<string name="username">Kyttjtunnus</string>
<string name="version_dev_download">Lataa</string>
<string name="video_overlay_icon">Videon peittokuva -kuvake</string>
<string name="wait_a_moment">Odota hetki</string>
<string name="wait_checking_credentials">Tarkistetaan tallennettuja tilitietoja</string>
<string name="wait_for_tmp_copy_from_private_storage">Kopioidaan tiedostoa yksityisest tallennustilasta</string>
<string name="webview_version_check_alert_dialog_positive_button_title">Pivit</string>
<string name="what_s_new_image">Mit uutta -kuva</string>
<string name="whats_new_skip">Ohita</string>
<string name="whats_new_title">Uutta versiossa %1$s</string>
<string name="whats_your_status">Mik on tilatietosi?</string>
<string name="widgets_not_available_title">Ei saatavilla</string>
<string name="worker_download">Ladataan tiedostoja</string>
<string name="write_email">Lhet shkposti</string>
<string name="wrong_storage_path">Tiedostokansiota ei ole olemassa!</string>
<string name="wrong_storage_path_desc">Tm voi johtua varmuuskopion palautuksesta toisella laitteella. Palautetaan oletusasetukset. Tarkista tiedostokansion asetukset.</string>
<plurals name="sync_fail_in_favourites_content">
<item quantity="one">Ei voitu synkronoida %1$d tiedosto (ristiriita: %2$d)</item>
<item quantity="other">Ei voitu synkronoida %1$d tiedostoa (ristiriidat: %2$d)</item>
</plurals>
<plurals name="sync_foreign_files_forgotten_content">
<item quantity="one">Ei onnistuttu kopioimaan %1$d tiedostoa %2$s kansioon</item>
<item quantity="other">Ei onnistuttu kopioimaan %1$d tiedostoja %2$s kansioon</item>
</plurals>
<plurals name="processed_n_entries">
<item quantity="one">Ksiteltiin %d kohde</item>
<item quantity="other">Ksiteltiin %d kohdetta</item>
</plurals>
<plurals name="found_n_duplicates">
<item quantity="one">Lytyi %d kaksoiskappale.</item>
<item quantity="other">Lytyi %d kaksoiskappaletta.</item>
</plurals>
<plurals name="export_successful">
<item quantity="one">Vietiin %d tiedosto </item>
<item quantity="other">Vietiin %d tiedostoa</item>
</plurals>
<plurals name="export_failed">
<item quantity="one">%d tiedoston vienti eponnistui</item>
<item quantity="other">%d tiedoston vienti eponnistui</item>
</plurals>
<plurals name="export_partially_failed">
<item quantity="one">Viety %d tiedosto, loput ohitettu virheen vuoksi</item>
<item quantity="other">Viety %d tiedostoa, loput ohitettu virheen vuoksi</item>
</plurals>
<plurals name="export_start">
<item quantity="one">Viedn %d tiedosto. Katso ilmoituksesta listietoja.</item>
<item quantity="other">Viedn %d tiedostoa. Katso ilmoituksesta listietoja.</item>
</plurals>
<plurals name="file_list__footer__folder">
<item quantity="one">%1$d kansio</item>
<item quantity="other">%1$d kansiota</item>
</plurals>
<plurals name="file_list__footer__file">
<item quantity="one">%1$d tiedosto</item>
<item quantity="other">%1$d tiedostoa</item>
</plurals>
<plurals name="synced_folders_show_hidden_folders">
<item quantity="one">Nyt %1$d piilotettu kansio</item>
<item quantity="other">Nyt %1$d piilotettua kansiota</item>
</plurals>
<plurals name="items_selected_count">
<item quantity="one">%d valittu</item>
<item quantity="other">%d valittu</item>
</plurals>
</resources>
``` | /content/code_sandbox/app/src/main/res/values-fi-rFI/strings.xml | xml | 2016-06-06T21:23:36 | 2024-08-16T18:22:36 | android | nextcloud/android | 4,122 | 22,105 |
```xml
import React from 'react'
import Layout from '../components/Layout'
import { Seo } from '../components/Seo'
import { DescriptionBlock } from '../components/styled'
const NotFoundPage = () => (
<Layout>
<Seo title="404: Not found" />
<div className="guide__header">
<h1>Not Found</h1>
</div>
<DescriptionBlock>
<p>You just hit a route that doesn't exist... the sadness.</p>
</DescriptionBlock>
</Layout>
)
export default NotFoundPage
``` | /content/code_sandbox/website/src/pages/404.tsx | xml | 2016-04-16T03:27:56 | 2024-08-16T03:38:37 | nivo | plouc/nivo | 13,010 | 124 |
```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.
-->
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<include layout="@layout/design_content_appbar_toolbar_collapse_pin"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|left"
android:clickable="true"
app:layout_insetEdge="left"
app:srcCompat="@drawable/vector_icon"
tools:ignore="RtlHardcoded"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|left"
android:clickable="true"
app:layout_dodgeInsetEdges="left"
app:srcCompat="@drawable/vector_icon"
tools:ignore="RtlHardcoded"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
``` | /content/code_sandbox/testing/java/com/google/android/material/testapp/res/layout/design_appbar_dodge_left.xml | xml | 2016-12-05T16:11:29 | 2024-08-16T17:51:42 | material-components-android | material-components/material-components-android | 16,176 | 337 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.10" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.10" />
<PackageReference Include="coverlet.collector" Version="3.2.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="Xunit.Extensions.Ordering" Version="1.4.5" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TransferUtilityBasics\TransferUtilityBasics.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="testsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="testsettings.*.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DependentUpon>testsettings.json</DependentUpon>
</Content>
</ItemGroup>
<ItemGroup>
<None Update="DownloadTest.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="TransferFolderTest\DownloadTest.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="TransferFolderTest\UploadFolder\UploadTest.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="TransferFolderTest\UploadTest.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="UploadTest.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
``` | /content/code_sandbox/dotnetv3/S3/scenarios/TransferUtilityBasics/TransferUtilityBasicsTests/TransferUtilityBasicsTests.csproj | xml | 2016-08-18T19:06:57 | 2024-08-16T18:59:44 | aws-doc-sdk-examples | awsdocs/aws-doc-sdk-examples | 9,298 | 650 |
```xml
import { useHandler } from '@proton/components';
import {
conversationCountsActions,
messageCountsActions,
selectConversationCounts,
selectMessageCounts,
} from '@proton/mail';
import type { LabelCount } from '@proton/shared/lib/interfaces/Label';
import isTruthy from '@proton/utils/isTruthy';
import { useMailDispatch, useMailStore } from 'proton-mail/store/hooks';
import { replaceCounter } from '../../helpers/counter';
import { isConversation, isUnread } from '../../helpers/elements';
import type { Element } from '../../models/element';
import {
optimisticDelete as optimisticDeleteConversationAction,
optimisticDeleteConversationMessages,
optimisticRestore as optimisticRestoreConversationsAction,
} from '../../store/conversations/conversationsActions';
import type { ConversationState } from '../../store/conversations/conversationsTypes';
import {
optimisticDelete as optimisticDeleteElementAction,
optimisticRestoreDelete as optimisticRestoreDeleteElementAction,
} from '../../store/elements/elementsActions';
import type { MessageState } from '../../store/messages/messagesTypes';
import {
optimisticDelete as optimisticDeleteMessageAction,
optimisticRestore as optimisticRestoreMessageAction,
} from '../../store/messages/optimistic/messagesOptimisticActions';
import { useGetAllConversations } from '../conversation/useConversation';
import { useGetElementByID } from '../mailbox/useElements';
import { useGetMessage } from '../message/useMessage';
const useOptimisticDelete = () => {
const store = useMailStore();
const dispatch = useMailDispatch();
const getElementByID = useGetElementByID();
const getAllConversations = useGetAllConversations();
const getMessage = useGetMessage();
return useHandler((elements: Element[], labelID: string) => {
const elementIDs = elements.map(({ ID }) => ID || '');
const conversationMode = isConversation(elements[0]);
const total = elementIDs.length;
const totalUnread = elements.filter((element) => isUnread(element, labelID)).length;
const rollbackMessages = [] as MessageState[];
const rollbackConversations = [] as ConversationState[];
const rollbackCounters = {} as { [key: string]: LabelCount };
// Message cache
elementIDs.forEach((elementID) => {
const message = getMessage(elementID);
if (message) {
rollbackMessages.push(message);
}
});
dispatch(optimisticDeleteMessageAction(elementIDs));
// Conversation cache
const allConversations = getAllConversations();
allConversations.forEach((conversation) => {
if (conversation?.Conversation.ID && elementIDs.includes(conversation?.Conversation.ID)) {
dispatch(optimisticDeleteConversationAction(conversation?.Conversation.ID));
rollbackConversations.push(conversation);
} else if (conversation?.Messages) {
const messages = conversation.Messages?.filter((message) => !elementIDs.includes(message.ID));
if (conversation && messages?.length !== conversation?.Messages?.length) {
dispatch(optimisticDeleteConversationMessages({ ID: conversation.Conversation.ID, messages }));
rollbackConversations.push(conversation);
}
}
});
// Elements cache
const rollbackElements = elementIDs.map((elementID) => getElementByID(elementID)).filter(isTruthy);
dispatch(optimisticDeleteElementAction({ elementIDs }));
if (conversationMode) {
let { value: conversationCounters = [] } = selectConversationCounts(store.getState());
// Conversation counters
const currentConversationCounter = conversationCounters.find(
(counter: any) => counter.LabelID === labelID
) as LabelCount;
rollbackCounters.conversations = currentConversationCounter;
store.dispatch(
conversationCountsActions.set(
replaceCounter(conversationCounters, {
LabelID: labelID,
Total: (currentConversationCounter.Total || 0) - total,
Unread: (currentConversationCounter.Unread || 0) - totalUnread,
})
)
);
} else {
let { value: messageCounters = [] } = selectMessageCounts(store.getState());
// Message counters
const currentMessageCounter = messageCounters.find(
(counter: any) => counter.LabelID === labelID
) as LabelCount;
rollbackCounters.messages = currentMessageCounter;
store.dispatch(
messageCountsActions.set(
replaceCounter(messageCounters, {
LabelID: labelID,
Total: (currentMessageCounter.Total || 0) - total,
Unread: (currentMessageCounter.Unread || 0) - totalUnread,
})
)
);
}
return () => {
dispatch(optimisticRestoreMessageAction(rollbackMessages));
dispatch(optimisticRestoreConversationsAction(rollbackConversations));
dispatch(optimisticRestoreDeleteElementAction({ elements: rollbackElements }));
if (rollbackCounters.conversations) {
let { value: conversationCounters = [] } = selectConversationCounts(store.getState());
store.dispatch(
conversationCountsActions.set(replaceCounter(conversationCounters, rollbackCounters.conversations))
);
}
if (rollbackCounters.messages) {
let { value: messageCounters = [] } = selectMessageCounts(store.getState());
store.dispatch(messageCountsActions.set(replaceCounter(messageCounters, rollbackCounters.messages)));
}
};
});
};
export default useOptimisticDelete;
``` | /content/code_sandbox/applications/mail/src/app/hooks/optimistic/useOptimisticDelete.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,124 |
```xml
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at path_to_url
*/
import {WorkspacePath} from '../../update-tool/file-system';
import {ResolvedResource} from '../../update-tool/component-resource-collector';
import {Migration} from '../../update-tool/migration';
import {OutputNameUpgradeData} from '../data';
import {findOutputsOnElementWithAttr, findOutputsOnElementWithTag} from '../html-parsing/angular';
import {getVersionUpgradeData, UpgradeData} from '../upgrade-data';
/**
* Migration that walks through every inline or external HTML template and switches
* changed output binding names to the proper new output name.
*/
export class OutputNamesMigration extends Migration<UpgradeData> {
/** Change data that upgrades to the specified target version. */
data: OutputNameUpgradeData[] = getVersionUpgradeData(this, 'outputNames');
// Only enable the migration rule if there is upgrade data.
enabled = this.data.length !== 0;
override visitTemplate(template: ResolvedResource): void {
this.data.forEach(name => {
const limitedTo = name.limitedTo;
const relativeOffsets: number[] = [];
if (limitedTo.attributes) {
relativeOffsets.push(
...findOutputsOnElementWithAttr(template.content, name.replace, limitedTo.attributes),
);
}
if (limitedTo.elements) {
relativeOffsets.push(
...findOutputsOnElementWithTag(template.content, name.replace, limitedTo.elements),
);
}
relativeOffsets
.map(offset => template.start + offset)
.forEach(start =>
this._replaceOutputName(template.filePath, start, name.replace.length, name.replaceWith),
);
});
}
private _replaceOutputName(
filePath: WorkspacePath,
start: number,
width: number,
newName: string,
) {
this.fileSystem.edit(filePath).remove(start, width).insertRight(start, newName);
}
}
``` | /content/code_sandbox/src/cdk/schematics/ng-update/migrations/output-names.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 418 |
```xml
import * as pulumi from '@pulumi/pulumi'
class CustomResource extends pulumi.dynamic.Resource {
constructor (name: string, opts?: pulumi.ResourceOptions) {
super(new DummyResourceProvider(), name, {}, opts, "custom-provider", "CustomResource")
}
}
class DummyResourceProvider implements pulumi.dynamic.ResourceProvider {
async create (props: any): Promise<pulumi.dynamic.CreateResult> {
var config = JSON.parse(process.env.PULUMI_CONFIG)
return { id: config["id"], outs: {} }
}
}
const resource = new CustomResource('resource-name')
export const rid = resource.id
``` | /content/code_sandbox/tests/integration/dynamic/nodejs-pulumi-config/index.ts | xml | 2016-10-31T21:02:47 | 2024-08-16T19:47:04 | pulumi | pulumi/pulumi | 20,743 | 131 |
```xml
import { isEnabled } from "@erxes/ui/src/utils/core";
export const commonMutationVariables = `
$parentId: String,
$proccessId: String,
$aboveItemId: String,
$stageId: String,
$startDate: Date,
$closeDate: Date,
$description: String,
$assignedUserIds: [String],
$order: Int,
$attachments: [AttachmentInput],
$reminderMinute: Int,
$isComplete: Boolean,
$status: String,
$priority: String,
$sourceConversationIds: [String],
$customFieldsData: JSON,
$tagIds: [String]
$branchIds:[String],
$departmentIds:[String]
`;
export const commonMutationParams = `
parentId: $parentId,
proccessId: $proccessId,
aboveItemId: $aboveItemId,
stageId: $stageId,
startDate: $startDate,
closeDate: $closeDate,
description: $description,
assignedUserIds: $assignedUserIds,
order: $order,
attachments: $attachments,
reminderMinute: $reminderMinute,
isComplete: $isComplete,
status: $status,
priority: $priority,
sourceConversationIds: $sourceConversationIds,
customFieldsData: $customFieldsData,
tagIds: $tagIds
branchIds: $branchIds
departmentIds: $departmentIds
`;
export const commonDragVariables = `
$itemId: String!,
$aboveItemId: String,
$destinationStageId: String!,
$sourceStageId: String,
$proccessId: String
`;
export const commonDragParams = `
itemId: $itemId,
aboveItemId: $aboveItemId,
destinationStageId: $destinationStageId,
sourceStageId: $sourceStageId,
proccessId: $proccessId
`;
export const commonListFields = `
_id
name
companies
customers
assignedUsers
labels
stage
isComplete
isWatched
relations
startDate
closeDate
createdAt
modifiedAt
priority
hasNotified
score
number
tagIds
customProperties
status
`;
export const commonFields = `
_id
name
stageId
hasNotified
pipeline {
_id
name
tagId
isCheckDate
tag {
order
}
}
boardId
... @defer {
companies {
_id
primaryName
links
}
}
... @defer {
customers {
_id
firstName
middleName
lastName
primaryEmail
primaryPhone
visitorContactInfo
}
}
tags {
_id
name
colorCode
}
tagIds
startDate
closeDate
description
priority
assignedUsers {
_id
username
email
isActive
details {
avatar
fullName
}
}
labels {
_id
name
colorCode
}
labelIds
stage {
probability
type
defaultTick
}
isWatched
attachments {
name
url
type
size
}
createdAt
modifiedAt
modifiedBy
reminderMinute
isComplete
status
createdUser {
_id
details {
fullName
avatar
}
}
order
customFieldsData
score
timeTrack {
status
timeSpent
startDate
}
number
customProperties
branchIds
departmentIds
`;
const pipelinesWatch = `
mutation purchasesPipelinesWatch($_id: String!, $isAdd: Boolean, $type: String!) {
purchasesPipelinesWatch(_id: $_id, isAdd: $isAdd, type: $type) {
_id
isWatched
}
}
`;
const stagesEdit = `
mutation purchasesStagesEdit($_id: String!, $type: String, $name: String, $status: String) {
purchasesStagesEdit(_id: $_id, type: $type, name: $name, status: $status) {
_id
}
}
`;
const stagesRemove = `
mutation purchasesStagesRemove($_id: String!) {
purchasesStagesRemove(_id: $_id)
}
`;
const boardItemUpdateTimeTracking = `
mutation purchasesBoardItemUpdateTimeTracking($_id: String!, $type: String!, $status: String!, $timeSpent: Int! $startDate: String) {
purchasesBoardItemUpdateTimeTracking(_id: $_id, type: $type, status: $status, timeSpent: $timeSpent, startDate: $startDate)
}
`;
const stagesSortItems = `
mutation purchasesStagesSortItems($stageId: String!, $type: String, $proccessId: String, $sortType: String) {
purchasesStagesSortItems(stageId: $stageId, type: $type, proccessId: $proccessId, sortType: $sortType)
}
`;
const pipelineLabelsAdd = `
mutation purchasesPipelineLabelsAdd($name: String!, $colorCode: String!, $pipelineId: String!) {
purchasesPipelineLabelsAdd(name: $name, colorCode: $colorCode, pipelineId: $pipelineId) {
_id
}
}
`;
const pipelineLabelsEdit = `
mutation purchasesPipelineLabelsEdit($_id: String!, $name: String!, $colorCode: String!, $pipelineId: String!) {
purchasesPipelineLabelsEdit(_id: $_id, name: $name, colorCode: $colorCode, pipelineId: $pipelineId) {
_id
}
}
`;
const pipelineLabelsRemove = `
mutation purchasesPipelineLabelsRemove($_id: String!) {
purchasesPipelineLabelsRemove(_id: $_id)
}
`;
const pipelineLabelsLabel = `
mutation purchasesPipelineLabelsLabel($pipelineId: String!, $targetId: String!, $labelIds: [String!]!) {
purchasesPipelineLabelsLabel(pipelineId: $pipelineId, targetId: $targetId, labelIds: $labelIds)
}
`;
const boardItemsSaveForGanttTimeline = `
mutation purchasesBoardItemsSaveForGanttTimeline($items: JSON, $links: JSON, $type: String!) {
purchasesBoardItemsSaveForGanttTimeline(items: $items, links: $links, type: $type)
}
`;
const stagesUpdateOrder = `
mutation purchasesStagesUpdateOrder($orders: [PurchasesOrderItem]) {
purchasesStagesUpdateOrder(orders: $orders) {
_id
}
}
`;
const conversationConvertToCard = `
mutation conversationConvertToCard(
$_id: String!
$type: String!
$assignedUserIds: [String]
$attachments: [AttachmentInput]
$bookingProductId: String
$closeDate: Date
$customFieldsData: JSON
$description: String
$itemId: String
$itemName: String
$labelIds: [String]
$priority: String
$stageId: String
$startDate: Date
) {
conversationConvertToCard(
_id: $_id
type: $type
assignedUserIds: $assignedUserIds
attachments: $attachments
bookingProductId: $bookingProductId
closeDate: $closeDate
customFieldsData: $customFieldsData
description: $description
itemId: $itemId
itemName: $itemName
labelIds: $labelIds
priority: $priority
stageId: $stageId
startDate: $startDate
)
}
`;
export default {
pipelinesWatch,
stagesEdit,
stagesRemove,
boardItemUpdateTimeTracking,
stagesSortItems,
pipelineLabelsAdd,
pipelineLabelsEdit,
pipelineLabelsRemove,
pipelineLabelsLabel,
boardItemsSaveForGanttTimeline,
stagesUpdateOrder,
conversationConvertToCard
};
``` | /content/code_sandbox/packages/ui-purchases/src/boards/graphql/mutations.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,766 |
```xml
import { c } from 'ttag';
import clsx from '@proton/utils/clsx';
import noop from '@proton/utils/noop';
import type { MessageState } from '../../../store/messages/messagesTypes';
import RecipientItem from '../../message/recipients/RecipientItem';
import RecipientType from '../../message/recipients/RecipientType';
interface Props {
message: MessageState;
}
const EOReplyHeader = ({ message }: Props) => {
const subject = message.data?.Subject;
return (
<>
<div className="flex items-center px-7 py-5">
<h1 className="eo-layout-title text-ellipsis m-0 mb-2" title={subject}>
{subject}
</h1>
</div>
<div className="message-header eo-message-header message-header-expanded is-outbound border-top border-bottom px-7 py-4">
<RecipientType label={c('Label').t`From:`} className={clsx(['flex items-start flex-nowrap mb-3'])}>
<RecipientItem
recipientOrGroup={{ recipient: message.data?.EORecipient }}
isLoading={false}
isOutside
onContactDetails={noop}
onContactEdit={noop}
/>
</RecipientType>
<RecipientType
label={c('Label').t`To:`}
className={clsx(['flex items-start flex-nowrap message-recipient-expanded'])}
>
<RecipientItem
recipientOrGroup={{ recipient: message.data?.Sender }}
isLoading={false}
isOutside
onContactDetails={noop}
onContactEdit={noop}
/>
</RecipientType>
</div>
</>
);
};
export default EOReplyHeader;
``` | /content/code_sandbox/applications/mail/src/app/components/eo/reply/EOReplyHeader.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 363 |
```xml
import * as React from 'react';
import createSvgIcon from '../utils/createSvgIcon';
const CheckboxCompositeReversedIcon = createSvgIcon({
svg: ({ classes }) => (
<svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false">
<path d="M2048 0v2048H0V0h2048zm-339 685l-90-90-851 850-339-338-90 90 429 430 941-942z" />
</svg>
),
displayName: 'CheckboxCompositeReversedIcon',
});
export default CheckboxCompositeReversedIcon;
``` | /content/code_sandbox/packages/react-icons-mdl2/src/components/CheckboxCompositeReversedIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 148 |
```xml
/// <reference types="./types/global" />
/// <reference types="./types/react-native-web" />
/// <reference types="./types/metro-require" />
``` | /content/code_sandbox/packages/expo-router/index.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 33 |
```xml
import { IntegrationLogger } from '@botpress/sdk/dist/integration/logger'
import Stripe from 'stripe'
import { Client } from '.botpress'
import { Events } from '.botpress/implementation/events'
export const fireChargeFailed = async ({
stripeEvent,
client,
logger,
}: {
stripeEvent: Stripe.ChargeFailedEvent
client: Client
logger: IntegrationLogger
}) => {
const { user } = await client.getOrCreateUser({
tags: {
id:
typeof stripeEvent.data.object.customer === 'string'
? stripeEvent.data.object.customer
: stripeEvent.data.object.customer?.id || '',
},
})
logger.forBot().debug('Triggering charge failed event')
const payload = {
origin: 'stripe',
userId: user.id,
data: { type: stripeEvent.type, object: { ...stripeEvent.data.object } },
} satisfies Events['chargeFailed']
await client.createEvent({
type: 'chargeFailed',
payload,
})
}
``` | /content/code_sandbox/integrations/stripe/src/events/charge-failed.ts | xml | 2016-11-16T21:57:59 | 2024-08-16T18:45:35 | botpress | botpress/botpress | 12,401 | 217 |
```xml
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { StorageComponent } from './storage.component';
describe('StorageComponent', () => {
let component: StorageComponent;
let fixture: ComponentFixture<StorageComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [ StorageComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(StorageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
``` | /content/code_sandbox/samples/modular/src/app/storage/storage.component.spec.ts | xml | 2016-01-11T20:47:23 | 2024-08-14T12:09:31 | angularfire | angular/angularfire | 7,648 | 121 |
```xml
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at path_to_url
*/
import {
ComponentHarnessConstructor,
ContentContainerComponentHarness,
HarnessLoader,
HarnessPredicate,
} from '@angular/cdk/testing';
import {TabHarnessFilters} from './tab-harness-filters';
/** Harness for interacting with an Angular Material tab in tests. */
export class MatTabHarness extends ContentContainerComponentHarness<string> {
/** The selector for the host element of a `MatTab` instance. */
static hostSelector = '.mat-mdc-tab';
/**
* Gets a `HarnessPredicate` that can be used to search for a tab with specific attributes.
* @param options Options for filtering which tab instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatTabHarness>(
this: ComponentHarnessConstructor<T>,
options: TabHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options)
.addOption('label', options.label, (harness, label) =>
HarnessPredicate.stringMatches(harness.getLabel(), label),
)
.addOption(
'selected',
options.selected,
async (harness, selected) => (await harness.isSelected()) == selected,
);
}
/** Gets the label of the tab. */
async getLabel(): Promise<string> {
return (await this.host()).text();
}
/** Gets the aria-label of the tab. */
async getAriaLabel(): Promise<string | null> {
return (await this.host()).getAttribute('aria-label');
}
/** Gets the value of the "aria-labelledby" attribute. */
async getAriaLabelledby(): Promise<string | null> {
return (await this.host()).getAttribute('aria-labelledby');
}
/** Whether the tab is selected. */
async isSelected(): Promise<boolean> {
const hostEl = await this.host();
return (await hostEl.getAttribute('aria-selected')) === 'true';
}
/** Whether the tab is disabled. */
async isDisabled(): Promise<boolean> {
const hostEl = await this.host();
return (await hostEl.getAttribute('aria-disabled')) === 'true';
}
/** Selects the given tab by clicking on the label. Tab cannot be selected if disabled. */
async select(): Promise<void> {
await (await this.host()).click('center');
}
/** Gets the text content of the tab. */
async getTextContent(): Promise<string> {
const contentId = await this._getContentId();
const contentEl = await this.documentRootLocatorFactory().locatorFor(`#${contentId}`)();
return contentEl.text();
}
protected override async getRootHarnessLoader(): Promise<HarnessLoader> {
const contentId = await this._getContentId();
return this.documentRootLocatorFactory().harnessLoaderFor(`#${contentId}`);
}
/** Gets the element id for the content of the current tab. */
private async _getContentId(): Promise<string> {
const hostEl = await this.host();
// Tabs never have an empty "aria-controls" attribute.
return (await hostEl.getAttribute('aria-controls'))!;
}
}
``` | /content/code_sandbox/src/material/tabs/testing/tab-harness.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 701 |
```xml
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:pathData="M12,2C6.47,2 2,6.47 2,12c0,5.53 4.47,10 10,10s10,-4.47 10,-10C22,6.47 17.53,2 12,2zM12,20c-4.42,0 -8,-3.58 -8,-8c0,-4.42 3.58,-8 8,-8s8,3.58 8,8C20,16.42 16.42,20 12,20z"
android:fillColor="@android:color/white" />
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_circle_outline_24dp.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 204 |
```xml
import { ComponentRegistry } from './ComponentRegistry';
import { Store } from './Store';
import { mock, instance, verify, anyFunction } from 'ts-mockito';
import { ComponentWrapper } from './ComponentWrapper';
import { ComponentEventsObserver } from '../events/ComponentEventsObserver';
import { AppRegistryService } from '../adapters/AppRegistryService';
import { ComponentProvider } from 'react-native';
const DummyComponent = () => null;
describe('ComponentRegistry', () => {
let mockedStore: Store;
let mockedComponentEventsObserver: ComponentEventsObserver;
let mockedComponentWrapper: ComponentWrapper;
let mockedAppRegistryService: AppRegistryService;
let componentWrapper: ComponentWrapper;
let store: Store;
let uut: ComponentRegistry;
beforeEach(() => {
mockedStore = mock(Store);
mockedComponentEventsObserver = mock(ComponentEventsObserver);
mockedComponentWrapper = mock(ComponentWrapper);
mockedAppRegistryService = mock(AppRegistryService);
store = instance(mockedStore);
componentWrapper = instance(mockedComponentWrapper);
uut = new ComponentRegistry(
store,
instance(mockedComponentEventsObserver),
componentWrapper,
instance(mockedAppRegistryService)
);
});
it('registers component by componentName into AppRegistry', () => {
uut.registerComponent('example.MyComponent.name', () => DummyComponent);
verify(
mockedAppRegistryService.registerComponent('example.MyComponent.name', anyFunction())
).called();
});
it('saves the wrapper component generator to the store', () => {
uut.registerComponent('example.MyComponent.name', () => DummyComponent);
verify(
mockedStore.setComponentClassForName('example.MyComponent.name', anyFunction())
).called();
});
it('should not invoke generator', () => {
const generator: ComponentProvider = jest.fn(() => DummyComponent);
uut.registerComponent('example.MyComponent.name', generator);
expect(generator).toHaveBeenCalledTimes(0);
});
it('should wrap component only once', () => {
uut = new ComponentRegistry(
new Store(),
instance(mockedComponentEventsObserver),
componentWrapper,
instance(mockedAppRegistryService)
);
componentWrapper.wrap = jest.fn();
const generator: ComponentProvider = jest.fn(() => DummyComponent);
const componentProvider = uut.registerComponent('example.MyComponent.name', generator);
componentProvider();
componentProvider();
expect(componentWrapper.wrap).toHaveBeenCalledTimes(1);
});
it('should recreate wrapped component on re-register component', () => {
uut = new ComponentRegistry(
new Store(),
instance(mockedComponentEventsObserver),
new ComponentWrapper(),
instance(mockedAppRegistryService)
);
const generator: ComponentProvider = () => DummyComponent;
const w1 = uut.registerComponent('example.MyComponent.name', generator)();
const w2 = uut.registerComponent('example.MyComponent.name', generator)();
expect(w1).not.toBe(w2);
});
});
``` | /content/code_sandbox/lib/src/components/ComponentRegistry.test.tsx | xml | 2016-03-11T11:22:54 | 2024-08-15T09:05:44 | react-native-navigation | wix/react-native-navigation | 13,021 | 634 |
```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 { renderIcon } from '../icon.renderer.js';
import { IconShapeTuple } from '../interfaces/icon.interfaces.js';
const icon = {
outline:
'<path d="M26.64,25.27,19,17.53,19,3,25.21,9.4l-5.65,5.79L21,16.62l5.68-5.82a2,2,0,0,0,0-2.78L20.48,1.7A2.08,2.08,0,0,0,18.85,1,2,2,0,0,0,17,3V15.38L10.05,8.27A1,1,0,0,0,8.62,9.66L16.79,18,9.06,26a1,1,0,0,0,0,1.41,1,1,0,0,0,.7.29,1,1,0,0,0,.72-.31L17,20.68V33a2.07,2.07,0,0,0,.71,1.62A2,2,0,0,0,19,35a1.94,1.94,0,0,0,1.42-.6l6.23-6.38A2,2,0,0,0,26.64,25.27ZM19,33.05V20.29l6.21,6.36Z"/>',
solid:
'<path d="M26.52,24.52l-5.65-5.83-1.46-1.5v-12L23.79,9.7l-3.6,3.71,2.24,2.29,4.09-4.22a2.54,2.54,0,0,0,0-3.56L20.57,1.78A2.54,2.54,0,0,0,16.2,3.55V13.86l-5.53-5.7a1.6,1.6,0,1,0-2.3,2.23L15.75,18l-7,7.19a1.6,1.6,0,0,0,0,2.26,1.63,1.63,0,0,0,1.12.45,1.58,1.58,0,0,0,1.15-.49l5.11-5.27V32.45a2.53,2.53,0,0,0,1.59,2.36,2.44,2.44,0,0,0,.95.19,2.56,2.56,0,0,0,1.83-.77l5.95-6.15A2.54,2.54,0,0,0,26.52,24.52ZM19.4,30.83V21.77l4.39,4.53Z"/>',
};
export const bluetoothIconName = 'bluetooth';
export const bluetoothIcon: IconShapeTuple = [bluetoothIconName, renderIcon(icon)];
``` | /content/code_sandbox/packages/core/src/icon/shapes/bluetooth.ts | xml | 2016-09-29T17:24:17 | 2024-08-11T17:06:15 | clarity | vmware-archive/clarity | 6,431 | 752 |
```xml
import React, {useCallback, useMemo, useState} from 'react'
import {connect, ResolveThunks} from 'react-redux'
import {withSource} from 'src/CheckSources'
import {Source, NotificationAction} from 'src/types'
import {UserRole, User, Database} from 'src/types/influxAdmin'
import {notify as notifyAction} from 'src/shared/actions/notifications'
import {
changeShowRoles,
createUserAsync,
filterUsers as filterUsersAction,
} from 'src/admin/actions/influxdb'
import {
notifyDBUserNameInvalid,
notifyDBPasswordInvalid,
notifyDBUserNameExists,
} from 'src/shared/copy/notifications'
import AdminInfluxDBTabbedPage, {
hasRoleManagement,
isConnectedToLDAP,
} from './AdminInfluxDBTabbedPage'
import FancyScrollbar from 'src/shared/components/FancyScrollbar'
import NoEntities from 'src/admin/components/influxdb/NoEntities'
import UserRow from 'src/admin/components/UserRow'
import useDebounce from 'src/utils/useDebounce'
import useChangeEffect from 'src/utils/useChangeEffect'
import {ComponentSize, SlideToggle} from 'src/reusable_ui'
import {computeEffectiveUserDBPermissions} from '../../util/computeEffectiveDBPermissions'
import CreateUserDialog, {
validatePassword,
validateUserName,
} from '../../components/influxdb/CreateUserDialog'
import {withRouter, WithRouterProps} from 'react-router'
import MultiDBSelector from 'src/admin/components/influxdb/MultiDBSelector'
const validateUser = (
user: Pick<User, 'name' | 'password'>,
notify: NotificationAction
) => {
if (!validateUserName(user.name)) {
notify(notifyDBUserNameInvalid())
return false
}
if (!validatePassword(user.password)) {
notify(notifyDBPasswordInvalid())
return false
}
return true
}
const mapStateToProps = ({
adminInfluxDB: {databases, users, roles, selectedDBs, showRoles, usersFilter},
}) => ({
databases,
users,
roles,
selectedDBs,
showRoles,
usersFilter,
})
const mapDispatchToProps = {
filterUsers: filterUsersAction,
createUser: createUserAsync,
toggleShowRoles: changeShowRoles,
notify: notifyAction,
}
interface OwnProps {
source: Source
}
interface ConnectedProps {
databases: Database[]
users: User[]
roles: UserRole[]
selectedDBs: string[]
showRoles: boolean
usersFilter: string
}
type ReduxDispatchProps = ResolveThunks<typeof mapDispatchToProps>
type Props = WithRouterProps & OwnProps & ConnectedProps & ReduxDispatchProps
const UsersPage = ({
router,
source,
databases,
users,
roles,
selectedDBs,
showRoles,
usersFilter,
notify,
createUser,
filterUsers,
toggleShowRoles,
}: Props) => {
const [isEnterprise, usersPage] = useMemo(
() => [
hasRoleManagement(source),
`/sources/${source.id}/admin-influxdb/users`,
],
[source]
)
// database columns
const visibleDBNames = useMemo<string[]>(() => {
if (selectedDBs.includes('*')) {
return databases.map(db => db.name)
}
return selectedDBs
}, [databases, selectedDBs])
// effective permissions
const visibleUsers = useMemo(() => users.filter(x => !x.hidden), [users])
const userDBPermissions = useMemo(
() =>
computeEffectiveUserDBPermissions(visibleUsers, roles, visibleDBNames),
[visibleDBNames, visibleUsers, roles]
)
// filter users
const [filterText, setFilterText] = useState(usersFilter)
const changeFilterText = useCallback(e => setFilterText(e.target.value), [])
const debouncedFilterText = useDebounce(filterText, 200)
useChangeEffect(() => {
filterUsers(debouncedFilterText)
}, [debouncedFilterText])
const [createVisible, setCreateVisible] = useState(false)
const createNew = useCallback(
async (user: {name: string; password: string}) => {
if (users.some(x => x.name === user.name)) {
notify(notifyDBUserNameExists())
return
}
if (!validateUser(user, notify)) {
return
}
await createUser(source.links.users, user)
router.push(
`/sources/${source.id}/admin-influxdb/users/${encodeURIComponent(
user.name
)}`
)
},
[users, router, source, notify]
)
return (
<AdminInfluxDBTabbedPage activeTab="users" source={source}>
<CreateUserDialog
visible={createVisible}
setVisible={setCreateVisible}
create={createNew}
/>
<div className="panel panel-solid influxdb-admin">
<div className="panel-heading">
<div className="search-widget">
<input
type="text"
className="form-control input-sm"
placeholder={`Filter Users...`}
value={filterText}
onChange={changeFilterText}
data-test="user-filter--input"
/>
<span className="icon search" />
</div>
<MultiDBSelector />
{isEnterprise && (
<div className="hide-roles-toggle">
<SlideToggle
active={showRoles}
onChange={toggleShowRoles}
size={ComponentSize.ExtraSmall}
/>
Show Roles
</div>
)}
<div className="panel-heading--right">
<button
className="btn btn-sm btn-primary"
onClick={() => setCreateVisible(true)}
data-test="create-user--button"
>
<span className="icon plus" /> Create User
</button>
</div>
</div>
<div className="panel-body">
{visibleUsers.length ? (
<FancyScrollbar>
<table className="table v-center admin-table table-highlight admin-table--compact">
<thead>
<tr>
<th>User</th>
{showRoles && (
<th className="admin-table--left-offset">
{isEnterprise ? 'Roles' : 'Admin'}
</th>
)}
{visibleDBNames.length
? visibleDBNames.map(name => (
<th
className="admin-table__dbheader"
title={`effective permissions for db: ${name}`}
key={name}
>
{name}
</th>
))
: null}
</tr>
</thead>
<tbody>
{visibleUsers.map((user, userIndex) => (
<UserRow
key={user.name}
user={user}
page={`${usersPage}/${encodeURIComponent(
user.name || ''
)}`}
userDBPermissions={userDBPermissions[userIndex]}
allRoles={roles}
showRoles={showRoles}
hasRoles={isEnterprise}
/>
))}
</tbody>
</table>
</FancyScrollbar>
) : (
<NoEntities entities="Users" filtered={!!debouncedFilterText} />
)}
</div>
</div>
</AdminInfluxDBTabbedPage>
)
}
const UsersPageAvailable = (props: Props) => {
if (isConnectedToLDAP(props.source)) {
return (
<AdminInfluxDBTabbedPage activeTab="users" source={props.source}>
<div className="container-fluid">
Users are managed in LDAP directory.
</div>
</AdminInfluxDBTabbedPage>
)
}
return <UsersPage {...props} />
}
export default withSource(
withRouter(connect(mapStateToProps, mapDispatchToProps)(UsersPageAvailable))
)
``` | /content/code_sandbox/ui/src/admin/containers/influxdb/UsersPage.tsx | xml | 2016-08-24T23:28:56 | 2024-08-13T19:50:03 | chronograf | influxdata/chronograf | 1,494 | 1,657 |
```xml
import glob from 'glob'
import http from 'http'
import fs from 'fs-extra'
import { join } from 'path'
import { FileRef, NextInstance, createNext } from 'e2e-utils'
import {
retry,
killApp,
findPort,
fetchViaHTTP,
initNextServerScript,
} from 'next-test-utils'
describe('fetch-cache', () => {
let next: NextInstance
let appPort: any
let cliOuptut = ''
let nextInstance: any
let fetchGetReqIndex = 0
let revalidateReqIndex = 0
let fetchGetShouldError = false
let fetchCacheServer: http.Server
let fetchCacheRequests: Array<{
url: string
method: string
headers: Record<string, string | string[]>
}> = []
let fetchCacheEnv: Record<string, string> = {
SUSPENSE_CACHE_PROTO: 'http',
}
const setupNext = async ({
nextEnv,
minimalMode,
}: {
nextEnv?: boolean
minimalMode?: boolean
}) => {
// test build against environment with next support
process.env.NOW_BUILDER = nextEnv ? '1' : ''
next = await createNext({
files: {
app: new FileRef(join(__dirname, 'app')),
},
nextConfig: {
eslint: {
ignoreDuringBuilds: true,
},
output: 'standalone',
},
})
await next.stop()
await fs.move(
join(next.testDir, '.next/standalone'),
join(next.testDir, 'standalone')
)
for (const file of await fs.readdir(next.testDir)) {
if (file !== 'standalone') {
await fs.remove(join(next.testDir, file))
console.log('removed', file)
}
}
const files = glob.sync('**/*', {
cwd: join(next.testDir, 'standalone/.next/server/pages'),
dot: true,
})
for (const file of files) {
if (file.endsWith('.json') || file.endsWith('.html')) {
await fs.remove(join(next.testDir, '.next/server', file))
}
}
const testServer = join(next.testDir, 'standalone/server.js')
await fs.writeFile(
testServer,
(await fs.readFile(testServer, 'utf8')).replace(
'port:',
`minimalMode: ${minimalMode},port:`
)
)
appPort = await findPort()
nextInstance = await initNextServerScript(
testServer,
/- Local:/,
{
...process.env,
...fetchCacheEnv,
PORT: appPort,
},
undefined,
{
cwd: next.testDir,
onStderr(data) {
cliOuptut += data
},
onStdout(data) {
cliOuptut += data
},
}
)
}
beforeAll(async () => {
fetchGetReqIndex = 0
revalidateReqIndex = 0
fetchCacheRequests = []
fetchGetShouldError = false
fetchCacheServer = http.createServer((req, res) => {
console.log(`fetch cache request ${req.url} ${req.method}`, req.headers)
const parsedUrl = new URL(req.url || '/', 'path_to_url
fetchCacheRequests.push({
url: req.url,
method: req.method?.toLowerCase(),
headers: req.headers,
})
if (parsedUrl.pathname === '/v1/suspense-cache/revalidate') {
revalidateReqIndex += 1
// timeout unless it's 3rd retry
const shouldTimeout = revalidateReqIndex % 3 !== 0
if (shouldTimeout) {
console.log('not responding for', req.url, { revalidateReqIndex })
return
}
res.statusCode = 200
res.end(`revalidated ${parsedUrl.searchParams.get('tags')}`)
return
}
const keyMatches = parsedUrl.pathname.match(
/\/v1\/suspense-cache\/(.*?)\/?$/
)
const key = keyMatches?.[0]
if (key) {
const type = req.method?.toLowerCase()
console.log(`got ${type} for ${key}`)
if (type === 'get') {
fetchGetReqIndex += 1
if (fetchGetShouldError) {
res.statusCode = 500
res.end('internal server error')
return
}
}
res.statusCode = type === 'post' ? 200 : 404
res.end(`${type} for ${key}`)
return
}
res.statusCode = 404
res.end('not found')
})
await new Promise<void>(async (resolve) => {
let fetchCachePort = await findPort()
fetchCacheServer.listen(fetchCachePort, () => {
fetchCacheEnv['SUSPENSE_CACHE_URL'] = `[::]:${fetchCachePort}`
console.log(
`Started fetch cache server at path_to_url{fetchCacheEnv['SUSPENSE_CACHE_URL']}`
)
resolve()
})
})
await setupNext({ nextEnv: true, minimalMode: true })
})
afterAll(async () => {
await next.destroy()
if (fetchCacheServer) fetchCacheServer.close()
if (nextInstance) await killApp(nextInstance)
})
it('should have correct fetchUrl field for fetches and unstable_cache', async () => {
const res = await fetchViaHTTP(appPort, '/?myKey=myValue')
const html = await res.text()
expect(res.status).toBe(200)
expect(html).toContain('hello world')
const fetchUrlHeader = 'x-vercel-cache-item-name'
const fetchTagsHeader = 'x-vercel-cache-tags'
const fetchSoftTagsHeader = 'x-next-cache-soft-tags'
const unstableCacheSet = fetchCacheRequests.find((item) => {
return (
item.method === 'get' &&
item.headers[fetchUrlHeader]?.includes('unstable_cache')
)
})
const fetchSet = fetchCacheRequests.find((item) => {
return (
item.method === 'get' &&
item.headers[fetchUrlHeader]?.includes('next-data-api-endpoint')
)
})
expect(unstableCacheSet.headers[fetchUrlHeader]).toMatch(
/unstable_cache \/\?myKey=myValue .*?/
)
expect(unstableCacheSet.headers[fetchTagsHeader]).toBe('thankyounext')
expect(unstableCacheSet.headers[fetchSoftTagsHeader]).toBe(
'_N_T_/layout,_N_T_/page,_N_T_/'
)
expect(fetchSet.headers[fetchUrlHeader]).toBe(
'path_to_url
)
expect(fetchSet.headers[fetchSoftTagsHeader]).toBe(
'_N_T_/layout,_N_T_/page,_N_T_/'
)
expect(fetchSet.headers[fetchTagsHeader]).toBe('thankyounext')
})
it('should retry 3 times when revalidate times out', async () => {
await fetchViaHTTP(appPort, '/api/revalidate')
await retry(() => {
expect(revalidateReqIndex).toBe(3)
})
expect(cliOuptut).not.toContain('Failed to revalidate')
expect(cliOuptut).not.toContain('Error')
})
it('should not retry for failed fetch-cache GET', async () => {
fetchGetShouldError = true
const fetchGetReqIndexStart = fetchGetReqIndex
try {
await fetchViaHTTP(appPort, '/api/revalidate')
const res = await fetchViaHTTP(appPort, '/')
expect(res.status).toBe(200)
expect(await res.text()).toContain('hello world')
expect(fetchGetReqIndex).toBe(fetchGetReqIndexStart + 2)
} finally {
fetchGetShouldError = false
}
})
})
``` | /content/code_sandbox/test/production/app-dir/fetch-cache/fetch-cache.test.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 1,725 |
```xml
import { WebApplication } from '@/Application/WebApplication'
import { NotesController } from '@/Controllers/NotesController/NotesController'
import { useRef, useState } from 'react'
import RoundIconButton from '../Button/RoundIconButton'
import Popover from '../Popover/Popover'
import ChangeEditorMultipleMenu from './ChangeEditorMultipleMenu'
type Props = {
application: WebApplication
notesController: NotesController
}
const ChangeMultipleButton = ({ application, notesController }: Props) => {
const changeButtonRef = useRef<HTMLButtonElement>(null)
const [isChangeMenuOpen, setIsChangeMenuOpen] = useState(false)
const toggleMenu = () => setIsChangeMenuOpen((open) => !open)
const [disableClickOutside, setDisableClickOutside] = useState(false)
return (
<>
<RoundIconButton label={'Change note type'} onClick={toggleMenu} ref={changeButtonRef} icon="plain-text" />
<Popover
title="Change note type"
togglePopover={toggleMenu}
disableClickOutside={disableClickOutside}
anchorElement={changeButtonRef}
open={isChangeMenuOpen}
className="md:pb-1"
>
<ChangeEditorMultipleMenu
application={application}
notes={notesController.selectedNotes}
setDisableClickOutside={setDisableClickOutside}
/>
</Popover>
</>
)
}
export default ChangeMultipleButton
``` | /content/code_sandbox/packages/web/src/javascripts/Components/ChangeEditor/ChangeMultipleButton.tsx | xml | 2016-12-05T23:31:33 | 2024-08-16T06:51:19 | app | standardnotes/app | 5,180 | 299 |
```xml
import React from 'react';
import HttpMethodIcon from '../font_icon/http_method_icon';
import ItemWithMenu from '../item_with_menu';
import './style/index.less';
import { Menu, Icon, Badge } from 'antd';
import { confirmDlg } from '../confirm_dialog/index';
import { DtoBaseItem, DtoRecord } from '../../common/interfaces/dto_record';
import { StringUtil } from '../../utils/string_util';
import Msg from '../../locales';
import LocalesString from '../../locales/string';
interface RecordItemProps {
item: DtoBaseItem;
inFolder: boolean;
readOnly: boolean;
deleteRecord();
duplicateRecord();
moveRecordToFolder(record: DtoBaseItem, collectionId?: string, folderId?: string);
moveToCollection(record: DtoBaseItem, collection?: string);
showTimeline();
}
interface RecordItemState { }
class RecordItem extends React.Component<RecordItemProps, RecordItemState> {
private itemWithMenu: ItemWithMenu | null;
constructor(props: RecordItemProps) {
super(props);
}
public shouldComponentUpdate(nextProps: RecordItemProps, _nextState: RecordItemState) {
const preRecord = this.props.item as DtoRecord;
const nextRecord = nextProps.item as DtoRecord;
return this.props.item.id !== nextProps.item.id ||
this.props.item.name !== nextProps.item.name ||
this.props.item.method !== nextProps.item.method ||
(preRecord && nextRecord &&
preRecord.parameters !== nextRecord.parameters ||
preRecord.parameterType !== nextRecord.parameterType ||
preRecord.reduceAlgorithm !== nextRecord.reduceAlgorithm) ||
this.props.inFolder !== nextProps.inFolder;
}
private getMenu = () => {
return (
<Menu className="item_menu" onClick={this.onClickMenu}>
<Menu.Item key="duplicate">
<Icon type="copy" /> {Msg('Common.Duplicate')}
</Menu.Item>
<Menu.Item key="delete">
<Icon type="delete" /> {Msg('Common.Delete')}
</Menu.Item>
<Menu.Item key="history">
<Icon type="clock-circle-o" /> {Msg('Collection.History')}
</Menu.Item>
</Menu>
);
}
private onClickMenu = (e) => {
this[e.key]();
}
delete = () => confirmDlg(LocalesString.get('Collection.DeleteRequest'), () => this.props.deleteRecord(), LocalesString.get('Collection.DeleteThisRequest'));
duplicate = () => this.props.duplicateRecord();
history = () => this.props.showTimeline();
private checkTransferFlag = (e, flag) => {
return e.dataTransfer.types.indexOf(flag) > -1;
}
private dragStart = (e) => {
e.dataTransfer.setData('record', JSON.stringify(this.props.item));
}
private dragOver = (e) => {
e.preventDefault();
}
private drop = (e) => {
const currentRecord = this.props.item;
if (this.checkTransferFlag(e, 'record')) {
const transferRecord = JSON.parse(e.dataTransfer.getData('record')) as DtoBaseItem;
if (transferRecord.pid !== currentRecord.pid || transferRecord.collectionId !== currentRecord.collectionId) {
this.props.moveRecordToFolder(transferRecord, currentRecord.collectionId, currentRecord.pid);
}
} else if (this.checkTransferFlag(e, 'folder')) {
const folder = JSON.parse(e.dataTransfer.getData('folder')) as DtoBaseItem;
if (folder.collectionId !== currentRecord.collectionId) {
this.props.moveToCollection(folder, currentRecord.collectionId);
}
}
}
public render() {
let { item, inFolder, readOnly } = this.props;
let { method, name } = item;
method = method || 'GET';
const record = item as DtoRecord;
const paramReqInfo = record ? StringUtil.verifyParameters(record.parameters || '', record.parameterType) : { isValid: false };
const reqCount = record ? StringUtil.getUniqParamArr(record.parameters || '', record.parameterType, record.reduceAlgorithm).length : 0;
return (
<div
draggable={!readOnly}
onDragStart={this.dragStart}
onDragOver={this.dragOver}
onDrop={this.drop}
>
{paramReqInfo.isValid && !readOnly ? <Badge className="record-item-badge" overflowCount={999} count={reqCount} style={{ backgroundColor: HttpMethodIcon.colorMapping[method.toUpperCase()] }} /> : ''}
<ItemWithMenu
ref={ele => this.itemWithMenu = ele}
className={`record ${inFolder ? 'record-in-folder' : ''}`}
icon={(
<span className="record-icon">
<HttpMethodIcon httpMethod={method.toUpperCase()} needTextMapping={true} />
</span>
)}
name={name}
menu={this.getMenu()}
disableMenu={readOnly}
/>
</div>
);
}
}
export default RecordItem;
``` | /content/code_sandbox/client/src/components/collection_tree/record_item.tsx | xml | 2016-09-26T02:47:43 | 2024-07-24T09:32:20 | Hitchhiker | brookshi/Hitchhiker | 2,193 | 1,059 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="path_to_url">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="debug|x64">
<Configuration>debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release|x64">
<Configuration>release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="checked|x64">
<Configuration>checked</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="profile|x64">
<Configuration>profile</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{5B1132F6-84F8-142E-B951-ADB8505CC27F}</ProjectGuid>
<RootNamespace>PxTask</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='checked|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='profile|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='checked|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='profile|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug|x64'">
<OutDir>./../../../lib/vc12win64\</OutDir>
<IntDir>./x64/PxTask/debug\</IntDir>
<TargetExt>.lib</TargetExt>
<TargetName>$(ProjectName)DEBUG_x64</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<StringPooling>true</StringPooling>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<BasicRuntimeChecks>UninitializedLocalUsageCheck</BasicRuntimeChecks>
<AdditionalOptions>/MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /d2Zi+</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>./../../../include;./../../task/include;./../../foundation/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;_DEBUG;PX_DEBUG=1;PX_CHECKED=1;PX_NVTX=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Lib>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)DEBUG_x64.lib</OutputFile>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<TargetMachine>MachineX64</TargetMachine>
</Lib>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release|x64'">
<OutDir>./../../../lib/vc12win64\</OutDir>
<IntDir>./x64/PxTask/release\</IntDir>
<TargetExt>.lib</TargetExt>
<TargetName>$(ProjectName)_x64</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<StringPooling>true</StringPooling>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<AdditionalOptions>/MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /d2Zi+</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>./../../../include;./../../task/include;./../../foundation/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Lib>
<AdditionalOptions>/INCREMENTAL:NO</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)_x64.lib</OutputFile>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<TargetMachine>MachineX64</TargetMachine>
</Lib>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='checked|x64'">
<OutDir>./../../../lib/vc12win64\</OutDir>
<IntDir>./x64/PxTask/checked\</IntDir>
<TargetExt>.lib</TargetExt>
<TargetName>$(ProjectName)CHECKED_x64</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='checked|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<StringPooling>true</StringPooling>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<AdditionalOptions>/MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /d2Zi+</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>./../../../include;./../../task/include;./../../foundation/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;NDEBUG;PX_CHECKED=1;PX_NVTX=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Lib>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)CHECKED_x64.lib</OutputFile>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<TargetMachine>MachineX64</TargetMachine>
</Lib>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='profile|x64'">
<OutDir>./../../../lib/vc12win64\</OutDir>
<IntDir>./x64/PxTask/profile\</IntDir>
<TargetExt>.lib</TargetExt>
<TargetName>$(ProjectName)PROFILE_x64</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='profile|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<StringPooling>true</StringPooling>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<AdditionalOptions>/MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /d2Zi+</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>./../../../include;./../../task/include;./../../foundation/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;NDEBUG;PX_PROFILE=1;PX_NVTX=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Lib>
<AdditionalOptions>/INCREMENTAL:NO</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)PROFILE_x64.lib</OutputFile>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<TargetMachine>MachineX64</TargetMachine>
</Lib>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\..\..\include\task\PxCpuDispatcher.h">
</ClInclude>
<ClInclude Include="..\..\..\include\task\PxGpuDispatcher.h">
</ClInclude>
<ClInclude Include="..\..\..\include\task\PxGpuTask.h">
</ClInclude>
<ClInclude Include="..\..\..\include\task\PxTask.h">
</ClInclude>
<ClInclude Include="..\..\..\include\task\PxTaskDefine.h">
</ClInclude>
<ClInclude Include="..\..\..\include\task\PxTaskManager.h">
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\task\src\TaskManager.cpp">
</ClCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets"></ImportGroup>
</Project>
``` | /content/code_sandbox/PxShared/src/compiler/vc12win64/PxTask.vcxproj | xml | 2016-10-12T16:34:31 | 2024-08-16T09:40:38 | PhysX-3.4 | NVIDIAGameWorks/PhysX-3.4 | 2,343 | 3,398 |
```xml
import { ResizeObserver } from '@juggle/resize-observer'
import React, { useEffect, useRef, RefObject } from 'react'
import { prefixObject } from '../../utils/Styles'
import { MultiInspector } from './Inspector'
import type { PlaygroundOptions } from './Workspace'
const styles = prefixObject({
container: {
backgroundColor: 'rgba(0,0,0,0.02)',
border: '1px solid rgba(0,0,0,0.05)',
padding: '4px 8px',
borderRadius: 8,
display: 'inline-block',
flexDirection: 'row',
alignItems: 'stretch',
minWidth: 0,
minHeight: 0,
},
content: {
display: 'flex',
whiteSpace: 'pre',
},
itemSpacer: {
width: 8,
},
})
function useResizeObserver(ref: RefObject<HTMLDivElement>, f: () => void) {
useEffect(() => {
let resizeObserver: ResizeObserver
let mounted = true
import('@juggle/resize-observer').then(({ ResizeObserver }) => {
if (!mounted) return
resizeObserver = new ResizeObserver(() => {
f()
})
if (ref.current) {
resizeObserver.observe(ref.current)
}
})
return () => {
mounted = false
if (ref.current && resizeObserver) {
resizeObserver.unobserve(ref.current)
}
}
}, [])
}
interface Props {
indent: number
data: unknown[]
didResize: () => void
playgroundOptions: PlaygroundOptions
}
export default function PlaygroundPreview({
indent,
data,
didResize,
playgroundOptions,
}: Props) {
const ref = useRef<HTMLDivElement>(null)
useResizeObserver(ref, didResize)
return (
<div ref={ref} style={{ ...styles.container, marginLeft: indent }}>
<div style={styles.content}>
<MultiInspector
data={data}
inspector={playgroundOptions.inspector}
renderReactElements={playgroundOptions.renderReactElements}
expandLevel={playgroundOptions.expandLevel}
/>
</div>
</div>
)
}
``` | /content/code_sandbox/src/components/workspace/PlaygroundPreview.tsx | xml | 2016-05-05T19:10:17 | 2024-08-07T06:39:11 | javascript-playgrounds | dabbott/javascript-playgrounds | 1,391 | 471 |
```xml
import { TestBed } from '@angular/core/testing';
import { LocaleService } from '~/app/shared/services/locale.service';
describe('LocaleService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: LocaleService = TestBed.inject(LocaleService);
expect(service).toBeTruthy();
});
});
``` | /content/code_sandbox/deb/openmediavault/workbench/src/app/shared/services/locale.service.spec.ts | xml | 2016-05-03T10:35:34 | 2024-08-16T08:03:04 | openmediavault | openmediavault/openmediavault | 4,954 | 71 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="path_to_url"
xmlns:x="path_to_url"
xmlns:local="clr-namespace:Xamarin.Forms.Xaml.UnitTests"
x:Class="Xamarin.Forms.Xaml.UnitTests.Bz47703">
<ContentPage.Resources>
<ResourceDictionary>
<local:Bz47703Converter x:Key="converter" />
</ResourceDictionary>
</ContentPage.Resources>
<local:Bz47703View x:Name="view" DisplayBinding="{Binding Name, Converter={StaticResource converter}}" />
</ContentPage>
``` | /content/code_sandbox/Xamarin.Forms.Xaml.UnitTests/Issues/Bz47703.xaml | xml | 2016-03-18T15:52:03 | 2024-08-16T16:25:43 | Xamarin.Forms | xamarin/Xamarin.Forms | 5,637 | 138 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="path_to_url"
xmlns="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-function-parent</artifactId>
<name>Spring Cloud Function Parent</name>
<version>4.2.0-SNAPSHOT</version>
<packaging>pom</packaging>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>4.2.0-SNAPSHOT</version>
<relativePath/>
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<wrapper.version>1.0.27.RELEASE</wrapper.version>
<docs.main>spring-cloud-function</docs.main>
<maven-checkstyle-plugin.failsOnError>true</maven-checkstyle-plugin.failsOnError>
<maven-checkstyle-plugin.failsOnViolation>true
</maven-checkstyle-plugin.failsOnViolation>
<maven-checkstyle-plugin.includeTestSourceDirectory>true
</maven-checkstyle-plugin.includeTestSourceDirectory>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-dependencies</artifactId>
<version>${project.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--add-opens java.base/java.util=ALL-UNNAMED</argLine>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<inherited>false</inherited>
<configuration>
<aggregate>true</aggregate>
<excludePackageNames>com.example,functions,example
</excludePackageNames>
</configuration>
<executions>
<execution>
<id>aggregate</id>
<goals>
<goal>aggregate-jar</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-layout</artifactId>
<version>${wrapper.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.codehaus.mojo
</groupId>
<artifactId>
flatten-maven-plugin
</artifactId>
<versionRange>
[1.0.0,)
</versionRange>
<goals>
<goal>flatten</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</reporting>
<profiles>
<profile>
<id>core</id>
<modules>
<module>spring-cloud-function-dependencies</module>
<module>spring-cloud-function-core</module>
<module>spring-cloud-function-context</module>
<module>spring-cloud-function-web</module>
</modules>
</profile>
<profile>
<id>all</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<modules>
<module>spring-cloud-function-dependencies</module>
<module>spring-cloud-function-core</module>
<module>spring-cloud-function-context</module>
<module>spring-cloud-function-web</module>
<module>spring-cloud-starter-function-web</module>
<module>spring-cloud-starter-function-webflux</module>
<module>spring-cloud-function-samples</module>
<module>spring-cloud-function-deployer</module>
<module>spring-cloud-function-adapters</module>
<module>spring-cloud-function-integration</module>
<module>spring-cloud-function-rsocket</module>
<module>spring-cloud-function-kotlin</module>
<module>docs</module>
</modules>
</profile>
</profiles>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>path_to_url
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>path_to_url
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>path_to_url
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>path_to_url
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>path_to_url
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>path_to_url
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
``` | /content/code_sandbox/pom.xml | xml | 2016-09-22T02:34:34 | 2024-08-16T08:19:07 | spring-cloud-function | spring-cloud/spring-cloud-function | 1,032 | 1,815 |
```xml
import { AsyncIterableX } from '../asynciterablex.js';
import { createGrouping } from './_grouping.js';
import { identity } from '../../util/identity.js';
import { OperatorAsyncFunction } from '../../interfaces.js';
import { wrapWithAbort } from './withabort.js';
import { throwIfAborted } from '../../aborterror.js';
/** @ignore */
export class JoinAsyncIterable<TOuter, TInner, TKey, TResult> extends AsyncIterableX<TResult> {
private _outer: AsyncIterable<TOuter>;
private _inner: AsyncIterable<TInner>;
private _outerSelector: (value: TOuter, signal?: AbortSignal) => TKey | Promise<TKey>;
private _innerSelector: (value: TInner, signal?: AbortSignal) => TKey | Promise<TKey>;
private _resultSelector: (
outer: TOuter,
inner: TInner,
signal?: AbortSignal
) => TResult | Promise<TResult>;
constructor(
outer: AsyncIterable<TOuter>,
inner: AsyncIterable<TInner>,
outerSelector: (value: TOuter, signal?: AbortSignal) => TKey | Promise<TKey>,
innerSelector: (value: TInner, signal?: AbortSignal) => TKey | Promise<TKey>,
resultSelector: (
outer: TOuter,
inner: TInner,
signal?: AbortSignal
) => TResult | Promise<TResult>
) {
super();
this._outer = outer;
this._inner = inner;
this._outerSelector = outerSelector;
this._innerSelector = innerSelector;
this._resultSelector = resultSelector;
}
async *[Symbol.asyncIterator](signal?: AbortSignal) {
throwIfAborted(signal);
const map = await createGrouping(this._inner, this._innerSelector, identity, signal);
for await (const outerElement of wrapWithAbort(this._outer, signal)) {
const outerKey = await this._outerSelector(outerElement, signal);
if (map.has(outerKey)) {
for (const innerElement of map.get(outerKey)!) {
yield await this._resultSelector(outerElement, innerElement, signal);
}
}
}
}
}
/**
* Correlates the elements of two sequences based on matching keys.
*
* @template TOuter The type of the elements of the first async-iterable sequence.
* @template TInner The type of the elements of the second async-iterable sequence.
* @template TKey The type of the keys returned by the key selector functions.
* @template TResult The type of the result elements.
* @param {AsyncIterable<TInner>} inner The async-enumerable sequence to join to the first sequence.
* @param {((value: TOuter, signal?: AbortSignal) => TKey | Promise<TKey>)} outerSelector A function to extract the join key from each element
* of the first sequence.
* @param {((value: TInner, signal?: AbortSignal) => TKey | Promise<TKey>)} innerSelector A function to extract the join key from each element
* of the second sequence.
* @param {((outer: TOuter, inner: TInner, signal?: AbortSignal) => TResult | Promise<TResult>)} resultSelector A function to create a result element
* from two matching elements.
* @returns {OperatorAsyncFunction<TOuter, TResult>} An async-iterable sequence that has elements that are obtained by performing an inner join
* on two sequences.
*/
export function innerJoin<TOuter, TInner, TKey, TResult>(
inner: AsyncIterable<TInner>,
outerSelector: (value: TOuter, signal?: AbortSignal) => TKey | Promise<TKey>,
innerSelector: (value: TInner, signal?: AbortSignal) => TKey | Promise<TKey>,
resultSelector: (outer: TOuter, inner: TInner, signal?: AbortSignal) => TResult | Promise<TResult>
): OperatorAsyncFunction<TOuter, TResult> {
return function innerJoinOperatorFunction(outer: AsyncIterable<TOuter>): AsyncIterableX<TResult> {
return new JoinAsyncIterable<TOuter, TInner, TKey, TResult>(
outer,
inner,
outerSelector,
innerSelector,
resultSelector
);
};
}
``` | /content/code_sandbox/src/asynciterable/operators/innerjoin.ts | xml | 2016-02-22T20:04:19 | 2024-08-09T18:46:41 | IxJS | ReactiveX/IxJS | 1,319 | 891 |
```xml
/**
*/
import { ConfigAPI, types } from '@babel/core';
export declare function detectDynamicExports(api: ConfigAPI & {
types: typeof types;
}): babel.PluginObj;
``` | /content/code_sandbox/packages/babel-preset-expo/build/detect-dynamic-exports.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 38 |
```xml
<vector xmlns:android="path_to_url" android:height="34.0dp" android:tint="?attr/colorControlNormal" android:viewportHeight="15" android:viewportWidth="15" android:width="34.0dp">
<path android:fillColor="@android:color/white" android:pathData="M4 9.42L4 8.02C3.72 7.94 3.39 7.75 3 7.43C1 5.83 3.84 0.5 4.5 0.5C5.17 0.5 8 5.83 6 7.43C5.61 7.75 5.28 7.94 5 8.02L5 9.07C5.24 9.02 5.48 9 5.73 9C6.06 9 6.57 8.62 7.27 7.86C7.73 7.36 8.46 7.21 9.07 7.5L9.87 7.87C10.05 7.96 10.23 8.05 10.4 8.15L11.68 8.92C11.77 8.97 11.86 9.04 11.94 9.11L12.41 9.5C12.78 9.82 13 10.28 13 10.77L13 11.32C12.96 11.35 12.91 11.38 12.87 11.42L12.4 11.82C12.11 12.06 11.69 12.06 11.4 11.82C11.25 11.7 11.11 11.56 10.96 11.44C10.25 10.85 9.21 10.85 8.5 11.44C8.34 11.56 8.19 11.71 8.03 11.84C7.74 12.08 7.32 12.08 7.03 11.84C6.87 11.71 6.72 11.56 6.56 11.44C5.85 10.86 4.82 10.86 4.11 11.44C3.95 11.56 3.82 11.7 3.66 11.82C3.57 11.89 3.46 11.94 3.35 11.97C3.05 12.04 2.75 11.95 2.54 11.73C2.43 11.64 2.33 11.56 2.22 11.47C2.53 10.59 3.18 9.86 4 9.42L4 9.42ZM9.68 13L9.54 13C9.36 13.02 9.19 13.09 9.06 13.22C8.92 13.34 8.79 13.46 8.64 13.58C7.91 14.15 6.86 14.13 6.16 13.51L5.77 13.17C5.67 13.08 5.54 13.02 5.41 13L5.13 13C5 13.02 4.87 13.08 4.77 13.17C4.58 13.32 4.41 13.48 4.22 13.63C3.52 14.14 2.55 14.12 1.87 13.57L1.56 13.31C1.42 13.14 1.22 13.04 1 13L1 12.03C1.26 11.99 1.52 12.04 1.75 12.16C2.03 12.33 2.29 12.52 2.54 12.73C2.7 12.9 2.92 12.99 3.15 13C3.19 12.99 3.24 12.99 3.29 12.99C3.31 12.98 3.33 12.98 3.35 12.97C3.46 12.94 3.57 12.89 3.66 12.82C3.82 12.7 3.95 12.56 4.11 12.44C4.38 12.22 4.69 12.08 5.01 12.03C5.15 11.98 5.3 11.97 5.45 12.01C5.85 12.03 6.24 12.17 6.56 12.44C6.72 12.56 6.87 12.71 7.03 12.84C7.11 12.91 7.21 12.96 7.3 12.99C7.49 13 7.68 12.99 7.86 12.95C7.92 12.92 7.98 12.88 8.03 12.84C8.19 12.71 8.34 12.56 8.5 12.44C8.76 12.22 9.06 12.09 9.37 12.03C9.48 12 9.58 11.99 9.69 12C10.14 11.99 10.59 12.14 10.96 12.44C11.11 12.56 11.25 12.7 11.4 12.82C11.53 12.93 11.68 12.99 11.84 13C11.93 13 12.02 12.99 12.12 12.97C12.22 12.94 12.32 12.89 12.4 12.82L12.87 12.42C13.19 12.16 13.59 12.02 14 12.03L14 13C13.74 13.02 13.49 13.14 13.32 13.34C13.05 13.62 12.7 13.82 12.32 13.92C11.71 14.1 11.04 13.97 10.55 13.56L10.16 13.22C10.03 13.09 9.86 13.02 9.68 13L9.68 13ZM7.35 13L7.71 13C7.59 13.03 7.47 13.03 7.35 13L7.35 13Z"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_preset_temaki_islet_tree.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 1,590 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import iterFirst = require( './index' );
/**
* Returns an iterator protocol-compliant object.
*
* @returns iterator protocol-compliant object
*/
function iterator() {
return {
'next': next
};
/**
* Implements the iterator protocol `next` method.
*
* @returns iterator protocol-compliant object
*/
function next() {
return {
'value': true,
'done': false
};
}
}
// TESTS //
// The function returns a value...
{
iterFirst( iterator() ); // $ExpectType any
}
// The compiler throws an error if the function is provided a value other than an iterator protocol-compliant object...
{
iterFirst( '5' ); // $ExpectError
iterFirst( 5 ); // $ExpectError
iterFirst( true ); // $ExpectError
iterFirst( false ); // $ExpectError
iterFirst( null ); // $ExpectError
iterFirst( undefined ); // $ExpectError
iterFirst( [] ); // $ExpectError
iterFirst( {} ); // $ExpectError
iterFirst( ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the function is provided insufficient arguments...
{
iterFirst(); // $ExpectError
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/iter/first/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 322 |
```xml
// See LICENSE.txt for license information.
import React, {useCallback, useEffect, useMemo, useState} from 'react';
import {type LayoutChangeEvent, Platform, ScrollView, View} from 'react-native';
import Animated, {useAnimatedStyle, useDerivedValue, useSharedValue, withTiming} from 'react-native-reanimated';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import Button from '@components/button';
import {USER_CHIP_BOTTOM_MARGIN, USER_CHIP_HEIGHT} from '@components/selected_chip';
import Toast from '@components/toast';
import {useTheme} from '@context/theme';
import {useKeyboardHeightWithDuration} from '@hooks/device';
import {changeOpacity, makeStyleSheetFromTheme} from '@utils/theme';
import SelectedUser from './selected_user';
type Props = {
/**
* Name of the button Icon
*/
buttonIcon: string;
/*
* Text displayed on the action button
*/
buttonText: string;
/**
* the overlap of the keyboard with this list
*/
keyboardOverlap?: number;
/**
* A handler function that will select or deselect a user when clicked on.
*/
onPress: (selectedId?: {[id: string]: boolean}) => void;
/**
* A handler function that will deselect a user when clicked on.
*/
onRemove: (id: string) => void;
/**
* An object mapping user ids to a falsey value indicating whether or not they have been selected.
*/
selectedIds: {[id: string]: UserProfile};
/**
* callback to set the value of showToast
*/
setShowToast?: (show: boolean) => void;
/**
* show the toast
*/
showToast?: boolean;
/**
* How to display the names of users.
*/
teammateNameDisplay: string;
/**
* test ID
*/
testID?: string;
/**
* toast Icon
*/
toastIcon?: string;
/**
* toast Message
*/
toastMessage?: string;
/**
* Max number of users in the list
*/
maxUsers?: number;
}
const BUTTON_HEIGHT = 48;
const CHIP_HEIGHT_WITH_MARGIN = USER_CHIP_HEIGHT + USER_CHIP_BOTTOM_MARGIN;
const EXPOSED_CHIP_HEIGHT = 0.33 * USER_CHIP_HEIGHT;
const MAX_CHIP_ROWS = 2;
const SCROLL_MARGIN_TOP = 20;
const SCROLL_MARGIN_BOTTOM = 12;
const USERS_CHIPS_MAX_HEIGHT = (CHIP_HEIGHT_WITH_MARGIN * MAX_CHIP_ROWS) + EXPOSED_CHIP_HEIGHT;
const SCROLL_MAX_HEIGHT = USERS_CHIPS_MAX_HEIGHT + SCROLL_MARGIN_TOP + SCROLL_MARGIN_BOTTOM;
const PANEL_MAX_HEIGHT = SCROLL_MAX_HEIGHT + BUTTON_HEIGHT;
const TABLET_MARGIN_BOTTOM = 20;
const TOAST_BOTTOM_MARGIN = 24;
const getStyleFromTheme = makeStyleSheetFromTheme((theme) => {
return {
container: {
backgroundColor: theme.centerChannelBg,
borderBottomWidth: 0,
borderColor: changeOpacity(theme.centerChannelColor, 0.16),
borderTopLeftRadius: 12,
borderTopRightRadius: 12,
borderWidth: 1,
maxHeight: PANEL_MAX_HEIGHT,
overflow: 'hidden',
paddingHorizontal: 20,
shadowColor: theme.centerChannelColor,
shadowOffset: {
width: 0,
height: 8,
},
shadowOpacity: 0.16,
shadowRadius: 24,
},
toast: {
backgroundColor: theme.errorTextColor,
},
usersScroll: {
marginTop: SCROLL_MARGIN_TOP,
marginBottom: SCROLL_MARGIN_BOTTOM,
},
users: {
flexDirection: 'row',
flexGrow: 1,
flexWrap: 'wrap',
},
message: {
color: theme.centerChannelBg,
fontSize: 12,
marginRight: 5,
marginTop: 10,
marginBottom: 2,
},
};
});
export default function SelectedUsers({
buttonIcon,
buttonText,
keyboardOverlap = 0,
onPress,
onRemove,
selectedIds,
setShowToast,
showToast = false,
teammateNameDisplay,
testID,
toastIcon,
toastMessage,
maxUsers,
}: Props) {
const theme = useTheme();
const style = getStyleFromTheme(theme);
const keyboard = useKeyboardHeightWithDuration();
const insets = useSafeAreaInsets();
const usersChipsHeight = useSharedValue(0);
const [isVisible, setIsVisible] = useState(false);
const numberSelectedIds = Object.keys(selectedIds).length;
const users = useMemo(() => {
const u = [];
for (const id of Object.keys(selectedIds)) {
if (!selectedIds[id]) {
continue;
}
u.push(
<SelectedUser
key={id}
user={selectedIds[id]}
teammateNameDisplay={teammateNameDisplay}
onRemove={onRemove}
testID={`${testID}.selected_user`}
/>,
);
}
return u;
}, [selectedIds, teammateNameDisplay, onRemove]);
const totalPanelHeight = useDerivedValue(() => (
isVisible ?
usersChipsHeight.value + SCROLL_MARGIN_BOTTOM + SCROLL_MARGIN_TOP + BUTTON_HEIGHT :
0
), [isVisible]);
const handlePress = useCallback(() => {
onPress();
}, [onPress]);
const onLayout = useCallback((e: LayoutChangeEvent) => {
usersChipsHeight.value = Math.min(
USERS_CHIPS_MAX_HEIGHT,
e.nativeEvent.layout.height,
);
}, []);
const androidMaxHeight = Platform.select({
android: {
maxHeight: isVisible ? undefined : 0,
},
});
const animatedContainerStyle = useAnimatedStyle(() => ({
marginBottom: withTiming(keyboardOverlap + TABLET_MARGIN_BOTTOM, {duration: keyboard.duration}),
backgroundColor: isVisible ? theme.centerChannelBg : 'transparent',
...androidMaxHeight,
}), [keyboardOverlap, keyboard.duration, isVisible, theme.centerChannelBg]);
const animatedToastStyle = useAnimatedStyle(() => {
return {
bottom: TOAST_BOTTOM_MARGIN + totalPanelHeight.value + insets.bottom,
opacity: withTiming(showToast ? 1 : 0, {duration: 250}),
position: 'absolute',
};
}, [showToast, insets.bottom]);
const animatedViewStyle = useAnimatedStyle(() => ({
height: withTiming(totalPanelHeight.value, {duration: 250}),
borderWidth: isVisible ? 1 : 0,
maxHeight: isVisible ? PANEL_MAX_HEIGHT + BUTTON_HEIGHT : 0,
}), [isVisible]);
const animatedButtonStyle = useAnimatedStyle(() => ({
opacity: withTiming(isVisible ? 1 : 0, {duration: isVisible ? 500 : 100}),
}), [isVisible]);
useEffect(() => {
setIsVisible(numberSelectedIds > 0);
}, [numberSelectedIds > 0]);
// This effect hides the toast after 4 seconds
useEffect(() => {
let timer: NodeJS.Timeout;
if (showToast) {
timer = setTimeout(() => {
setShowToast?.(false);
}, 4000);
}
return () => clearTimeout(timer);
}, [showToast]);
const isDisabled = Boolean(maxUsers && (numberSelectedIds > maxUsers));
return (
<Animated.View style={animatedContainerStyle}>
{showToast &&
<Toast
animatedStyle={animatedToastStyle}
iconName={toastIcon}
style={style.toast}
message={toastMessage}
/>
}
<Animated.View style={[style.container, animatedViewStyle]}>
<ScrollView style={style.usersScroll}>
<View
style={style.users}
onLayout={onLayout}
>
{users}
</View>
</ScrollView>
<Animated.View style={animatedButtonStyle}>
<Button
onPress={handlePress}
iconName={buttonIcon}
text={buttonText}
iconSize={20}
theme={theme}
buttonType={isDisabled ? 'disabled' : 'default'}
emphasis={'primary'}
size={'lg'}
testID={`${testID}.start.button`}
/>
</Animated.View>
</Animated.View>
</Animated.View>
);
}
``` | /content/code_sandbox/app/components/selected_users/index.tsx | xml | 2016-10-07T16:52:32 | 2024-08-16T12:08:38 | mattermost-mobile | mattermost/mattermost-mobile | 2,155 | 1,763 |
```xml
import RemixLogo from './RemixLogo';
export default RemixLogo;
``` | /content/code_sandbox/packages/remix/test/fixtures-vite/02-interactive-remix-routing-v2/app/components/RemixLogo/index.tsx | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 15 |
```xml
import React, { useContext, useEffect, useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { onAuthStateChanged, User } from 'firebase/auth';
import {
getCurrentUser,
GetCurrentUserResponse,
deleteReview,
deleteFavoritedMovie,
deleteFavoritedActor,
} from '@movie/dataconnect';
import { MdStar } from 'react-icons/md';
import { AuthContext } from '@/lib/firebase';
export default function MyProfilePage() {
const navigate = useNavigate();
const [authUser, setAuthUser] = useState<User | null>(null);
const [user, setUser] = useState<GetCurrentUserResponse['user'] | null>(null);
const [loading, setLoading] = useState(true);
const auth = useContext(AuthContext);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
setAuthUser(user);
fetchUserProfile();
} else {
navigate('/');
}
});
return () => unsubscribe();
}, [navigate, auth]);
async function fetchUserProfile() {
try {
const response = await getCurrentUser();
setUser(response.data.user);
} catch (error) {
console.error('Error fetching user:', error);
} finally {
setLoading(false);
}
}
async function handleDeleteReview(reviewId: string) {
if (!authUser) return;
try {
await deleteReview({ movieId: reviewId });
fetchUserProfile();
} catch (error) {
console.error('Error deleting review:', error);
}
}
async function handleUnfavoriteMovie(movieId: string) {
if (!authUser) return;
try {
await deleteFavoritedMovie({ movieId });
fetchUserProfile();
} catch (error) {
console.error('Error unfavoriting movie:', error);
}
}
async function handleUnfavoriteActor(actorId: string) {
if (!authUser) return;
try {
await deleteFavoritedActor({ actorId });
fetchUserProfile();
} catch (error) {
console.error('Error unfavoriting actor:', error);
}
}
if (loading) return <p>Loading...</p>;
if (!user) return <p>User not found.</p>;
return (
<div className="container mx-auto p-4 bg-gray-900 min-h-screen text-white">
<div className="mb-8">
<h1 className="text-5xl font-bold mb-4">Welcome back, {user.username}</h1>
</div>
<div className="mt-8">
<h2 className="text-2xl font-bold mb-2">Reviews</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{user.reviews.map((review) => (
<div key={review.id} className="bg-gray-800 rounded-lg overflow-scroll shadow-md p-4 relative max-h-72">
<h3 className="font-bold text-lg mb-1 text-white">{review.movie.title}</h3>
<div className="flex items-center text-yellow-500 mb-2">
<MdStar className="text-yellow-500" size={24} />
<span className="ml-1 text-gray-400">{review.rating}</span>
</div>
<p className="text-sm text-gray-400 mb-2">{review.reviewDate}</p>
<p className="text-sm text-gray-300">{review.reviewText}</p>
<button
onClick={() => handleDeleteReview(review.id)}
className="absolute bottom-2 right-2 text-red-500 hover:text-red-600"
>
Delete Review
</button>
</div>
))}
</div>
</div>
<div className="mt-8">
<h2 className="text-2xl font-bold mb-2">Favorite Movies</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{user.favoriteMovies.map((fav) => (
<div key={fav.movie.id} className="bg-gray-800 rounded-lg overflow-scroll shadow-md hover:shadow-lg transition-shadow duration-200 cursor-pointer relative max-h-80">
<Link to={`/movie/${fav.movie.id}`}>
<img className="w-full h-64 object-cover" src={fav.movie.imageUrl} alt={fav.movie.title} />
</Link>
<div className="p-4">
<h3 className="font-bold text-lg mb-1 text-white">{fav.movie.title}</h3>
<p className="text-sm text-gray-400 capitalize">{fav.movie.genre}</p>
<p className="text-sm text-gray-300 overflow-y-scroll max-h-24">{fav.movie.description}</p>
<div className="flex items-center text-yellow-500 mt-2">
<MdStar className="text-yellow-500" size={24} />
<span className="ml-1 text-gray-400">{fav.movie.rating}</span>
</div>
<div className="flex flex-wrap gap-1 mt-2">
{fav.movie.tags?.map((tag, index) => (
<span key={index} className="bg-gray-700 text-white px-2 py-1 rounded-full text-xs capitalize">{tag}</span>
))}
</div>
</div>
<button
onClick={() => handleUnfavoriteMovie(fav.movie.id)}
className="absolute bottom-2 right-2 text-red-500 hover:text-red-600"
>
Remove Favorite
</button>
</div>
))}
</div>
</div>
<div className="mt-8">
<h2 className="text-2xl font-bold mb-2">Favorite Actors</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{user.favoriteActors.map((favActor) => (
<div key={favActor.actor.id} className="bg-gray-800 rounded-lg overflow-scroll shadow-md hover:shadow-lg transition-shadow duration-200 cursor-pointer relative max-h-80">
<Link to={`/actor/${favActor.actor.id}`}>
<img className="w-48 h-48 object-cover rounded-full mx-auto mt-4" src={favActor.actor.imageUrl} alt={favActor.actor.name} />
</Link>
<div className="p-4 text-center">
<h3 className="font-bold text-lg mb-1 text-white">{favActor.actor.name}</h3>
</div>
<button
onClick={() => handleUnfavoriteActor(favActor.actor.id)}
className="absolute bottom-2 right-2 text-red-500 hover:text-red-600"
>
Remove Favorite
</button>
</div>
))}
</div>
</div>
</div>
);
}
``` | /content/code_sandbox/dataconnect/app/src/pages/MyProfile.tsx | xml | 2016-04-26T17:13:48 | 2024-08-16T13:54:58 | quickstart-js | firebase/quickstart-js | 5,069 | 1,501 |
```xml
/**
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import fs from 'fs';
import path from 'path';
import requireString from 'require-from-string';
import { logMetroError } from './metro/metroErrorInterface';
import { getMetroServerRoot } from './middleware/ManifestMiddleware';
import { createBundleUrlPath, ExpoMetroOptions } from './middleware/metroOptions';
import { augmentLogs } from './serverLogLikeMetro';
import { delayAsync } from '../../utils/delay';
import { SilentError } from '../../utils/errors';
import { profile } from '../../utils/profile';
/** The list of input keys will become optional, everything else will remain the same. */
export type PickPartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export const cachedSourceMaps: Map<string, { url: string; map: string }> = new Map();
// Support unhandled rejections
// Detect if running in Bun
// @ts-expect-error: This is a global variable that is set by Bun.
if (!process.isBun) {
require('source-map-support').install({
retrieveSourceMap(source: string) {
if (cachedSourceMaps.has(source)) {
return cachedSourceMaps.get(source);
}
return null;
},
});
}
async function ensureFileInRootDirectory(projectRoot: string, otherFile: string) {
// Cannot be accessed using Metro's server API, we need to move the file
// into the project root and try again.
if (!path.relative(projectRoot, otherFile).startsWith('..' + path.sep)) {
return otherFile;
}
// Copy the file into the project to ensure it works in monorepos.
// This means the file cannot have any relative imports.
const tempDir = path.join(projectRoot, '.expo/static-tmp');
await fs.promises.mkdir(tempDir, { recursive: true });
const moduleId = path.join(tempDir, path.basename(otherFile));
await fs.promises.writeFile(moduleId, await fs.promises.readFile(otherFile, 'utf8'));
// Sleep to give watchman time to register the file.
await delayAsync(50);
return moduleId;
}
export async function createMetroEndpointAsync(
projectRoot: string,
devServerUrl: string,
absoluteFilePath: string,
props: PickPartial<ExpoMetroOptions, 'mainModuleName' | 'bytecode'>
): Promise<string> {
const root = getMetroServerRoot(projectRoot);
const safeOtherFile = await ensureFileInRootDirectory(projectRoot, absoluteFilePath);
const serverPath = path.relative(root, safeOtherFile).replace(/\.[jt]sx?$/, '');
const urlFragment = createBundleUrlPath({
mainModuleName: serverPath,
lazy: false,
asyncRoutes: false,
inlineSourceMap: false,
engine: 'hermes',
minify: false,
bytecode: false,
...props,
});
let url: string;
if (devServerUrl) {
url = new URL(urlFragment.replace(/^\//, ''), devServerUrl).toString();
} else {
url = '/' + urlFragment.replace(/^\/+/, '');
}
return url;
}
export function evalMetroAndWrapFunctions<T = Record<string, any>>(
projectRoot: string,
script: string,
filename: string
): T {
// TODO: Add back stack trace logic that hides traces from metro-runtime and other internal modules.
const contents = evalMetroNoHandling(projectRoot, script, filename);
if (!contents) {
// This can happen if ErrorUtils isn't working correctly on web and failing to throw an error when a module throws.
// This is unexpected behavior and should not be pretty formatted, therefore we're avoiding CommandError.
throw new Error(
'[Expo SSR] Module returned undefined, this could be due to a misconfiguration in Metro error handling'
);
}
// wrap each function with a try/catch that uses Metro's error formatter
return Object.keys(contents).reduce((acc, key) => {
const fn = contents[key];
if (typeof fn !== 'function') {
return { ...acc, [key]: fn };
}
acc[key] = async function (...props: any[]) {
try {
return await fn.apply(this, props);
} catch (error: any) {
await logMetroError(projectRoot, { error });
throw new SilentError(error);
}
};
return acc;
}, {} as any);
}
export function evalMetroNoHandling(projectRoot: string, src: string, filename: string) {
augmentLogs(projectRoot);
return profile(requireString, 'eval-metro-bundle')(src, filename);
}
``` | /content/code_sandbox/packages/@expo/cli/src/start/server/getStaticRenderFunctions.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 1,025 |
```xml
import React from 'react'
import { Emoji } from 'emoji-mart'
import cc from 'classcat'
import Flexbox from '../../design/components/atoms/Flexbox'
import { IconSize } from '../../design/components/atoms/Icon'
import WithDelayedTooltip from '../../design/components/atoms/WithDelayedTooltip'
interface EmojiIconProps {
emoji: string
defaultIcon?: string
className?: string
style?: React.CSSProperties
onClick?: (event: React.MouseEvent<HTMLDivElement>) => void
size?: IconSize
tooltip?: React.ReactNode
emojiTextContent?: React.ReactNode
tooltipDelay: number
tooltipSide?: 'right' | 'bottom' | 'bottom-right' | 'top'
}
const CommentEmoji = ({
emoji,
defaultIcon,
className,
style,
size = 34,
tooltip,
tooltipDelay = 0,
onClick,
emojiTextContent,
tooltipSide,
}: EmojiIconProps) => {
if (emoji == null && defaultIcon == null) {
return null
}
return (
<Flexbox
style={{ marginRight: 5, cursor: 'pointer', ...style }}
flex={'0 0 auto'}
className={cc([onClick != null && 'button', className])}
onClick={onClick}
>
<WithDelayedTooltip
tooltip={tooltip}
tooltipDelay={tooltipDelay}
side={tooltipSide}
>
<Flexbox direction={'row'}>
<Emoji emoji={emoji} set='apple' size={size} />
{emojiTextContent != null && emojiTextContent}
</Flexbox>
</WithDelayedTooltip>
</Flexbox>
)
}
export default CommentEmoji
``` | /content/code_sandbox/src/cloud/components/CommentEmoji.tsx | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 367 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<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.apache.shardingsphere</groupId>
<artifactId>shardingsphere-parser-distsql</artifactId>
<version>5.5.1-SNAPSHOT</version>
</parent>
<artifactId>shardingsphere-parser-distsql-statement</artifactId>
<name>${project.artifactId}</name>
<dependencies>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-infra-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-parser-sql-statement-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-test-util</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
``` | /content/code_sandbox/parser/distsql/statement/pom.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 372 |
```xml
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import { generateXcodeProjectAsync } from './XcodeGen';
import { ProjectSpec } from './XcodeGen.types';
import { Flavor, Framework, XcodebuildSettings } from './XcodeProject.types';
import { formatXcodeBuildOutput } from '../Formatter';
import { spawnAsync } from '../Utils';
/**
* Path to the shared derived data directory.
*/
const SHARED_DERIVED_DATA_DIR = path.join(os.tmpdir(), 'Expo/DerivedData');
/**
* Path to the products in derived data directory. We pick `.framework` files from there.
*/
const PRODUCTS_DIR = path.join(SHARED_DERIVED_DATA_DIR, 'Build/Products');
/**
* A class representing single Xcode project and operating on its `.xcodeproj` file.
*/
export default class XcodeProject {
/**
* Creates `XcodeProject` instance from given path to `.xcodeproj` file.
*/
static async fromXcodeprojPathAsync(xcodeprojPath: string): Promise<XcodeProject> {
if (!(await fs.pathExists(xcodeprojPath))) {
throw new Error(`Xcodeproj not found at path: ${xcodeprojPath}`);
}
return new XcodeProject(xcodeprojPath);
}
/**
* Generates `.xcodeproj` file based on given spec and returns it.
*/
static async generateProjectFromSpec(dir: string, spec: ProjectSpec): Promise<XcodeProject> {
const xcodeprojPath = await generateXcodeProjectAsync(dir, spec);
return new XcodeProject(xcodeprojPath);
}
/**
* Name of the project. It should stay in sync with its filename.
*/
name: string;
/**
* Root directory of the project and at which the `.xcodeproj` file is placed.
*/
rootDir: string;
constructor(xcodeprojPath: string) {
this.name = path.basename(xcodeprojPath, '.xcodeproj');
this.rootDir = path.dirname(xcodeprojPath);
}
/**
* Returns output path to where the `.xcframework` file will be stored after running `buildXcframeworkAsync`.
*/
getXcframeworkPath(): string {
return path.join(this.rootDir, `${this.name}.xcframework`);
}
/**
* Builds `.framework` for given target name and flavor specifying,
* configuration, the SDK and a list of architectures to compile against.
*/
async buildFrameworkAsync(
target: string,
flavor: Flavor,
options?: XcodebuildSettings
): Promise<Framework> {
await this.xcodebuildAsync(
[
'build',
'-project',
`${this.name}.xcodeproj`,
'-scheme',
`${target}_iOS`,
'-configuration',
flavor.configuration,
'-sdk',
flavor.sdk,
...spreadArgs('-arch', flavor.archs),
'-derivedDataPath',
SHARED_DERIVED_DATA_DIR,
],
options
);
const frameworkPath = flavorToFrameworkPath(target, flavor);
const stat = await fs.lstat(path.join(frameworkPath, target));
// Remove `Headers` as each our module contains headers as part of the provided source code
// and CocoaPods exposes them through HEADER_SEARCH_PATHS either way.
await fs.remove(path.join(frameworkPath, 'Headers'));
// `_CodeSignature` is apparently generated only for simulator, afaik we don't need it.
await fs.remove(path.join(frameworkPath, '_CodeSignature'));
return {
target,
flavor,
frameworkPath,
binarySize: stat.size,
};
}
/**
* Builds universal `.xcframework` from given frameworks.
*/
async buildXcframeworkAsync(
frameworks: Framework[],
options?: XcodebuildSettings
): Promise<string> {
const frameworkPaths = frameworks.map((framework) => framework.frameworkPath);
const outputPath = this.getXcframeworkPath();
await fs.remove(outputPath);
await this.xcodebuildAsync(
['-create-xcframework', ...spreadArgs('-framework', frameworkPaths), '-output', outputPath],
options
);
return outputPath;
}
/**
* Removes `.xcframework` artifact produced by `buildXcframeworkAsync`.
*/
async cleanXcframeworkAsync(): Promise<void> {
await fs.remove(this.getXcframeworkPath());
}
/**
* Generic function spawning `xcodebuild` process.
*/
async xcodebuildAsync(args: string[], settings?: XcodebuildSettings) {
// `xcodebuild` writes error details to stdout but we don't want to pollute our output if nothing wrong happens.
// Spawn it quietly, pipe stderr to stdout and pass it to the current process stdout only when it fails.
const finalArgs = ['-quiet', ...args, '2>&1'];
if (settings) {
finalArgs.unshift(
...Object.entries(settings).map(([key, value]) => {
return `${key}=${parseXcodeSettingsValue(value)}`;
})
);
}
try {
await spawnAsync('xcodebuild', finalArgs, {
cwd: this.rootDir,
shell: true,
stdio: ['ignore', 'pipe', 'inherit'],
});
} catch (e) {
// Print formatted Xcode logs (merged from stdout and stderr).
process.stdout.write(formatXcodeBuildOutput(e.stdout));
throw e;
}
}
/**
* Cleans shared derived data directory.
*/
static async cleanBuildFolderAsync(): Promise<void> {
await fs.remove(SHARED_DERIVED_DATA_DIR);
}
}
/**
* Returns a path to the prebuilt framework for given flavor.
*/
function flavorToFrameworkPath(target: string, flavor: Flavor): string {
return path.join(PRODUCTS_DIR, `${flavor.configuration}-${flavor.sdk}`, `${target}.framework`);
}
/**
* Spreads given args under specific flag.
* Example: `spreadArgs('-arch', ['arm64', 'x86_64'])` returns `['-arch', 'arm64', '-arch', 'x86_64']`
*/
function spreadArgs(argName: string, args: string[]): string[] {
return ([] as string[]).concat(...args.map((arg) => [argName, arg]));
}
/**
* Converts boolean values to its Xcode build settings format. Value of other type just passes through.
*/
function parseXcodeSettingsValue(value: string | boolean): string {
if (typeof value === 'boolean') {
return value ? 'YES' : 'NO';
}
return value;
}
``` | /content/code_sandbox/tools/src/prebuilds/XcodeProject.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 1,422 |
```xml
import { Component } from '@angular/core';
@Component({
selector: 'clustering-demo',
styleUrls: ['./clustering-demo.component.scss'],
templateUrl: './clustering-demo.component.html',
})
export class ClusteringDemoComponent {}
``` | /content/code_sandbox/apps/docs-app/src/app/content/echarts/echarts-demos/clustering/demos/clustering-demo.component.ts | xml | 2016-07-11T23:30:52 | 2024-08-15T15:20:45 | covalent | Teradata/covalent | 2,228 | 48 |
```xml
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<dataset>
<metadata>
<column name="transition_time" />
<column name="correction" />
</metadata>
</dataset>
``` | /content/code_sandbox/test/e2e/sql/src/test/resources/cases/dql/dataset/empty_storage_units/mysql/select_mysql_mysql_time_zone_leap_second.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 104 |
```xml
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<abp-loader-bar></abp-loader-bar>
<abp-dynamic-layout></abp-dynamic-layout>
<abp-internet-status></abp-internet-status>
`,
})
export class AppComponent {}
``` | /content/code_sandbox/templates/app/angular/src/app/app.component.ts | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 70 |
```xml
import { LitElement } from 'lit';
export type UnpackCustomEvent<T> = T extends CustomEvent<infer U> ? U : never;
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export class MduiElement<E> extends LitElement {
/**
* false
* @param type
* @param options cancelable detailbubblescomposed
*/
protected emit<K extends keyof E, D extends UnpackCustomEvent<E[K]>>(
type: K,
options?: CustomEventInit<D>,
): boolean {
const event = new CustomEvent<D>(
type as string,
Object.assign(
{
bubbles: true,
cancelable: false,
composed: true,
detail: {},
},
options,
),
);
return this.dispatchEvent(event);
}
}
export interface MduiElement<E> {
addEventListener<K extends keyof M, M extends E & HTMLElementEventMap>(
type: K,
listener: (this: this, ev: M[K]) => unknown,
options?: boolean | AddEventListenerOptions,
): void;
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions,
): void;
removeEventListener<K extends keyof M, M extends E & HTMLElementEventMap>(
type: K,
listener: (this: this, ev: M[K]) => unknown,
options?: boolean | EventListenerOptions,
): void;
removeEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions,
): void;
}
``` | /content/code_sandbox/packages/shared/src/base/mdui-element.ts | xml | 2016-07-11T17:39:02 | 2024-08-16T07:12:34 | mdui | zdhxiong/mdui | 4,077 | 355 |
```xml
import { Component, OnInit } from '@angular/core';
import { Code } from '@domain/code';
interface City {
name: string;
code: string;
}
@Component({
selector: 'filter-doc',
template: `
<app-docsectiontext>
<p>MultiSelect provides built-in filtering that is enabled by adding the <i>filter</i> property.</p>
</app-docsectiontext>
<div class="card flex justify-content-center">
<p-multiSelect [options]="cities" [(ngModel)]="selectedCities" [filter]="true" optionLabel="name" placeholder="Select Cities" />
</div>
<app-code [code]="code" selector="multi-select-filter-demo"></app-code>
`
})
export class FilterDoc implements OnInit {
cities!: City[];
selectedCities!: City[];
ngOnInit() {
this.cities = [
{ name: 'New York', code: 'NY' },
{ name: 'Rome', code: 'RM' },
{ name: 'London', code: 'LDN' },
{ name: 'Istanbul', code: 'IST' },
{ name: 'Paris', code: 'PRS' }
];
}
code: Code = {
basic: `<p-multiSelect
[options]="cities"
[(ngModel)]="selectedCities"
[filter]="true"
optionLabel="name"
placeholder="Select Cities" />`,
html: `<div class="card flex justify-content-center">
<p-multiSelect
[options]="cities"
[(ngModel)]="selectedCities"
[filter]="true"
optionLabel="name"
placeholder="Select Cities" />
</div>`,
typescript: `import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MultiSelectModule } from 'primeng/multiselect';
interface City {
name: string,
code: string
}
@Component({
selector: 'multi-select-filter-demo',
templateUrl: './multi-select-filter-demo.html',
standalone: true,
imports: [FormsModule, MultiSelectModule]
})
export class MultiSelectFilterDemo implements OnInit {
cities!: City[];
selectedCities!: City[];
ngOnInit() {
this.cities = [
{ name: 'New York', code: 'NY' },
{ name: 'Rome', code: 'RM' },
{ name: 'London', code: 'LDN' },
{ name: 'Istanbul', code: 'IST' },
{ name: 'Paris', code: 'PRS' }
];
}
}`
};
}
``` | /content/code_sandbox/src/app/showcase/doc/multiselect/filterdoc.ts | xml | 2016-01-16T09:23:28 | 2024-08-16T19:58:20 | primeng | primefaces/primeng | 9,969 | 573 |
```xml
import "../utilities/globals/index.js";
export type {
Transaction,
WatchFragmentOptions,
WatchFragmentResult,
} from "./core/cache.js";
export { ApolloCache } from "./core/cache.js";
export { Cache } from "./core/types/Cache.js";
export type { DataProxy } from "./core/types/DataProxy.js";
export type {
MissingTree,
Modifier,
Modifiers,
ModifierDetails,
ReadFieldOptions,
} from "./core/types/common.js";
export { MissingFieldError } from "./core/types/common.js";
export type { Reference } from "../utilities/index.js";
export {
isReference,
makeReference,
canonicalStringify,
} from "../utilities/index.js";
export { EntityStore } from "./inmemory/entityStore.js";
export {
fieldNameFromStoreName,
defaultDataIdFromObject,
} from "./inmemory/helpers.js";
export { InMemoryCache } from "./inmemory/inMemoryCache.js";
export type { ReactiveVar } from "./inmemory/reactiveVars.js";
export { makeVar, cacheSlot } from "./inmemory/reactiveVars.js";
export type {
TypePolicies,
TypePolicy,
FieldPolicy,
FieldReadFunction,
FieldMergeFunction,
FieldFunctionOptions,
PossibleTypesMap,
} from "./inmemory/policies.js";
export { Policies } from "./inmemory/policies.js";
export type { FragmentRegistryAPI } from "./inmemory/fragmentRegistry.js";
export { createFragmentRegistry } from "./inmemory/fragmentRegistry.js";
export * from "./inmemory/types.js";
``` | /content/code_sandbox/src/cache/index.ts | xml | 2016-02-26T20:25:00 | 2024-08-16T10:56:57 | apollo-client | apollographql/apollo-client | 19,304 | 326 |
```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="zh-Hans" original="../Resources.resx">
<body>
<trans-unit id="BI0000">
<source>Unexpected error - Please fill a bug report at path_to_url
<target state="new">Unexpected error - Please fill a bug report at path_to_url
<note></note>
</trans-unit>
<trans-unit id="BI0001">
<source>The .NET runtime could not load the {0} type. Message: {1}</source>
<target state="new">The .NET runtime could not load the {0} type. Message: {1}</target>
<note></note>
</trans-unit>
<trans-unit id="BI0002">
<source>Could not compile the API bindings.
{0}
</source>
<target state="new">Could not compile the API bindings.
{0}
</target>
<note></note>
</trans-unit>
<trans-unit id="BI0026">
<source>Could not parse the command line argument '--warnaserror': {0}</source>
<target state="new">Could not parse the command line argument '--warnaserror': {0}</target>
<note />
</trans-unit>
<trans-unit id="BI0068">
<source>Invalid value for target framework: {0}.</source>
<target state="new">Invalid value for target framework: {0}.</target>
<note />
</trans-unit>
<trans-unit id="BI0070">
<source>Invalid target framework: {0}. Valid target frameworks are: {1}.</source>
<target state="new">Invalid target framework: {0}. Valid target frameworks are: {1}.</target>
<note />
</trans-unit>
<trans-unit id="BI0086">
<source>A target framework (--target-framework) must be specified.</source>
<target state="new">A target framework (--target-framework) must be specified.</target>
<note />
</trans-unit>
<trans-unit id="BI0087">
<source>Xamarin.Mac Classic binding projects are not supported anymore. Please upgrade the binding project to a Xamarin.Mac Unified binding project.</source>
<target state="new">Xamarin.Mac Classic binding projects are not supported anymore. Please upgrade the binding project to a Xamarin.Mac Unified binding project.</target>
<note />
</trans-unit>
<trans-unit id="BI0088">
<source>Internal error: don't know how to create ref/out (input) code for {0} in {1}. Please file a bug report with a test case (path_to_url
<target state="new">Internal error: don't know how to create ref/out (input) code for {0} in {1}. Please file a bug report with a test case (path_to_url
<note />
</trans-unit>
<trans-unit id="BI0089">
<source>Internal error: property {0} doesn't have neither a getter nor a setter.</source>
<target state="new">Internal error: property {0} doesn't have neither a getter nor a setter.</target>
<note />
</trans-unit>
<trans-unit id="BI0099">
<source>Internal error {0}. Please file a bug report with a test case (path_to_url
<target state="new">Internal error {0}. Please file a bug report with a test case (path_to_url
<note />
</trans-unit>
<trans-unit id="BI1000">
<source>Could not compile the generated API bindings.
{0}
</source>
<target state="new">Could not compile the generated API bindings.
{0}
</target>
<note></note>
</trans-unit>
<trans-unit id="BI1001">
<source>Do not know how to make a trampoline for {0}</source>
<target state="new">Do not know how to make a trampoline for {0}</target>
<note />
</trans-unit>
<trans-unit id="BI1002">
<source>Unknown kind {0} in method '{1}.{2}'</source>
<target state="new">Unknown kind {0} in method '{1}.{2}'</target>
<note />
</trans-unit>
<trans-unit id="BI1003">
<source>The delegate method {0}.{1} needs to take at least one parameter</source>
<target state="new">The delegate method {0}.{1} needs to take at least one parameter</target>
<note />
</trans-unit>
<trans-unit id="BI1004">
<source>The delegate method {0}.{1} is missing the [EventArgs] attribute (has {2} parameters)</source>
<target state="new">The delegate method {0}.{1} is missing the [EventArgs] attribute (has {2} parameters)</target>
<note />
</trans-unit>
<trans-unit id="BI1005">
<source>EventArgs in {0}.{1} attribute should not include the text `EventArgs' at the end</source>
<target state="new">EventArgs in {0}.{1} attribute should not include the text `EventArgs' at the end</target>
<note />
</trans-unit>
<trans-unit id="BI1006">
<source>The delegate method {0}.{1} is missing the [DelegateName] attribute (or EventArgs)</source>
<target state="new">The delegate method {0}.{1} is missing the [DelegateName] attribute (or EventArgs)</target>
<note />
</trans-unit>
<trans-unit id="BI1007">
<source>Unknown attribute {0} on {1}.{2}</source>
<target state="new">Unknown attribute {0} on {1}.{2}</target>
<note />
</trans-unit>
<trans-unit id="BI1008">
<source>[IsThreadStatic] is only valid on properties that are also [Static]</source>
<target state="new">[IsThreadStatic] is only valid on properties that are also [Static]</target>
<note />
</trans-unit>
<trans-unit id="BI1009">
<source>No selector specified for method `{0}.{1}'</source>
<target state="new">No selector specified for method `{0}.{1}'</target>
<note />
</trans-unit>
<trans-unit id="BI1010">
<source>No Export attribute on {0}.{1} property</source>
<target state="new">No Export attribute on {0}.{1} property</target>
<note />
</trans-unit>
<trans-unit id="BI1011">
<source>Do not know how to extract type {0}/{1} from an NSDictionary</source>
<target state="new">Do not know how to extract type {0}/{1} from an NSDictionary</target>
<note />
</trans-unit>
<trans-unit id="BI1012">
<source>No Export or Bind attribute defined on {0}.{1}</source>
<target state="new">No Export or Bind attribute defined on {0}.{1}</target>
<note />
</trans-unit>
<trans-unit id="BI1013">
<source>Unsupported type for Fields (string), you probably meant NSString</source>
<target state="new">Unsupported type for Fields (string), you probably meant NSString</target>
<note />
</trans-unit>
<trans-unit id="BI1014">
<source>Unsupported type for Fields: {0} for '{1}'.</source>
<target state="new">Unsupported type for Fields: {0} for '{1}'.</target>
<note />
</trans-unit>
<trans-unit id="BI1015">
<source>In class {0} You specified the Events property, but did not bind those to names with Delegates</source>
<target state="new">In class {0} You specified the Events property, but did not bind those to names with Delegates</target>
<note />
</trans-unit>
<trans-unit id="BI1016">
<source>The delegate method {0}.{1} is missing the [DefaultValue] attribute</source>
<target state="new">The delegate method {0}.{1} is missing the [DefaultValue] attribute</target>
<note />
</trans-unit>
<trans-unit id="BI1017">
<source>Do not know how to make a signature for {0}</source>
<target state="new">Do not know how to make a signature for {0}</target>
<note />
</trans-unit>
<trans-unit id="BI1018">
<source>No [Export] attribute on property {0}.{1}</source>
<target state="new">No [Export] attribute on property {0}.{1}</target>
<note />
</trans-unit>
<trans-unit id="BI1019">
<source>Invalid [NoDefaultValue] attribute on method '{0}.{1}'</source>
<target state="new">Invalid [NoDefaultValue] attribute on method '{0}.{1}'</target>
<note />
</trans-unit>
<trans-unit id="BI1020">
<source>Unsupported type {0} used on exported method {1}.{2} -> {3}</source>
<target state="new">Unsupported type {0} used on exported method {1}.{2} -> {3}</target>
<note />
</trans-unit>
<trans-unit id="BI1021">
<source>Unsupported type for read/write Fields: {0} for {1}.{2}</source>
<target state="new">Unsupported type for read/write Fields: {0} for {1}.{2}</target>
<note />
</trans-unit>
<trans-unit id="BI1022">
<source>Model classes can not be categories</source>
<target state="new">Model classes can not be categories</target>
<note />
</trans-unit>
<trans-unit id="BI1023">
<source>The number of Events (Type) and Delegates (string) must match for `{0}`</source>
<target state="new">The number of Events (Type) and Delegates (string) must match for `{0}`</target>
<note />
</trans-unit>
<trans-unit id="BI1024">
<source>No selector specified for property '{0}.{1}'</source>
<target state="new">No selector specified for property '{0}.{1}'</target>
<note />
</trans-unit>
<trans-unit id="BI1025">
<source>[Static] and [Protocol] are mutually exclusive ({0})</source>
<target state="new">[Static] and [Protocol] are mutually exclusive ({0})</target>
<note />
</trans-unit>
<trans-unit id="BI1026">
<source>`{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong`</source>
<target state="new">`{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong`</target>
<note />
</trans-unit>
<trans-unit id="BI1027">
<source>Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings.</source>
<target state="new">Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings.</target>
<note />
</trans-unit>
<trans-unit id="BI1028">
<source>Internal sanity check failed, please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal sanity check failed, please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1029">
<source>Internal error: invalid enum mode for type '{0}'</source>
<target state="new">Internal error: invalid enum mode for type '{0}'</target>
<note />
</trans-unit>
<trans-unit id="BI1030">
<source>{0} cannot have [BaseType(typeof({1}))] as it creates a circular dependency</source>
<target state="new">{0} cannot have [BaseType(typeof({1}))] as it creates a circular dependency</target>
<note />
</trans-unit>
<trans-unit id="BI1031">
<source>The [Target] attribute is not supported for the Unified API (found on the member '{0}.{1}'). For Objective-C categories, create an api definition interface with the [Category] attribute instead.</source>
<target state="new">The [Target] attribute is not supported for the Unified API (found on the member '{0}.{1}'). For Objective-C categories, create an api definition interface with the [Category] attribute instead.</target>
<note />
</trans-unit>
<trans-unit id="BI1032">
<source>No support for setters in StrongDictionary classes for type {0} in {1}.{2}</source>
<target state="new">No support for setters in StrongDictionary classes for type {0} in {1}.{2}</target>
<note />
</trans-unit>
<trans-unit id="BI1033">
<source>Limitation: can not automatically create strongly typed dictionary for ({0}) the value type of the {1}.{2} property</source>
<target state="new">Limitation: can not automatically create strongly typed dictionary for ({0}) the value type of the {1}.{2} property</target>
<note>Generating a strongly typed dictionary for type '{0}' is not supported.
{0} - the property type.
{1} - the dictionary type.
{2} - the property name.
</note>
</trans-unit>
<trans-unit id="BI1034">
<source>The [Protocolize] attribute is set on the member {0}.{1}, but the member's type ({2}) is not a protocol.</source>
<target state="new">The [Protocolize] attribute is set on the member {0}.{1}, but the member's type ({2}) is not a protocol.</target>
<note />
</trans-unit>
<trans-unit id="BI1035">
<source>The property {0} on class {1} is hiding a property from a parent class {2} but the selectors do not match.</source>
<target state="new">The property {0} on class {1} is hiding a property from a parent class {2} but the selectors do not match.</target>
<note />
</trans-unit>
<trans-unit id="BI1036">
<source>The last parameter in the method '{0}.{1}' must be a delegate (it's '{2}').</source>
<target state="new">The last parameter in the method '{0}.{1}' must be a delegate (it's '{2}').</target>
<note />
</trans-unit>
<trans-unit id="BI1037">
<source>The selector {0} on type {1} is found multiple times with both read only and write only versions, with no read/write version.</source>
<target state="new">The selector {0} on type {1} is found multiple times with both read only and write only versions, with no read/write version.</target>
<note />
</trans-unit>
<trans-unit id="BI1038">
<source>The selector {0} on type {1} is found multiple times with different return types.</source>
<target state="new">The selector {0} on type {1} is found multiple times with different return types.</target>
<note />
</trans-unit>
<trans-unit id="BI1039">
<source>The selector {0} on type {1} is found multiple times with different argument length {2} : {3}.</source>
<target state="new">The selector {0} on type {1} is found multiple times with different argument length {2} : {3}.</target>
<note />
</trans-unit>
<trans-unit id="BI1040">
<source>The selector {0} on type {1} is found multiple times with different argument out states on argument {2}.</source>
<target state="new">The selector {0} on type {1} is found multiple times with different argument out states on argument {2}.</target>
<note />
</trans-unit>
<trans-unit id="BI1041">
<source>The selector {0} on type {1} is found multiple times with different argument types on argument {2} - {3} : {4}. </source>
<target state="new">The selector {0} on type {1} is found multiple times with different argument types on argument {2} - {3} : {4}. </target>
<note></note>
</trans-unit>
<trans-unit id="BI1042">
<source>Missing '[Field (LibraryName=value)]' for {0} (e.g."__Internal")</source>
<target state="new">Missing '[Field (LibraryName=value)]' for {0} (e.g."__Internal")</target>
<note />
</trans-unit>
<trans-unit id="BI1043">
<source>Repeated overload {0} and no [DelegateApiNameAttribute] provided to generate property name on host class.</source>
<target state="new">Repeated overload {0} and no [DelegateApiNameAttribute] provided to generate property name on host class.</target>
<note />
</trans-unit>
<trans-unit id="BI1044">
<source>Repeated name '{0}' provided in [DelegateApiNameAttribute].</source>
<target state="new">Repeated name '{0}' provided in [DelegateApiNameAttribute].</target>
<note />
</trans-unit>
<trans-unit id="BI1045">
<source>Only a single [DefaultEnumValue] attribute can be used inside enum {0}.</source>
<target state="new">Only a single [DefaultEnumValue] attribute can be used inside enum {0}.</target>
<note />
</trans-unit>
<trans-unit id="BI1046">
<source>The [Field] constant {0} cannot only be used once inside enum {1}.</source>
<target state="new">The [Field] constant {0} cannot only be used once inside enum {1}.</target>
<note />
</trans-unit>
<trans-unit id="BI1047">
<source>Unsupported platform: {0}. Please file a bug report (path_to_url with a test case.</source>
<target state="new">Unsupported platform: {0}. Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1048">
<source>Unsupported type {0} decorated with [BindAs]</source>
<target state="new">Unsupported type {0} decorated with [BindAs]</target>
<note />
</trans-unit>
<trans-unit id="BI1049">
<source>Could not {0} type {1} from {2} {3} used on member {4} decorated with [BindAs].</source>
<target state="new">Could not {0} type {1} from {2} {3} used on member {4} decorated with [BindAs].</target>
<note />
</trans-unit>
<trans-unit id="BI1050">
<source>[BindAs] cannot be used inside Protocol or Model types. Type: {0}</source>
<target state="new">[BindAs] cannot be used inside Protocol or Model types. Type: {0}</target>
<note />
</trans-unit>
<trans-unit id="BI1051">
<source>Internal error: Don't know how to get attributes for {0}. Please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal error: Don't know how to get attributes for {0}. Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1052">
<source>Internal error: Could not find the type {0} in the assembly {1}. Please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal error: Could not find the type {0} in the assembly {1}. Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1053">
<source>Internal error: unknown target framework '{0}'.</source>
<target state="new">Internal error: unknown target framework '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="BI1054">
<source>Internal error: can't convert type '{0}' (unknown assembly). Please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal error: can't convert type '{0}' (unknown assembly). Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1055">
<source>Internal error: failed to convert type '{0}'. Please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal error: failed to convert type '{0}'. Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1056">
<source>Internal error: failed to instantiate mock attribute '{0}' (could not convert type constructor argument #{1}). Please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal error: failed to instantiate mock attribute '{0}' (could not convert type constructor argument #{1}). Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1057">
<source>Internal error: failed to instantiate mock attribute '{0}' (could not convert constructor type #{1} ({2})). Please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal error: failed to instantiate mock attribute '{0}' (could not convert constructor type #{1} ({2})). Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1058">
<source>Internal error: could not find a constructor for the mock attribute '{0}'. Please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal error: could not find a constructor for the mock attribute '{0}'. Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1059">
<source>Found {0} {1} attributes on the member {2}. At most one was expected.</source>
<target state="new">Found {0} {1} attributes on the member {2}. At most one was expected.</target>
<note />
</trans-unit>
<trans-unit id="BI1060">
<source>The {0} protocol is decorated with [Model], but not [BaseType]. Please verify that [Model] is relevant for this protocol; if so, add [BaseType] as well, otherwise remove [Model].</source>
<target state="new">The {0} protocol is decorated with [Model], but not [BaseType]. Please verify that [Model] is relevant for this protocol; if so, add [BaseType] as well, otherwise remove [Model].</target>
<note />
</trans-unit>
<trans-unit id="BI1061">
<source>The attribute '{0}' found on '{1}' is not a valid binding attribute. Please remove this attribute.</source>
<target state="new">The attribute '{0}' found on '{1}' is not a valid binding attribute. Please remove this attribute.</target>
<note />
</trans-unit>
<trans-unit id="BI1062">
<source>The member '{0}.{1}' contains ref/out parameters and must not be decorated with [Async].</source>
<target state="new">The member '{0}.{1}' contains ref/out parameters and must not be decorated with [Async].</target>
<note />
</trans-unit>
<trans-unit id="BI1063">
<source>The 'WrapAttribute' can only be used at the property or at getter/setter level at a given time. Property: '{0}.{1}'</source>
<target state="new">The 'WrapAttribute' can only be used at the property or at getter/setter level at a given time. Property: '{0}.{1}'</target>
<note />
</trans-unit>
<trans-unit id="BI1064">
<source>Unsupported ref/out parameter type '{0}' for the parameter '{1}' in {2}.{3}.</source>
<target state="new">Unsupported ref/out parameter type '{0}' for the parameter '{1}' in {2}.{3}.</target>
<note />
</trans-unit>
<trans-unit id="BI1065">
<source>Unsupported parameter type '{0}' for the parameter '{1}' in {2}.{3}.</source>
<target state="new">Unsupported parameter type '{0}' for the parameter '{1}' in {2}.{3}.</target>
<note />
</trans-unit>
<trans-unit id="BI1066">
<source>Unsupported return type '{0}' in {1}.{2}.</source>
<target state="new">Unsupported return type '{0}' in {1}.{2}.</target>
<note />
</trans-unit>
<trans-unit id="BI1067">
<source>The type '{0}' is trying to inline the property '{1}' from the protocols '{2}' and '{3}', but the inlined properties don't share the same accessors ('{4}' is read-only, while '${5}' is write-only).</source>
<target state="new">The type '{0}' is trying to inline the property '{1}' from the protocols '{2}' and '{3}', but the inlined properties don't share the same accessors ('{4}' is read-only, while '${5}' is write-only).</target>
<note />
</trans-unit>
<trans-unit id="BI1068">
<source>The type '{0}' is trying to inline the property '{1}' from the protocols '{2}' and '{3}', and the inlined properties use different selectors ({4}.{5} uses '{6}', and {7}.{8} uses '{9}'.</source>
<target state="new">The type '{0}' is trying to inline the property '{1}' from the protocols '{2}' and '{3}', and the inlined properties use different selectors ({4}.{5} uses '{6}', and {7}.{8} uses '{9}'.</target>
<note />
</trans-unit>
<trans-unit id="BI1069">
<source>The type '{0}' is trying to inline the methods binding the selector '{1}' from the protocols '{2}' and '{3}', using methods with different signatures ('{4}' vs '{5}').</source>
<target state="new">The type '{0}' is trying to inline the methods binding the selector '{1}' from the protocols '{2}' and '{3}', using methods with different signatures ('{4}' vs '{5}').</target>
<note />
</trans-unit>
<trans-unit id="BI1070">
<source>The type '{0}' is trying to inline the property '{1}' from the protocols '{2}' and '{3}', but the inlined properties are of different types ('{4}' is {5}, while '{6}' is {7}).</source>
<target state="new">The type '{0}' is trying to inline the property '{1}' from the protocols '{2}' and '{3}', but the inlined properties are of different types ('{4}' is {5}, while '{6}' is {7}).</target>
<note />
</trans-unit>
<trans-unit id="BI1071">
<source>The BindAs type for the member "{0}.{1}" must be an array when the member's type is an array.</source>
<target state="new">The BindAs type for the member "{0}.{1}" must be an array when the member's type is an array.</target>
<note />
</trans-unit>
<trans-unit id="BI1072">
<source>The BindAs type for the parameter "{0}" in the method "{1}.{2}" must be an array when the parameter's type is an array.</source>
<target state="new">The BindAs type for the parameter "{0}" in the method "{1}.{2}" must be an array when the parameter's type is an array.</target>
<note />
</trans-unit>
<trans-unit id="BI1073">
<source>Internal error: failed to instantiate mock attribute '{0}' (unknown type for the named argument #{1} ({2}). Please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal error: failed to instantiate mock attribute '{0}' (unknown type for the named argument #{1} ({2}). Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="BI1074">
<source> Missing [CoreImageFilterProperty] attribute on {0} property {1}</source>
<target state="new"> Missing [CoreImageFilterProperty] attribute on {0} property {1}</target>
<note />
</trans-unit>
<trans-unit id="BI1075">
<source>Unimplemented CoreImage property type {0}</source>
<target state="new">Unimplemented CoreImage property type {0}</target>
<note />
</trans-unit>
<trans-unit id="BI1076">
<source>Unable to find selector for {0} on {1} on self or base class</source>
<target state="new">Unable to find selector for {0} on {1} on self or base class</target>
<note />
</trans-unit>
<trans-unit id="BI1077">
<source>Async method {0} with more than one result parameter in the callback by neither ResultTypeName or ResultType</source>
<target state="new">Async method {0} with more than one result parameter in the callback by neither ResultTypeName or ResultType</target>
<note>A message for an asynchronous method with more than one result parameter. The following are literal names and should not be translated: ResultTypeName, ResultType
{0} - The method name.
</note>
</trans-unit>
<trans-unit id="BI1078">
<source>{0} in method `{1}'</source>
<target state="new">{0} in method `{1}'</target>
<note />
</trans-unit>
<trans-unit id="BI1079">
<source>{0} in parameter `{1}' from {2}.{3}</source>
<target state="new">{0} in parameter `{1}' from {2}.{3}</target>
<note />
</trans-unit>
<trans-unit id="BI1080">
<source>Unsupported type 'ref/out {0}' decorated with [BindAs]</source>
<target state="new">Unsupported type 'ref/out {0}' decorated with [BindAs]</target>
<note />
</trans-unit>
<trans-unit id="BI1081">
<source>Unable to find the assembly '{0}'. Add it as a reference using its full path.</source>
<target state="new">Unable to find the assembly '{0}'. Add it as a reference using its full path.</target>
<note />
</trans-unit>
<trans-unit id="BI1101">
<source>Trying to use a string as a [Target]</source>
<target state="new">Trying to use a string as a [Target]</target>
<note />
</trans-unit>
<trans-unit id="BI1102">
<source>Using the deprecated 'EventArgs' for a delegate signature in {0}.{1}, please use 'DelegateName' instead.</source>
<target state="new">Using the deprecated 'EventArgs' for a delegate signature in {0}.{1}, please use 'DelegateName' instead.</target>
<note />
</trans-unit>
<trans-unit id="BI1103">
<source>'{0}' does not live under a namespace; namespaces are a highly recommended .NET best practice</source>
<target state="new">'{0}' does not live under a namespace; namespaces are a highly recommended .NET best practice</target>
<note />
</trans-unit>
<trans-unit id="BI1104">
<source>Could not load the referenced library '{0}': {1}.</source>
<target state="new">Could not load the referenced library '{0}': {1}.</target>
<note />
</trans-unit>
<trans-unit id="BI1105">
<source>Potential selector/argument mismatch [Export ("{0}")] has {1} arguments and {2} has {3} arguments</source>
<target state="new">Potential selector/argument mismatch [Export ("{0}")] has {1} arguments and {2} has {3} arguments</target>
<note />
</trans-unit>
<trans-unit id="BI1106">
<source>The parameter {2} in the method {0}.{1} exposes a model ({3}). Please expose the corresponding protocol type instead ({4}.I{5}).</source>
<target state="new">The parameter {2} in the method {0}.{1} exposes a model ({3}). Please expose the corresponding protocol type instead ({4}.I{5}).</target>
<note />
</trans-unit>
<trans-unit id="BI1107">
<source>The return type of the method {0}.{1} exposes a model ({2}). Please expose the corresponding protocol type instead ({3}.I{4}).</source>
<target state="new">The return type of the method {0}.{1} exposes a model ({2}). Please expose the corresponding protocol type instead ({3}.I{4}).</target>
<note />
</trans-unit>
<trans-unit id="BI1108">
<source>The [Protocolize] attribute is applied to the return type of the method {0}.{1}, but the return type ({2}) isn't a model and can thus not be protocolized. Please remove the [Protocolize] attribute.</source>
<target state="new">The [Protocolize] attribute is applied to the return type of the method {0}.{1}, but the return type ({2}) isn't a model and can thus not be protocolized. Please remove the [Protocolize] attribute.</target>
<note />
</trans-unit>
<trans-unit id="BI1109">
<source>The return type of the method {0}.{1} exposes a model ({2}). Please expose the corresponding protocol type instead ({3}.I{4}).</source>
<target state="new">The return type of the method {0}.{1} exposes a model ({2}). Please expose the corresponding protocol type instead ({3}.I{4}).</target>
<note />
</trans-unit>
<trans-unit id="BI1110">
<source>The property {0}.{1} exposes a model ({2}). Please expose the corresponding protocol type instead ({3}.I{4}).</source>
<target state="new">The property {0}.{1} exposes a model ({2}). Please expose the corresponding protocol type instead ({3}.I{4}).</target>
<note />
</trans-unit>
<trans-unit id="BI1111">
<source>Interface '{0}' on '{1}' is being ignored as it is not a protocol. Did you mean '{2}' instead?</source>
<target state="new">Interface '{0}' on '{1}' is being ignored as it is not a protocol. Did you mean '{2}' instead?</target>
<note />
</trans-unit>
<trans-unit id="BI1112">
<source>Property {0} should be renamed to 'Delegate' for BaseType.Events and BaseType.Delegates to work.</source>
<target state="new">Property {0} should be renamed to 'Delegate' for BaseType.Events and BaseType.Delegates to work.</target>
<note />
</trans-unit>
<trans-unit id="BI1113">
<source>BaseType.Delegates were set but no properties could be found. Do ensure that the WrapAttribute is used on the right properties.</source>
<target state="new">BaseType.Delegates were set but no properties could be found. Do ensure that the WrapAttribute is used on the right properties.</target>
<note />
</trans-unit>
<trans-unit id="BI1114">
<source>Binding error: test unable to find property: {0} on {1}</source>
<target state="new">Binding error: test unable to find property: {0} on {1}</target>
<note />
</trans-unit>
<trans-unit id="BI1115">
<source>The parameter '{0}' in the delegate '{1}' does not have a [CCallback] or [BlockCallback] attribute. Defaulting to [CCallback].</source>
<target state="new">The parameter '{0}' in the delegate '{1}' does not have a [CCallback] or [BlockCallback] attribute. Defaulting to [CCallback].</target>
<note />
</trans-unit>
<trans-unit id="BI1116">
<source>The parameter '{0}' in the delegate '{1}' does not have a [CCallback] or [BlockCallback] attribute. Defaulting to [CCallback]. Declare a custom delegate instead of using System.Action / System.Func and add the attribute on the corresponding parameter.</source>
<target state="new">The parameter '{0}' in the delegate '{1}' does not have a [CCallback] or [BlockCallback] attribute. Defaulting to [CCallback]. Declare a custom delegate instead of using System.Action / System.Func and add the attribute on the corresponding parameter.</target>
<note />
</trans-unit>
<trans-unit id="BI1117">
<source>The member '{0}' is decorated with [Static] and its container class {1} is decorated with [Category] this leads to hard to use code. Please inline {0} into {2} class.</source>
<target state="new">The member '{0}' is decorated with [Static] and its container class {1} is decorated with [Category] this leads to hard to use code. Please inline {0} into {2} class.</target>
<note />
</trans-unit>
<trans-unit id="BI1118">
<source>[NullAllowed] should not be used on methods, like '{0}', but only on properties, parameters and return values.</source>
<target state="new">[NullAllowed] should not be used on methods, like '{0}', but only on properties, parameters and return values.</target>
<note />
</trans-unit>
<trans-unit id="BI1119">
<source>Internal error: found the same type ({0}) in multiple assemblies ({1} and {2}). Please file a bug report (path_to_url with a test case.</source>
<target state="new">Internal error: found the same type ({0}) in multiple assemblies ({1} and {2}). Please file a bug report (path_to_url with a test case.</target>
<note />
</trans-unit>
<trans-unit id="default">
<source>The error message for code {0} could not be found. Please report this missing message on GitHub at path_to_url
<target state="new">The error message for code {0} could not be found. Please report this missing message on GitHub at path_to_url
<note>
This is the default message when an error code can not be found.
</note>
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/xlf/Resources.zh-Hans.xlf | xml | 2016-04-20T18:24:26 | 2024-08-16T13:29:19 | xamarin-macios | xamarin/xamarin-macios | 2,436 | 9,107 |
```xml
/* eslint-disable import/first */
export type Global = typeof globalThis & {
pnpm__startedAt?: number
[REPORTER_INITIALIZED]?: ReporterType // eslint-disable-line @typescript-eslint/no-use-before-define
}
declare const global: Global
if (!global['pnpm__startedAt']) {
global['pnpm__startedAt'] = Date.now()
}
import loudRejection from 'loud-rejection'
import { packageManager, isExecutedByCorepack } from '@pnpm/cli-meta'
import { getConfig } from '@pnpm/cli-utils'
import { type Config, type WantedPackageManager } from '@pnpm/config'
import { executionTimeLogger, scopeLogger } from '@pnpm/core-loggers'
import { PnpmError } from '@pnpm/error'
import { filterPackagesFromDir } from '@pnpm/filter-workspace-packages'
import { globalWarn, logger } from '@pnpm/logger'
import { type ParsedCliArgs } from '@pnpm/parse-cli-args'
import { prepareExecutionEnv } from '@pnpm/plugin-commands-env'
import { finishWorkers } from '@pnpm/worker'
import chalk from 'chalk'
import { isCI } from 'ci-info'
import path from 'path'
import isEmpty from 'ramda/src/isEmpty'
import stripAnsi from 'strip-ansi'
import which from 'which'
import { checkForUpdates } from './checkForUpdates'
import { pnpmCmds, rcOptionsTypes } from './cmd'
import { formatUnknownOptionsError } from './formatError'
import { parseCliArgs } from './parseCliArgs'
import { initReporter, type ReporterType } from './reporter'
import { switchCliVersion } from './switchCliVersion'
export const REPORTER_INITIALIZED = Symbol('reporterInitialized')
loudRejection()
const DEPRECATED_OPTIONS = new Set([
'independent-leaves',
'lock',
'resolution-strategy',
])
// A workaround for the path_to_url issue.
delete process.env.PKG_EXECPATH
export async function main (inputArgv: string[]): Promise<void> {
let parsedCliArgs!: ParsedCliArgs
try {
parsedCliArgs = await parseCliArgs(inputArgv)
} catch (err: any) { // eslint-disable-line
// Reporting is not initialized at this point, so just printing the error
printError(err.message, err['hint'])
process.exitCode = 1
return
}
const {
argv,
params: cliParams,
options: cliOptions,
cmd,
fallbackCommandUsed,
unknownOptions,
workspaceDir,
} = parsedCliArgs
if (cmd !== null && !pnpmCmds[cmd]) {
printError(`Unknown command '${cmd}'`, 'For help, run: pnpm help')
process.exitCode = 1
return
}
if (unknownOptions.size > 0 && !fallbackCommandUsed) {
const unknownOptionsArray = Array.from(unknownOptions.keys())
if (unknownOptionsArray.every((option) => DEPRECATED_OPTIONS.has(option))) {
let deprecationMsg = `${chalk.bgYellow.black('\u2009WARN\u2009')}`
if (unknownOptionsArray.length === 1) {
deprecationMsg += ` ${chalk.yellow(`Deprecated option: '${unknownOptionsArray[0]}'`)}`
} else {
deprecationMsg += ` ${chalk.yellow(`Deprecated options: ${unknownOptionsArray.map(unknownOption => `'${unknownOption}'`).join(', ')}`)}`
}
console.log(deprecationMsg)
} else {
printError(formatUnknownOptionsError(unknownOptions), `For help, run: pnpm help${cmd ? ` ${cmd}` : ''}`)
process.exitCode = 1
return
}
}
let config: Config & {
argv: { remain: string[], cooked: string[], original: string[] }
fallbackCommandUsed: boolean
parseable?: boolean
json?: boolean
}
try {
// When we just want to print the location of the global bin directory,
// we don't need the write permission to it. Related issue: #2700
const globalDirShouldAllowWrite = cmd !== 'root'
const isDlxCommand = cmd === 'dlx'
config = await getConfig(cliOptions, {
excludeReporter: false,
globalDirShouldAllowWrite,
rcOptionsTypes,
workspaceDir,
checkUnknownSetting: false,
ignoreNonAuthSettingsFromLocal: isDlxCommand,
}) as typeof config
if (!isExecutedByCorepack() && cmd !== 'setup' && cmd !== 'self-update' && config.wantedPackageManager != null) {
if (config.managePackageManagerVersions) {
await switchCliVersion(config)
} else {
checkPackageManager(config.wantedPackageManager, config)
}
}
if (isDlxCommand) {
config.useStderr = true
}
config.argv = argv
config.fallbackCommandUsed = fallbackCommandUsed
// Set 'npm_command' env variable to current command name
if (cmd) {
config.extraEnv = {
...config.extraEnv,
// Follow the behavior of npm by setting it to 'run-script' when running scripts (e.g. pnpm run dev)
// and to the command name otherwise (e.g. pnpm test)
npm_command: cmd === 'run' ? 'run-script' : cmd,
}
}
} catch (err: any) { // eslint-disable-line
// Reporting is not initialized at this point, so just printing the error
const hint = err['hint'] ? err['hint'] : `For help, run: pnpm help${cmd ? ` ${cmd}` : ''}`
printError(err.message, hint)
process.exitCode = 1
return
}
if (cmd == null && cliOptions.version) {
console.log(packageManager.version)
return
}
let write: (text: string) => void = process.stdout.write.bind(process.stdout)
// chalk reads the FORCE_COLOR env variable
if (config.color === 'always') {
process.env['FORCE_COLOR'] = '1'
} else if (config.color === 'never') {
process.env['FORCE_COLOR'] = '0'
// In some cases, it is already late to set the FORCE_COLOR env variable.
// Some text might be already generated.
//
// A better solution might be to dynamically load all the code after the settings are read
// and the env variable set.
write = (text) => process.stdout.write(stripAnsi(text))
}
const reporterType: ReporterType = (() => {
if (config.loglevel === 'silent') return 'silent'
if (config.reporter) return config.reporter as ReporterType
if (isCI || !process.stdout.isTTY) return 'append-only'
return 'default'
})()
const printLogs = !config['parseable'] && !config['json']
if (printLogs) {
initReporter(reporterType, {
cmd,
config,
})
global[REPORTER_INITIALIZED] = reporterType
}
const selfUpdate = config.global && (cmd === 'add' || cmd === 'update') && cliParams.includes(packageManager.name)
if (selfUpdate) {
await pnpmCmds.server(config as any, ['stop']) // eslint-disable-line @typescript-eslint/no-explicit-any
try {
const currentPnpmDir = path.dirname(which.sync('pnpm'))
if (path.relative(currentPnpmDir, config.bin) !== '') {
console.log(`The location of the currently running pnpm differs from the location where pnpm will be installed
Current pnpm location: ${currentPnpmDir}
Target location: ${config.bin}
`)
}
} catch (err) {
// if pnpm not found, then ignore
}
}
if (
(cmd === 'install' || cmd === 'import' || cmd === 'dedupe' || cmd === 'patch-commit' || cmd === 'patch' || cmd === 'patch-remove') &&
typeof workspaceDir === 'string'
) {
cliOptions['recursive'] = true
config.recursive = true
if (!config.recursiveInstall && !config.filter && !config.filterProd) {
config.filter = ['{.}...']
}
}
if (cliOptions['recursive']) {
const wsDir = workspaceDir ?? process.cwd()
config.filter = config.filter ?? []
config.filterProd = config.filterProd ?? []
const filters = [
...config.filter.map((filter) => ({ filter, followProdDepsOnly: false })),
...config.filterProd.map((filter) => ({ filter, followProdDepsOnly: true })),
]
const relativeWSDirPath = () => path.relative(process.cwd(), wsDir) || '.'
if (config.workspaceRoot) {
filters.push({ filter: `{${relativeWSDirPath()}}`, followProdDepsOnly: Boolean(config.filterProd.length) })
} else if (workspaceDir && !config.includeWorkspaceRoot && (cmd === 'run' || cmd === 'exec' || cmd === 'add' || cmd === 'test')) {
filters.push({ filter: `!{${relativeWSDirPath()}}`, followProdDepsOnly: Boolean(config.filterProd.length) })
}
const filterResults = await filterPackagesFromDir(wsDir, filters, {
engineStrict: config.engineStrict,
nodeVersion: config.nodeVersion ?? config.useNodeVersion,
patterns: config.workspacePackagePatterns,
linkWorkspacePackages: !!config.linkWorkspacePackages,
prefix: process.cwd(),
workspaceDir: wsDir,
testPattern: config.testPattern,
changedFilesIgnorePattern: config.changedFilesIgnorePattern,
useGlobDirFiltering: !config.legacyDirFiltering,
sharedWorkspaceLockfile: config.sharedWorkspaceLockfile,
})
if (filterResults.allProjects.length === 0) {
if (printLogs) {
console.log(`No projects found in "${wsDir}"`)
}
process.exitCode = config.failIfNoMatch ? 1 : 0
return
}
config.allProjectsGraph = filterResults.allProjectsGraph
config.selectedProjectsGraph = filterResults.selectedProjectsGraph
if (isEmpty(config.selectedProjectsGraph)) {
if (printLogs) {
console.log(`No projects matched the filters in "${wsDir}"`)
}
process.exitCode = config.failIfNoMatch ? 1 : 0
return
}
if (filterResults.unmatchedFilters.length !== 0 && printLogs) {
console.log(`No projects matched the filters "${filterResults.unmatchedFilters.join(', ')}" in "${wsDir}"`)
}
config.allProjects = filterResults.allProjects
config.workspaceDir = wsDir
}
let { output, exitCode }: { output?: string | null, exitCode: number } = await (async () => {
// NOTE: we defer the next stage, otherwise reporter might not catch all the logs
await new Promise<void>((resolve) => setTimeout(() => {
resolve()
}, 0))
if (
config.updateNotifier !== false &&
!isCI &&
!selfUpdate &&
!config.offline &&
!config.preferOffline &&
!config.fallbackCommandUsed &&
(cmd === 'install' || cmd === 'add')
) {
checkForUpdates(config).catch(() => { /* Ignore */ })
}
if (config.force === true && !config.fallbackCommandUsed) {
logger.warn({
message: 'using --force I sure hope you know what you are doing',
prefix: config.dir,
})
}
scopeLogger.debug({
...(
!cliOptions['recursive']
? { selected: 1 }
: {
selected: Object.keys(config.selectedProjectsGraph!).length,
total: config.allProjects!.length,
}
),
...(workspaceDir ? { workspacePrefix: workspaceDir } : {}),
})
if (config.useNodeVersion != null) {
if ('webcontainer' in process.versions) {
globalWarn('Automatic installation of different Node.js versions is not supported in WebContainer')
} else {
config.extraBinPaths = (
await prepareExecutionEnv(config, {
extraBinPaths: config.extraBinPaths,
executionEnv: {
nodeVersion: config.useNodeVersion,
},
})
).extraBinPaths
config.nodeVersion = config.useNodeVersion
}
}
let result = pnpmCmds[cmd ?? 'help'](
// TypeScript doesn't currently infer that the type of config
// is `Omit<typeof config, 'reporter'>` after the `delete config.reporter` statement
config as Omit<typeof config, 'reporter'>,
cliParams
)
if (result instanceof Promise) {
result = await result
}
executionTimeLogger.debug({
startedAt: global['pnpm__startedAt'],
endedAt: Date.now(),
})
if (!result) {
return { output: null, exitCode: 0 }
}
if (typeof result === 'string') {
return { output: result, exitCode: 0 }
}
return result
})()
// When use-node-version is set and "pnpm run" is executed,
// this will be the only place where the tarball worker pool is finished.
await finishWorkers()
if (output) {
if (!output.endsWith('\n')) {
output = `${output}\n`
}
write(output)
}
if (!cmd) {
exitCode = 1
}
if (exitCode) {
process.exitCode = exitCode
}
}
function printError (message: string, hint?: string): void {
const ERROR = chalk.bgRed.black('\u2009ERROR\u2009')
console.log(`${message.startsWith(ERROR) ? '' : ERROR + ' '}${chalk.red(message)}`)
if (hint) {
console.log(hint)
}
}
function checkPackageManager (pm: WantedPackageManager, config: Config): void {
if (!pm.name) return
if (pm.name !== 'pnpm') {
const msg = `This project is configured to use ${pm.name}`
if (config.packageManagerStrict) {
throw new PnpmError('OTHER_PM_EXPECTED', msg)
}
globalWarn(msg)
} else {
const currentPnpmVersion = packageManager.name === 'pnpm'
? packageManager.version
: undefined
if (currentPnpmVersion && config.packageManagerStrictVersion && pm.version && pm.version !== currentPnpmVersion) {
const msg = `This project is configured to use v${pm.version} of pnpm. Your current pnpm is v${currentPnpmVersion}`
if (config.packageManagerStrict) {
throw new PnpmError('BAD_PM_VERSION', msg, {
hint: 'If you want to bypass this version check, you can set the "package-manager-strict" configuration to "false" or set the "COREPACK_ENABLE_STRICT" environment variable to "0"',
})
} else {
globalWarn(msg)
}
}
}
}
``` | /content/code_sandbox/pnpm/src/main.ts | xml | 2016-01-28T07:40:43 | 2024-08-16T12:38:47 | pnpm | pnpm/pnpm | 28,869 | 3,299 |
```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.
-->
<FrameLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/fade_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/cat_transition_fade_button_hide_fab" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fade_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
app:srcCompat="@drawable/ic_add_24px" />
</FrameLayout>
``` | /content/code_sandbox/catalog/java/io/material/catalog/transition/res/layout/cat_transition_fade_fragment.xml | xml | 2016-12-05T16:11:29 | 2024-08-16T17:51:42 | material-components-android | material-components/material-components-android | 16,176 | 239 |
```xml
import React from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';
import { FiltersForm } from './Form';
import { refreshFilteredLogs } from '../../../actions/queryLogs';
import { addSuccessToast } from '../../../actions/toasts';
interface FiltersProps {
filter: object;
processingGetLogs: boolean;
setIsLoading: (...args: unknown[]) => unknown;
}
const Filters = ({ filter, setIsLoading }: FiltersProps) => {
const { t } = useTranslation();
const dispatch = useDispatch();
const refreshLogs = async () => {
setIsLoading(true);
await dispatch(refreshFilteredLogs());
dispatch(addSuccessToast('query_log_updated'));
setIsLoading(false);
};
return (
<div className="page-header page-header--logs">
<h1 className="page-title page-title--large">
{t('query_log')}
<button
type="button"
className="btn btn-icon--green logs__refresh"
title={t('refresh_btn')}
onClick={refreshLogs}>
<svg className="icons icon--24">
<use xlinkHref="#update" />
</svg>
</button>
</h1>
<FiltersForm responseStatusClass="d-sm-block" setIsLoading={setIsLoading} initialValues={filter} />
</div>
);
};
export default Filters;
``` | /content/code_sandbox/client/src/components/Logs/Filters/index.tsx | xml | 2016-07-06T10:31:47 | 2024-08-16T18:17:06 | AdGuardHome | AdguardTeam/AdGuardHome | 24,082 | 296 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<cobra document="path_to_url">
<name value="webshell22"/>
<language value="php"/>
<match mode="regex-only-match"><![CDATA[\s*(assert|eval|system|exec|shell_exec|passthru|popen|proc_open|pcntl_exec|include)\s*\(\s*(file_get_contents\s*\(\s*)?['\"]php://input]]></match>
<level value="7"/>
<test>
<case assert="true"><![CDATA[
ini_set('allow_url_include, 1');
include('php://input');
]]></case>
</test>
<solution>
##
webshell
##
</solution>
<status value="off"/>
<author name="Feei" email="feei@feei.cn"/>
</cobra>
``` | /content/code_sandbox/rules/CVI-360022.xml | xml | 2016-04-15T08:41:15 | 2024-08-16T10:33:17 | Cobra | FeeiCN/Cobra | 3,133 | 195 |
```xml
import { extend } from '../../core/util/common';
import Common, { type CommonProjectionType } from './Projection';
import Coordinate from '../Coordinate';
import { BaiduSphere, BaiduSphereType } from '../measurer';
const ProjectionMethods = {
EARTHRADIUS: 6370996.81,
MCBAND: [12890594.86, 8362377.87, 5591021, 3481989.83, 1678043.12, 0],
LLBAND: [75, 60, 45, 30, 15, 0],
MC2LL: [
[1.410526172116255e-8, 0.00000898305509648872, -1.9939833816331, 200.9824383106796, -187.2403703815547, 91.6087516669843, -23.38765649603339, 2.57121317296198, -0.03801003308653, 17337981.2],
[-7.435856389565537e-9, 0.000008983055097726239, -0.78625201886289, 96.32687599759846, -1.85204757529826, -59.36935905485877, 47.40033549296737, -16.50741931063887, 2.28786674699375, 10260144.86],
[-3.030883460898826e-8, 0.00000898305509983578, 0.30071316287616, 59.74293618442277, 7.357984074871, -25.38371002664745, 13.45380521110908, -3.29883767235584, 0.32710905363475, 6856817.37],
[-1.981981304930552e-8, 0.000008983055099779535, 0.03278182852591, 40.31678527705744, 0.65659298677277, -4.44255534477492, 0.85341911805263, 0.12923347998204, -0.04625736007561, 4482777.06],
[3.09191371068437e-9, 0.000008983055096812155, 0.00006995724062, 23.10934304144901, -0.00023663490511, -0.6321817810242, -0.00663494467273, 0.03430082397953, -0.00466043876332, 2555164.4],
[2.890871144776878e-9, 0.000008983055095805407, -3.068298e-8, 7.47137025468032, -0.00000353937994, -0.02145144861037, -0.00001234426596, 0.00010322952773, -0.00000323890364, 826088.5]
],
LL2MC: [
[-0.0015702102444, 111320.7020616939, 1704480524535203, -10338987376042340, 26112667856603880, -35149669176653700, 26595700718403920, -10725012454188240, 1800819912950474, 82.5],
[0.0008277824516172526, 111320.7020463578, 647795574.6671607, -4082003173.641316, 10774905663.51142, -15171875531.51559, 12053065338.62167, -5124939663.577472, 913311935.9512032, 67.5],
[0.00337398766765, 111320.7020202162, 4481351.045890365, -23393751.19931662, 79682215.47186455, -115964993.2797253, 97236711.15602145, -43661946.33752821, 8477230.501135234, 52.5],
[0.00220636496208, 111320.7020209128, 51751.86112841131, 3796837.749470245, 992013.7397791013, -1221952.21711287, 1340652.697009075, -620943.6990984312, 144416.9293806241, 37.5],
[-0.0003441963504368392, 111320.7020576856, 278.2353980772752, 2485758.690035394, 6070.750963243378, 54821.18345352118, 9540.606633304236, -2710.55326746645, 1405.483844121726, 22.5],
[-0.0003218135878613132, 111320.7020701615, 0.00369383431289, 823725.6402795718, 0.46104986909093, 2351.343141331292, 1.58060784298199, 8.77738589078284, 0.37238884252424, 7.45]
],
convertMC2LL: function (cB: Coordinate, out?: Coordinate): Coordinate {
let cE;
for (let cD = 0, len = this.MCBAND.length; cD < len; cD++) {
if (Math.abs(cB.y) >= this.MCBAND[cD]) {
cE = this.MC2LL[cD];
break;
}
}
const T = this.convertor(cB, cE, out);
return T;
},
convertLL2MC: function (T: Coordinate, out?: Coordinate): Coordinate {
let cD, cC, len;
T.x = this.getLoop(T.x, -180, 180);
T.y = this.getRange(T.y, -74, 74);
const cB = new Coordinate(T.x, T.y);
for (cC = 0, len = this.LLBAND.length; cC < len; cC++) {
if (cB.y >= this.LLBAND[cC]) {
cD = this.LL2MC[cC];
break;
}
}
if (!cD) {
for (cC = this.LLBAND.length - 1; cC >= 0; cC--) {
if (cB.y <= -this.LLBAND[cC]) {
cD = this.LL2MC[cC];
break;
}
}
}
const cE = this.convertor(T, cD, out);
return cE;
},
convertor: function (cC: Coordinate, cD: number, out?: Coordinate): Coordinate {
if (!cC || !cD) {
return null;
}
let T = cD[0] + cD[1] * Math.abs(cC.x);
const cB = Math.abs(cC.y) / cD[9];
let cE = cD[2] + cD[3] * cB + cD[4] * cB * cB +
cD[5] * cB * cB * cB + cD[6] * cB * cB * cB * cB +
cD[7] * cB * cB * cB * cB * cB +
cD[8] * cB * cB * cB * cB * cB * cB;
T *= (cC.x < 0 ? -1 : 1);
cE *= (cC.y < 0 ? -1 : 1);
if (out) {
out.x = T;
out.y = cE;
return out;
}
return new Coordinate(T, cE);
},
toRadians: function (T: number): number {
return Math.PI * T / 180;
},
toDegrees: function (T: number): number {
return (180 * T) / Math.PI;
},
getRange: function (cC: number, cB: number, T: number): number {
if (cB != null) {
cC = Math.max(cC, cB);
}
if (T != null) {
cC = Math.min(cC, T);
}
return cC;
},
getLoop: function (cC: number, cB: number, T: number): number {
if (cC === Infinity) {
return T;
} else if (cC === -Infinity) {
return cB;
}
while (cC > T) {
cC -= T - cB;
}
while (cC < cB) {
cC += T - cB;
}
return cC;
}
};
const BAIDUProjection = {
/**
* "BAIDU", Code of the projection
* @constant
*/
code: 'BAIDU',
project: function (p: Coordinate, out?: Coordinate): Coordinate {
return this.convertLL2MC(p, out);
},
unproject: function (p: Coordinate, out?: Coordinate): Coordinate {
return this.convertMC2LL(p, out);
}
};
export type BAIDUProjectionType = CommonProjectionType & typeof BAIDUProjection & BaiduSphereType & typeof ProjectionMethods;
/**
* [Baidu Map]{@link path_to_url}
*
* @english
* Projection used by [Baidu Map]{@link path_to_url}
*
* @category geo
* @protected
* @group projection
* @name BAIDU
* {@inheritDoc projection.Common}
* {@inheritDoc BaiduSphere}
*/
export default extend<BAIDUProjectionType, CommonProjectionType, typeof BAIDUProjection, BaiduSphereType, typeof ProjectionMethods>({} as BAIDUProjectionType, Common, BAIDUProjection, BaiduSphere, ProjectionMethods);
``` | /content/code_sandbox/src/geo/projection/Projection.Baidu.ts | xml | 2016-02-03T02:41:32 | 2024-08-15T16:51:49 | maptalks.js | maptalks/maptalks.js | 4,272 | 2,289 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="path_to_url" ToolsVersion="4.0">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{7FD1783E-2D31-4D05-BF23-6EBE1B42B608}</ProjectGuid>
<ProjectTypeGuids>{82b43b9b-a64c-4715-b499-d71e9ca2bd60};{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LLVM.ClangFormat</RootNamespace>
<AssemblyName>ClangFormat</AssemblyName>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>Key.snk</AssemblyOriginatorKeyFile>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<MinimumVisualStudioVersion>15.0</MinimumVisualStudioVersion>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<OldToolsVersion>4.0</OldToolsVersion>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<RunCodeAnalysis>true</RunCodeAnalysis>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="envdte, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="envdte80, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.VisualStudio.CoreUtility, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\VSSDK.CoreUtility.10.0.4\lib\net40\Microsoft.VisualStudio.CoreUtility.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Editor, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\VSSDK.Editor.10.0.4\lib\net40\Microsoft.VisualStudio.Editor.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.OLE.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<HintPath>..\packages\VSSDK.OLE.Interop.7.0.4\lib\net20\Microsoft.VisualStudio.OLE.Interop.dll</HintPath>
<Private>True</Private>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\VSSDK.Shell.10.10.0.3\lib\net40\Microsoft.VisualStudio.Shell.10.0.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Immutable.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\VSSDK.Shell.Immutable.10.10.0.3\lib\net40\Microsoft.VisualStudio.Shell.Immutable.10.0.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<HintPath>..\packages\VSSDK.Shell.Interop.7.0.4\lib\net20\Microsoft.VisualStudio.Shell.Interop.dll</HintPath>
<Private>True</Private>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Interop.8.0, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<HintPath>..\packages\VSSDK.Shell.Interop.8.8.0.3\lib\net20\Microsoft.VisualStudio.Shell.Interop.8.0.dll</HintPath>
<Private>True</Private>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Shell.Interop.10.0" />
<Reference Include="Microsoft.VisualStudio.Shell.Interop.9.0, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<HintPath>..\packages\VSSDK.Shell.Interop.9.9.0.3\lib\net20\Microsoft.VisualStudio.Shell.Interop.9.0.dll</HintPath>
<Private>True</Private>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Text.Data, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.Data.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Text.Logic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.Logic.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Text.UI, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.UI.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.Text.UI.Wpf, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\VSSDK.Text.10.0.4\lib\net40\Microsoft.VisualStudio.Text.UI.Wpf.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TextManager.Interop, Version=7.1.40304.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.VisualStudio.TextManager.Interop.8.0, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<HintPath>..\packages\VSSDK.TextManager.Interop.8.8.0.4\lib\net20\Microsoft.VisualStudio.TextManager.Interop.8.0.dll</HintPath>
<Private>True</Private>
<Private>False</Private>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="stdole, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<HintPath>..\packages\VSSDK.DTE.7.0.3\lib\net20\stdole.dll</HintPath>
<EmbedInteropTypes>False</EmbedInteropTypes>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Design" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<COMReference Include="Microsoft.VisualStudio.CommandBars">
<Guid>{1CBA492E-7263-47BB-87FE-639000619B15}</Guid>
<VersionMajor>8</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>False</EmbedInteropTypes>
</COMReference>
<COMReference Include="stdole">
<Guid>{00020430-0000-0000-C000-000000000046}</Guid>
<VersionMajor>2</VersionMajor>
<VersionMinor>0</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
<EmbedInteropTypes>False</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<ItemGroup>
<Compile Include="Guids.cs" />
<Compile Include="Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="GlobalSuppressions.cs" />
<Compile Include="ClangFormatPackage.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="PkgCmdID.cs" />
<Compile Include="RunningDocTableEventsDispatcher.cs" />
<Compile Include="Vsix.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<EmbeddedResource Include="VSPackage.resx">
<MergeWithCTO>true</MergeWithCTO>
<ManifestResourceName>VSPackage</ManifestResourceName>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="Key.snk" />
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
<None Include="source.extension.vsixmanifest">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<VSCTCompile Include="ClangFormat.vsct">
<ResourceName>Menus.ctmenu</ResourceName>
</VSCTCompile>
</ItemGroup>
<ItemGroup>
<None Include="Resources\Images_32bit.bmp" />
</ItemGroup>
<ItemGroup>
<Content Include="clang-format.exe">
<IncludeInVSIX>true</IncludeInVSIX>
</Content>
<Content Include="license.txt">
<IncludeInVSIX>true</IncludeInVSIX>
</Content>
<Content Include="Resources\Package.ico" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.0">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.4.5">
<Visible>False</Visible>
<ProductName>Windows Installer 4.5</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<PropertyGroup>
<UseCodebase>true</UseCodebase>
</PropertyGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\VSSDK\Microsoft.VsSDK.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\VSSDK\Microsoft.VsSDK.targets" Condition="false" />
<PropertyGroup>
<PreBuildEvent>if not exist $(ProjectDir)Key.snk ("$(FrameworkSDKDir)Bin\NETFX 4.6 Tools\sn.exe" -k $(ProjectDir)Key.snk)</PreBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
``` | /content/code_sandbox/gnu/llvm/clang/tools/clang-format-vs/ClangFormat/ClangFormat.csproj | xml | 2016-08-30T18:18:25 | 2024-08-16T17:21:09 | src | openbsd/src | 3,139 | 3,649 |
```xml
import type { Maybe } from '@proton/pass/types';
export const safeCall =
<T extends (...args: any[]) => any>(fn?: T) =>
(...args: Parameters<T>): Maybe<ReturnType<T>> => {
try {
return fn?.(...args);
} catch (_) {}
};
``` | /content/code_sandbox/packages/pass/utils/fp/safe-call.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 66 |
```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 { codec } from '@liskhq/lisk-codec';
import { utils } from '@liskhq/lisk-cryptography';
import { validator } from '@liskhq/lisk-validator';
import { CommandExecuteContext, CommandVerifyContext } from '../../state_machine';
import { BaseInteroperabilityCommand } from './base_interoperability_command';
import { BaseInteroperabilityInternalMethod } from './base_interoperability_internal_methods';
import { BaseInteroperabilityMethod } from './base_interoperability_method';
import { CCMStatusCode, EMPTY_BYTES, EVENT_TOPIC_CCM_EXECUTION, EmptyCCM } from './constants';
import { CCMProcessedCode, CcmProcessedEvent, CCMProcessedResult } from './events/ccm_processed';
import { CcmSendSuccessEvent } from './events/ccm_send_success';
import { ccmSchema, crossChainUpdateTransactionParams } from './schemas';
import {
CCMsg,
CCUpdateParams,
CrossChainMessageContext,
CrossChainUpdateTransactionParams,
TokenMethod,
} from './types';
import { ChainAccountStore, ChainStatus } from './stores/chain_account';
import {
emptyActiveValidatorsUpdate,
getEncodedCCMAndID,
getIDFromCCMBytes,
getMainchainID,
isInboxUpdateEmpty,
validateFormat,
} from './utils';
import { ChainValidatorsStore } from './stores/chain_validators';
import { OwnChainAccountStore } from './stores/own_chain_account';
export abstract class BaseCrossChainUpdateCommand<
T extends BaseInteroperabilityInternalMethod,
> extends BaseInteroperabilityCommand<T> {
public schema = crossChainUpdateTransactionParams;
protected _tokenMethod!: TokenMethod;
protected _interopsMethod!: BaseInteroperabilityMethod<T>;
public init(interopsMethod: BaseInteroperabilityMethod<T>, tokenMethod: TokenMethod) {
this._tokenMethod = tokenMethod;
this._interopsMethod = interopsMethod;
}
// path_to_url#verifycommon
protected async verifyCommon(
context: CommandVerifyContext<CrossChainUpdateTransactionParams>,
isMainchain: boolean,
): Promise<void> {
const { params } = context;
validator.validate(crossChainUpdateTransactionParams, params);
const ownChainAccount = await this.stores.get(OwnChainAccountStore).get(context, EMPTY_BYTES);
if (params.sendingChainID.equals(ownChainAccount.chainID)) {
throw new Error('The sending chain cannot be the same as the receiving chain.');
}
// An empty object has all properties set to their default values
if (params.certificate.length === 0 && isInboxUpdateEmpty(params.inboxUpdate)) {
throw new Error(
'A cross-chain update must contain a non-empty certificate and/or a non-empty inbox update.',
);
}
// The sending chain account must exist
const sendingChainAccount = await this.stores
.get(ChainAccountStore)
.getOrUndefined(context, params.sendingChainID);
if (!sendingChainAccount) {
throw new Error('The sending chain is not registered.');
}
let live;
if (isMainchain) {
live = await this.internalMethod.isLive(
context,
params.sendingChainID,
context.header.timestamp,
);
} else {
live = await this.internalMethod.isLive(context, params.sendingChainID);
}
if (!live) {
throw new Error('The sending chain is not live.');
}
if (sendingChainAccount.status === ChainStatus.REGISTERED && params.certificate.length === 0) {
throw new Error(
`Cross-chain updates from chains with status ${ChainStatus.REGISTERED} must contain a non-empty certificate.`,
);
}
if (params.certificate.length > 0) {
await this.internalMethod.verifyCertificate(context, params, context.header.timestamp);
}
const sendingChainValidators = await this.stores
.get(ChainValidatorsStore)
.get(context, params.sendingChainID);
if (
!emptyActiveValidatorsUpdate(params.activeValidatorsUpdate) ||
params.certificateThreshold !== sendingChainValidators.certificateThreshold
) {
await this.internalMethod.verifyValidatorsUpdate(context, params);
}
if (!isInboxUpdateEmpty(params.inboxUpdate)) {
this.internalMethod.verifyOutboxRootWitness(context, params);
}
}
// path_to_url#beforecrosschainmessagesexecution
protected async beforeCrossChainMessagesExecution(
context: CommandExecuteContext<CrossChainUpdateTransactionParams>,
isMainchain: boolean,
): Promise<[CCMsg[], boolean]> {
const { params } = context;
const { inboxUpdate } = params;
const ccms: CCMsg[] = [];
let ccm: CCMsg;
// Process cross-chain messages in inbox update.
// First process basic checks for all CCMs.
for (const ccmBytes of inboxUpdate.crossChainMessages) {
const ccmID = getIDFromCCMBytes(ccmBytes);
const ccmContext = {
...context,
eventQueue: context.eventQueue.getChildQueue(
Buffer.concat([EVENT_TOPIC_CCM_EXECUTION, ccmID]),
),
};
try {
// Verify general format. Past this point, we can access ccm root properties.
ccm = codec.decode<CCMsg>(ccmSchema, ccmBytes);
} catch (error) {
await this.internalMethod.terminateChainInternal(ccmContext, params.sendingChainID);
this.events
.get(CcmProcessedEvent)
.log(ccmContext, params.sendingChainID, ccmContext.chainID, {
ccm: EmptyCCM,
result: CCMProcessedResult.DISCARDED,
code: CCMProcessedCode.INVALID_CCM_DECODING_EXCEPTION,
});
// In this case, we do not even update the chain account with the new certificate.
return [[], false];
}
try {
validateFormat(ccm);
} catch (error) {
await this.internalMethod.terminateChainInternal(ccmContext, params.sendingChainID);
ccm = { ...ccm, params: EMPTY_BYTES };
this.events
.get(CcmProcessedEvent)
.log(ccmContext, params.sendingChainID, ccm.receivingChainID, {
ccm,
result: CCMProcessedResult.DISCARDED,
code: CCMProcessedCode.INVALID_CCM_VALIDATION_EXCEPTION,
});
// In this case, we do not even update the chain account with the new certificate.
return [[], false];
}
try {
this.verifyRoutingRules(ccm, params, ccmContext.chainID, isMainchain);
ccms.push(ccm);
} catch (error) {
await this.internalMethod.terminateChainInternal(ccmContext, params.sendingChainID);
this.events
.get(CcmProcessedEvent)
.log(ccmContext, params.sendingChainID, ccm.receivingChainID, {
ccm,
result: CCMProcessedResult.DISCARDED,
code: CCMProcessedCode.INVALID_CCM_ROUTING_EXCEPTION,
});
// In this case, we do not even update the chain account with the new certificate.
return [[], false];
}
}
return [ccms, true];
}
// path_to_url#verifyroutingrules
protected verifyRoutingRules(
ccm: CCMsg,
ccuParams: CrossChainUpdateTransactionParams,
ownChainID: Buffer,
isMainchain: boolean,
) {
// The CCM must come from the sending chain.
if (isMainchain) {
if (!ccm.sendingChainID.equals(ccuParams.sendingChainID)) {
throw new Error('CCM is not from the sending chain.');
}
if (ccm.status === CCMStatusCode.CHANNEL_UNAVAILABLE) {
throw new Error('CCM status channel unavailable can only be set on the mainchain.');
}
} else if (!ownChainID.equals(ccm.receivingChainID)) {
// The CCM must be directed to the sidechain.
throw new Error('CCM is not directed to the sidechain.');
}
// Sending and receiving chains must differ.
if (ccm.receivingChainID.equals(ccm.sendingChainID)) {
throw new Error('Sending and receiving chains must differ.');
}
}
// path_to_url#aftercrosschainmessagesexecution
protected async afterCrossChainMessagesExecution(
context: CommandExecuteContext<CrossChainUpdateTransactionParams>,
) {
const { params } = context;
// Update sidechain validators.
const sendingChainValidators = await this.stores
.get(ChainValidatorsStore)
.get(context, params.sendingChainID);
if (
!emptyActiveValidatorsUpdate(params.activeValidatorsUpdate) ||
params.certificateThreshold !== sendingChainValidators.certificateThreshold
) {
await this.internalMethod.updateValidators(context, params);
}
if (params.certificate.length > 0) {
await this.internalMethod.updateCertificate(context, params);
}
if (!isInboxUpdateEmpty(params.inboxUpdate) && params.certificate.length > 0) {
await this.internalMethod.updatePartnerChainOutboxRoot(context, params);
}
}
private async _beforeCrossChainCommandExecute(
context: CrossChainMessageContext,
baseEventSnapshotID: number,
baseStateSnapshotID: number,
): Promise<boolean> {
const { ccm, logger } = context;
const { ccmID } = getEncodedCCMAndID(ccm);
try {
// Call the beforeCrossChainCommandExecute functions from other modules.
// For example, the Token module assigns the message fee to the CCU sender.
for (const [module, method] of this.interoperableCCMethods.entries()) {
if (method.beforeCrossChainCommandExecute) {
logger.debug(
{
moduleName: module,
commandName: ccm.crossChainCommand,
ccmID: ccmID.toString('hex'),
},
'Execute beforeCrossChainCommandExecute',
);
await method.beforeCrossChainCommandExecute(context);
}
}
} catch (error) {
// revert state to baseSnapshot
context.eventQueue.restoreSnapshot(baseEventSnapshotID);
context.stateStore.restoreSnapshot(baseStateSnapshotID);
logger.info(
{ err: error as Error, moduleName: ccm.module, commandName: ccm.crossChainCommand },
'Fail to execute beforeCrossChainCommandExecute.',
);
await this.internalMethod.terminateChainInternal(context, ccm.sendingChainID);
this.events.get(CcmProcessedEvent).log(context, ccm.sendingChainID, ccm.receivingChainID, {
ccm,
result: CCMProcessedResult.DISCARDED,
code: CCMProcessedCode.INVALID_CCM_BEFORE_CCC_EXECUTION_EXCEPTION,
});
return false;
}
return true;
}
private async _afterCrossChainCommandExecute(
context: CrossChainMessageContext,
baseEventSnapshotID: number,
baseStateSnapshotID: number,
): Promise<boolean> {
const { ccm, logger } = context;
const { ccmID } = getEncodedCCMAndID(ccm);
try {
// Call the beforeCrossChainCommandExecute functions from other modules.
// For example, the Token module assigns the message fee to the CCU sender.
for (const [module, method] of this.interoperableCCMethods.entries()) {
if (method.afterCrossChainCommandExecute) {
logger.debug(
{
moduleName: module,
commandName: ccm.crossChainCommand,
ccmID: ccmID.toString('hex'),
},
'Execute afterCrossChainCommandExecute',
);
await method.afterCrossChainCommandExecute(context);
}
}
} catch (error) {
// revert state to baseSnapshot
context.eventQueue.restoreSnapshot(baseEventSnapshotID);
context.stateStore.restoreSnapshot(baseStateSnapshotID);
logger.info(
{ err: error as Error, moduleName: ccm.module, commandName: ccm.crossChainCommand },
'Fail to execute afterCrossChainCommandExecute.',
);
await this.internalMethod.terminateChainInternal(context, ccm.sendingChainID);
this.events.get(CcmProcessedEvent).log(context, ccm.sendingChainID, ccm.receivingChainID, {
ccm,
result: CCMProcessedResult.DISCARDED,
code: CCMProcessedCode.INVALID_CCM_AFTER_CCC_EXECUTION_EXCEPTION,
});
return false;
}
return true;
}
// path_to_url#apply
protected async apply(context: CrossChainMessageContext): Promise<void> {
const { ccm, logger } = context;
const { ccmID, encodedCCM } = getEncodedCCMAndID(ccm);
const valid = await this.verifyCCM(context, ccmID);
if (!valid) {
return;
}
// Create a state snapshot.
const baseEventSnapshotID = context.eventQueue.createSnapshot();
const baseStateSnapshotID = context.stateStore.createSnapshot();
let statusCode;
let processedCode;
let crossChainCommand;
// ccm.module supported ?
const crossChainCommands = this.ccCommands.get(ccm.module);
if (!crossChainCommands) {
statusCode = CCMStatusCode.MODULE_NOT_SUPPORTED;
processedCode = CCMProcessedCode.MODULE_NOT_SUPPORTED;
} else {
// ccm.crossChainCommand supported ?
crossChainCommand = crossChainCommands.find(com => com.name === ccm.crossChainCommand);
if (!crossChainCommand) {
statusCode = CCMStatusCode.CROSS_CHAIN_COMMAND_NOT_SUPPORTED;
processedCode = CCMProcessedCode.CROSS_CHAIN_COMMAND_NOT_SUPPORTED;
}
}
if (!crossChainCommands || !crossChainCommand) {
if (
!(await this._beforeCrossChainCommandExecute(
context,
baseEventSnapshotID,
baseStateSnapshotID,
))
) {
return;
}
if (
!(await this._afterCrossChainCommandExecute(
context,
baseEventSnapshotID,
baseStateSnapshotID,
))
) {
return;
}
await this.bounce(
context,
encodedCCM.length,
statusCode as CCMStatusCode,
processedCode as CCMProcessedCode,
);
return;
}
// Although this part is not mentioned in LIP, but it covers #8558
let decodedParams;
try {
decodedParams = codec.decode(crossChainCommand.schema, context.ccm.params);
validator.validate(crossChainCommand.schema, decodedParams);
} catch (error) {
logger.info(
{ err: error as Error, moduleName: ccm.module, commandName: ccm.crossChainCommand },
'Invalid CCM params.',
);
await this.internalMethod.terminateChainInternal(context, ccm.sendingChainID);
this.events.get(CcmProcessedEvent).log(context, ccm.sendingChainID, ccm.receivingChainID, {
ccm,
result: CCMProcessedResult.DISCARDED,
code: CCMProcessedCode.INVALID_CCM_VERIFY_CCM_EXCEPTION,
});
return;
}
if (crossChainCommand.verify) {
try {
await crossChainCommand.verify(context);
} catch (error) {
logger.info(
{ err: error as Error, moduleName: ccm.module, commandName: ccm.crossChainCommand },
'Fail to verify cross chain command.',
);
await this.internalMethod.terminateChainInternal(context, ccm.sendingChainID);
this.events.get(CcmProcessedEvent).log(context, ccm.sendingChainID, ccm.receivingChainID, {
ccm,
result: CCMProcessedResult.DISCARDED,
code: CCMProcessedCode.INVALID_CCM_VERIFY_CCM_EXCEPTION,
});
return;
}
}
if (
!(await this._beforeCrossChainCommandExecute(
context,
baseEventSnapshotID,
baseStateSnapshotID,
))
) {
return;
}
// Continue to ccm execution only if there was no error until now.
// Create a state snapshot.
const execEventSnapshotID = context.eventQueue.createSnapshot();
const execStateSnapshotID = context.stateStore.createSnapshot();
try {
/**
* This could happen during the execution of a mainchain CCU containing a CCM
* from a sidechain for which a direct channel has been registered.
* Then, ccu.params.sendingChainID == getMainchainID().
* This is not necessarily a violation of the protocol, since the message
* could have been sent before the direct channel was opened.
*/
const sendingChainExists = await this.stores
.get(ChainAccountStore)
.has(context, ccm.sendingChainID);
const ccuParams = codec.decode<CCUpdateParams>(
crossChainUpdateTransactionParams,
context.transaction.params,
);
if (sendingChainExists && !ccuParams.sendingChainID.equals(ccm.sendingChainID)) {
throw new Error('Cannot receive forwarded messages for a direct channel.');
}
// Execute the cross-chain command.
await crossChainCommand.execute({ ...context, params: decodedParams });
this.events.get(CcmProcessedEvent).log(context, ccm.sendingChainID, ccm.receivingChainID, {
ccm,
result: CCMProcessedResult.APPLIED,
code: CCMProcessedCode.SUCCESS,
});
} catch (error) {
// revert state to executionSnapshot
context.eventQueue.restoreSnapshot(execEventSnapshotID);
context.stateStore.restoreSnapshot(execStateSnapshotID);
// in case of error, run `afterCrossChainCommandExecute` & `bounce` followed by `return`
if (
!(await this._afterCrossChainCommandExecute(
context,
baseEventSnapshotID,
baseStateSnapshotID,
))
) {
return;
}
await this.bounce(
context,
encodedCCM.length,
CCMStatusCode.FAILED_CCM,
CCMProcessedCode.FAILED_CCM,
);
return;
}
// run `afterCrossChainCommandExecute` after a successful command execution (i.e., when there is no error in above `try` block)
await this._afterCrossChainCommandExecute(context, baseEventSnapshotID, baseStateSnapshotID);
}
// path_to_url#bounce
protected async bounce(
context: CrossChainMessageContext,
ccmSize: number,
ccmStatusCode: CCMStatusCode,
ccmProcessedCode: CCMProcessedCode,
): Promise<void> {
const { ccm } = context;
const minReturnFeePerByte = await this._interopsMethod.getMinReturnFeePerByte(
context,
ccm.sendingChainID,
);
const minFee = minReturnFeePerByte * BigInt(ccmSize);
if (ccm.status !== CCMStatusCode.OK || ccm.fee < minFee) {
this.events.get(CcmProcessedEvent).log(context, ccm.sendingChainID, ccm.receivingChainID, {
code: ccmProcessedCode,
result: CCMProcessedResult.DISCARDED,
ccm,
});
return;
}
this.events.get(CcmProcessedEvent).log(context, ccm.sendingChainID, ccm.receivingChainID, {
code: ccmProcessedCode,
result: CCMProcessedResult.BOUNCED,
ccm,
});
const bouncedCCM = {
...ccm,
status: ccmStatusCode,
sendingChainID: ccm.receivingChainID,
receivingChainID: ccm.sendingChainID,
// The fee of the bounced ccm is set to 0 because it was assigned to the relayer.
fee: BigInt(0),
};
let partnerChainID: Buffer;
const mainchainID = getMainchainID(bouncedCCM.receivingChainID);
const ownChainAccount = await this.stores.get(OwnChainAccountStore).get(context, EMPTY_BYTES);
// Processing on the mainchain
if (ownChainAccount.chainID.equals(mainchainID)) {
partnerChainID = bouncedCCM.receivingChainID;
// Processing on a sidechain
} else {
// Check for direct channel
const receivingChainExists = await this.stores
.get(ChainAccountStore)
.has(context, bouncedCCM.receivingChainID);
partnerChainID = !receivingChainExists ? mainchainID : bouncedCCM.receivingChainID;
}
await this.internalMethod.addToOutbox(context, partnerChainID, bouncedCCM);
const newCcmID = utils.hash(codec.encode(ccmSchema, bouncedCCM));
this.events
.get(CcmSendSuccessEvent)
.log(context, bouncedCCM.sendingChainID, bouncedCCM.receivingChainID, newCcmID, {
ccm: bouncedCCM,
});
}
protected async verifyCCM(context: CrossChainMessageContext, ccmID: Buffer): Promise<boolean> {
const { ccm, logger } = context;
try {
const isLive = await this.internalMethod.isLive(context, ccm.sendingChainID);
if (!isLive) {
throw new Error(`Sending chain ${ccm.sendingChainID.toString('hex')} is not live.`);
}
// Modules can verify the CCM.
// The Token module verifies the escrowed balance in the CCM sending chain for the message fee.
for (const [module, method] of this.interoperableCCMethods.entries()) {
if (method.verifyCrossChainMessage) {
logger.debug({ module, ccmID: ccmID.toString('hex') }, 'verifying cross chain message');
await method.verifyCrossChainMessage(context);
}
}
return true;
} catch (error) {
logger.info(
{ err: error as Error, moduleName: ccm.module, commandName: ccm.crossChainCommand },
'Fail to verify cross chain message.',
);
await this.internalMethod.terminateChainInternal(context, ccm.sendingChainID);
// Notice that, since the sending chain has been terminated,
// the verification of all future CCMs will fail.
this.events.get(CcmProcessedEvent).log(context, ccm.sendingChainID, ccm.receivingChainID, {
code: CCMProcessedCode.INVALID_CCM_VERIFY_CCM_EXCEPTION,
result: CCMProcessedResult.DISCARDED,
ccm,
});
return false;
}
}
// verifyCertificateSignature and verifyPartnerChainOutboxRoot checks are expensive. Therefore, it is done in the execute step instead of the verify
// step. Otherwise, a malicious relayer could spam the transaction pool with computationally
// costly CCU verifications without paying fees.
protected async verifyCertificateSignatureAndPartnerChainOutboxRoot(
context: CommandExecuteContext<CrossChainUpdateTransactionParams>,
) {
const { params, transaction } = context;
const { inboxUpdate } = params;
// Verify certificate signature. We do it here because if it fails, the transaction fails rather than being invalid.
await this.internalMethod.verifyCertificateSignature(context, params);
if (!isInboxUpdateEmpty(inboxUpdate)) {
await this.internalMethod.verifyPartnerChainOutboxRoot(context, params);
// Initialize the relayer account for the message fee token.
// This is necessary to ensure that the relayer can receive the CCM fees
// If the account already exists, nothing is done.
const messageFeeTokenID = await this._interopsMethod.getMessageFeeTokenID(
context,
params.sendingChainID,
);
await this._tokenMethod.initializeUserAccount(
context,
transaction.senderAddress,
messageFeeTokenID,
);
}
}
}
``` | /content/code_sandbox/framework/src/modules/interoperability/base_cross_chain_update_command.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 5,423 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(TFMCurrent)-tvos$(TPVtvOSCurrent)</TargetFrameworks>
<TargetFrameworks Condition="'$(TFMNext)' != ''">$(TargetFrameworks);$(TFMNext)-tvos$(TPVtvOSNext)</TargetFrameworks>
<PackagingGroup>HarfBuzzSharp</PackagingGroup>
<Title>$(PackagingGroup) - Native Assets for tvOS</Title>
</PropertyGroup>
<ItemGroup>
<PackageFile Include="..\..\output\native\tvos\libHarfBuzzSharp.framework\**" PackagePath="runtimes\tvos\native\libHarfBuzzSharp.framework" />
</ItemGroup>
<Target Name="IncludeAdditionalTfmSpecificPackageFiles">
<ItemGroup>
<TfmSpecificPackageFile Include="buildTransitive\HarfBuzzSharp.targets" PackagePath="buildTransitive\$(NuGetShortFolderName)\$(PackageId).targets" />
</ItemGroup>
</Target>
</Project>
``` | /content/code_sandbox/binding/HarfBuzzSharp.NativeAssets.tvOS/HarfBuzzSharp.NativeAssets.tvOS.csproj | xml | 2016-02-22T17:54:43 | 2024-08-16T17:53:42 | SkiaSharp | mono/SkiaSharp | 4,347 | 231 |
```xml
export const retrieveTenantSites = jest.fn();
``` | /content/code_sandbox/server/src/core/server/models/__mocks__/site.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 10 |
```xml
import {Store} from "@tsed/core";
import {RawSocketSession, SocketFilters, SocketSession} from "../index.js";
describe("SocketSession", () => {
it("should set metadata", () => {
class Test {}
SocketSession(Test, "test", 0);
const store = Store.from(Test);
expect(store.get("socketIO")).toEqual({
handlers: {
test: {
parameters: {
"0": {
filter: SocketFilters.SESSION,
mapIndex: undefined
}
}
}
}
});
});
});
describe("RawSocketSession", () => {
it("should set metadata", () => {
class Test {}
RawSocketSession(Test, "test", 0);
const store = Store.from(Test);
expect(store.get("socketIO")).toEqual({
handlers: {
test: {
parameters: {
"0": {
filter: SocketFilters.RAW_SESSION,
mapIndex: undefined
}
}
}
}
});
});
});
``` | /content/code_sandbox/packages/third-parties/socketio/src/decorators/socketSession.spec.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 221 |
```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
/// <reference types="@stdlib/types"/>
import { NumericArray } from '@stdlib/types/array';
/**
* Interface describing `gapxsumpw`.
*/
interface Routine {
/**
* Adds a constant to each strided array element and computes the sum using pairwise summation.
*
* @param N - number of indexed elements
* @param alpha - constant
* @param x - input array
* @param stride - stride length
* @returns sum
*
* @example
* var x = [ 1.0, -2.0, 2.0 ];
*
* var v = gapxsumpw( x.length, 5.0, x, 1 );
* // returns 16.0
*/
( N: number, alpha: number, x: NumericArray, stride: number ): number;
/**
* Adds a constant to each strided array element and computes the sum using pairwise summation and alternative indexing semantics.
*
* @param N - number of indexed elements
* @param alpha - constant
* @param x - input array
* @param stride - stride length
* @param offset - starting index
* @returns sum
*
* @example
* var x = [ 1.0, -2.0, 2.0 ];
*
* var v = gapxsumpw.ndarray( x.length, 5.0, x, 1, 0 );
* // returns 16.0
*/
ndarray( N: number, alpha: number, x: NumericArray, stride: number, offset: number ): number;
}
/**
* Adds a constant to each strided array element and computes the sum using pairwise summation.
*
* @param N - number of indexed elements
* @param alpha - constant
* @param x - input array
* @param stride - stride length
* @returns sum
*
* @example
* var x = [ 1.0, -2.0, 2.0 ];
*
* var v = gapxsumpw( x.length, 5.0, x, 1 );
* // returns 16.0
*
* @example
* var x = [ 1.0, -2.0, 2.0 ];
*
* var v = gapxsumpw.ndarray( x.length, 5.0, x, 1, 0 );
* // returns 16.0
*/
declare var gapxsumpw: Routine;
// EXPORTS //
export = gapxsumpw;
``` | /content/code_sandbox/lib/node_modules/@stdlib/blas/ext/base/gapxsumpw/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 616 |
```xml
import { Injectable } from '@angular/core';
import { Location } from '@angular/common';
import { Store, Action } from '@ngrx/store';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { Observable } from 'rxjs';
import { map, withLatestFrom } from 'rxjs/operators';
import * as fromRoot from '../reducers';
import * as mediaWallDirectUrlAction from '../actions/media-wall-direct-url';
import { generateDirectUrl } from '../models';
/**
* Effects offer a way to isolate and easily test side-effects within your
* application. StateUpdates is an observable of the latest state and
* dispatched action. The `toPayload` helper function returns just
* the payload of the currently dispatched action, useful in
* instances where the current state is not necessary.
*
* A simple way to think of it is that ngrx/effects is an event listener of sorts.
* It listens for actions being dispatched to the store. You can then tell `ngrx/effects`
* that when a particular action is dispatched, to take another, new action as a result.
* At the end, whats really happening is `ngrx/effects` is an `action generator` that dispatches
* a `new action` as a result of a different action.
*/
@Injectable()
export class MediaWallDirectUrlEffects {
@Effect()
generateDirectUrl$: Observable<Action>
= this.actions$
.pipe(
ofType(mediaWallDirectUrlAction.ActionTypes.WALL_GENERATE_DIRECT_URL),
withLatestFrom(this.store$),
map(([action, state]) => {
return {
query: state.mediaWallQuery.query,
design: state.mediaWallDesign.design,
hiddenFeedId: state.mediaWallResponse.response.hiddenFeedId,
blockedUser: state.mediaWallResponse.response.blockedUser,
profanityCheck: state.mediaWallResponse.response.profanityCheck,
removeDuplicate: state.mediaWallResponse.response.removeDuplicate,
wallHeader: state.mediaWallCustom.wallHeader,
wallCard: state.mediaWallCustom.wallCard,
wallBackground: state.mediaWallCustom.wallBackground
};
}),
map(queryObject => {
const configSet = {
query: queryObject.query.displayString,
imageFilter: queryObject.query.filter.image,
location: queryObject.query.location,
displayHeader: queryObject.design.displayHeader,
columnCount: queryObject.design.columnCount,
count: queryObject.design.count,
cardStyle: queryObject.design.cardStyle,
headerTitle: queryObject.design.headerTitle,
hiddenFeedId: queryObject.hiddenFeedId,
blockedUser: queryObject.blockedUser,
profanityCheck: queryObject.profanityCheck,
removeDuplicate: queryObject.removeDuplicate,
wallHeaderBackgroundColor: queryObject.wallHeader.backgroundColor,
wallHeaderFontColor: queryObject.wallHeader.fontColor,
wallCardFontColor: queryObject.wallCard.fontColor,
wallCardAccentColor: queryObject.wallCard.accentColor,
wallCardBackgroundColor: queryObject.wallCard.backgroundColor,
wallBackgroundColor: queryObject.wallBackground.backgroundColor
};
const directUrl = generateDirectUrl(configSet);
this.location.go(`/wall?${directUrl}`);
return new mediaWallDirectUrlAction.WallShortenDirectUrlAction(directUrl);
})
);
constructor(
private actions$: Actions,
private store$: Store<fromRoot.State>,
private location: Location
) { }
}
``` | /content/code_sandbox/src/app/effects/media-wall-direct-url.effects.ts | xml | 2016-09-20T13:50:42 | 2024-08-06T13:58:18 | loklak_search | fossasia/loklak_search | 1,829 | 739 |
```xml
/**
* Set bit on the number
*/
export const setBit = (number = 0, mask: number): number => number | mask;
/**
* Toggle a bit from the number
*/
export const toggleBit = (number = 0, mask: number): number => number ^ mask;
/**
* Clear a bit from the number
*/
export const clearBit = (number = 0, mask: number): number => number & ~mask;
/**
* Check if a bit is set in the number
*/
export const hasBit = (number = 0, mask: number): boolean => (number & mask) === mask;
export const hasBitBigInt = (number = BigInt(0), mask: bigint): boolean => (number & BigInt(mask)) === BigInt(mask);
/**
* Get all bits which are toggled on in the respective bitmap
*/
export const getBits = (bitmap: number) => {
const size = Math.floor(Math.log2(bitmap)) + 1;
const bits: number[] = [];
for (let i = 0; i <= size; i++) {
const bit = 2 ** i;
if (hasBit(bitmap, bit)) {
bits.push(bit);
}
}
return bits;
};
``` | /content/code_sandbox/packages/shared/lib/helpers/bitset.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 261 |
```xml
import * as React from 'react';
import { iconPlus, iconSearch } from "../../icons/Icons";
import { __ } from "../../utils";
import ConversationItem from "../containers/ConversationItem";
import { IConversation } from "../types";
import TopBar from "../containers/TopBar";
type Props = {
conversations: IConversation[];
goToConversation: (conversationId: string) => void;
createConversation: (e: React.FormEvent<HTMLLIElement>) => void;
goToHome: () => void;
loading: boolean;
};
function ConversationList(props: Props) {
const {
conversations,
goToConversation,
loading,
createConversation,
goToHome
} = props;
const [searchValue, setSearchValue] = React.useState<string>('');
const [ conversationList, setConversationList] = React.useState<IConversation[]>([]);
React.useEffect(() => {
if(!loading) {
setConversationList(conversations);
}
if(searchValue) {
setConversationList(result => result.filter(conv => conv.content.toString().toLowerCase().indexOf(searchValue.toLowerCase()) > -1));
}
}, [searchValue, loading]);
if (loading) {
return <div className="loader" />;
}
const createButton = () => {
return (
<ul className="erxes-last-section">
<li onClick={createConversation} className="erxes-create-btn">
<span>{iconPlus}</span>
<span className="erxes-start-text">{__("Start new conversation")}</span>
</li>
</ul>
);
};
const searchButton = () => {
return (
<li className="erxes-list-item">
<div className="erxes-left-side">
<span>{iconSearch}</span>
</div>
<div className="erxes-right-side">
<div className="erxes-name">
<input type="text" onChange={(e) => setSearchValue(e.target.value)} placeholder="Search for a conversation..." value={searchValue} />
</div>
</div>
</li>
);
}
return (
<>
<TopBar
middle={
`Previous Conversations`
}
onLeftButtonClick={goToHome}
/>
<div className="erxes-content">
<ul className="erxes-conversation-list">
{searchButton()}
{conversationList.map(conversation => (
<ConversationItem
key={conversation._id}
conversation={conversation}
goToConversation={goToConversation}
/>
))}
</ul>
{createButton()}
</div>
</>
);
}
export default ConversationList;
``` | /content/code_sandbox/widgets/client/messenger/components/ConversationList.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 566 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="path_to_url" xmlns:xsi="path_to_url" xmlns:flowable="path_to_url" xmlns:cmmndi="path_to_url" xmlns:dc="path_to_url" xmlns:di="path_to_url" xmlns:design="path_to_url" targetNamespace="path_to_url">
<case id="caseAndStageCompletionWithChildItemsTest" name="Case And Stage Completion With Child Items Test" flowable:initiatorVariableName="initiator" flowable:candidateStarterGroups="flowableUser">
<casePlanModel id="onecaseplanmodel1" name="Case plan model" flowable:formFieldValidation="false" autoComplete="true">
<extensionElements>
<flowable:default-menu-navigation-size><![CDATA[expanded]]></flowable:default-menu-navigation-size>
<flowable:work-form-field-validation><![CDATA[false]]></flowable:work-form-field-validation>
<design:stencilid><![CDATA[CasePlanModel]]></design:stencilid>
</extensionElements>
<planItem id="planItem5" name="Stage A" definitionRef="expandedStage1"></planItem>
<planItem id="planItem6" name="Manual task" definitionRef="humanTask5">
<itemControl>
<manualActivationRule></manualActivationRule>
</itemControl>
</planItem>
<planItem id="planItem7" name="Ignored task" definitionRef="humanTask6">
<itemControl>
<extensionElements>
<flowable:parentCompletionRule type="ignore"></flowable:parentCompletionRule>
</extensionElements>
</itemControl>
</planItem>
<planItem id="planItem8" name="Ignore after first completion task" definitionRef="humanTask7">
<itemControl>
<extensionElements>
<flowable:parentCompletionRule type="ignoreAfterFirstCompletion"></flowable:parentCompletionRule>
</extensionElements>
<repetitionRule flowable:counterVariable="repetitionCounter">
<extensionElements></extensionElements>
</repetitionRule>
</itemControl>
</planItem>
<stage id="expandedStage1" name="Stage A" autoComplete="true" flowable:includeInStageOverview="true">
<extensionElements>
<design:stencilid><![CDATA[ExpandedStage]]></design:stencilid>
</extensionElements>
<planItem id="planItem1" name="Task A" definitionRef="humanTask1"></planItem>
<planItem id="planItem2" name="Manual stage task" definitionRef="humanTask2">
<itemControl>
<manualActivationRule></manualActivationRule>
</itemControl>
</planItem>
<planItem id="planItem3" name="Ignored stage task" definitionRef="humanTask3">
<itemControl>
<extensionElements>
<flowable:parentCompletionRule type="ignore"></flowable:parentCompletionRule>
</extensionElements>
</itemControl>
</planItem>
<planItem id="planItem4" name="Ignore after first completion stage task" definitionRef="humanTask4">
<itemControl>
<extensionElements>
<flowable:parentCompletionRule type="ignoreAfterFirstCompletion"></flowable:parentCompletionRule>
</extensionElements>
<repetitionRule flowable:counterVariable="repetitionCounter">
<extensionElements></extensionElements>
</repetitionRule>
</itemControl>
</planItem>
<humanTask id="humanTask1" name="Task A" flowable:assignee="${initiator}" flowable:formFieldValidation="false">
<extensionElements>
<flowable:task-candidates-type><![CDATA[all]]></flowable:task-candidates-type>
<design:stencilid><![CDATA[HumanTask]]></design:stencilid>
<design:stencilsuperid><![CDATA[Task]]></design:stencilsuperid>
</extensionElements>
</humanTask>
<humanTask id="humanTask2" name="Manual stage task" flowable:assignee="${initiator}" flowable:formFieldValidation="false">
<extensionElements>
<flowable:task-candidates-type><![CDATA[all]]></flowable:task-candidates-type>
<design:stencilid><![CDATA[HumanTask]]></design:stencilid>
<design:stencilsuperid><![CDATA[Task]]></design:stencilsuperid>
</extensionElements>
</humanTask>
<humanTask id="humanTask3" name="Ignored stage task" flowable:assignee="${initiator}" flowable:formFieldValidation="false">
<extensionElements>
<flowable:task-candidates-type><![CDATA[all]]></flowable:task-candidates-type>
<design:stencilid><![CDATA[HumanTask]]></design:stencilid>
<design:stencilsuperid><![CDATA[Task]]></design:stencilsuperid>
</extensionElements>
</humanTask>
<humanTask id="humanTask4" name="Ignore after first completion stage task" flowable:assignee="${initiator}" flowable:formFieldValidation="false">
<extensionElements>
<flowable:task-candidates-type><![CDATA[all]]></flowable:task-candidates-type>
<design:stencilid><![CDATA[HumanTask]]></design:stencilid>
<design:stencilsuperid><![CDATA[Task]]></design:stencilsuperid>
</extensionElements>
</humanTask>
</stage>
<humanTask id="humanTask5" name="Manual task" flowable:assignee="${initiator}" flowable:formFieldValidation="false">
<extensionElements>
<flowable:task-candidates-type><![CDATA[all]]></flowable:task-candidates-type>
<design:stencilid><![CDATA[HumanTask]]></design:stencilid>
<design:stencilsuperid><![CDATA[Task]]></design:stencilsuperid>
</extensionElements>
</humanTask>
<humanTask id="humanTask6" name="Ignored task" flowable:assignee="${initiator}" flowable:formFieldValidation="false">
<extensionElements>
<flowable:task-candidates-type><![CDATA[all]]></flowable:task-candidates-type>
<design:stencilid><![CDATA[HumanTask]]></design:stencilid>
<design:stencilsuperid><![CDATA[Task]]></design:stencilsuperid>
</extensionElements>
</humanTask>
<humanTask id="humanTask7" name="Ignore after first completion task" flowable:assignee="${initiator}" flowable:formFieldValidation="false">
<extensionElements>
<flowable:task-candidates-type><![CDATA[all]]></flowable:task-candidates-type>
<design:stencilid><![CDATA[HumanTask]]></design:stencilid>
<design:stencilsuperid><![CDATA[Task]]></design:stencilsuperid>
</extensionElements>
</humanTask>
</casePlanModel>
</case>
<cmmndi:CMMNDI>
<cmmndi:CMMNDiagram id="CMMNDiagram_caseAndStageCompletionWithChildItemsTest">
<cmmndi:CMMNShape id="CMMNShape_onecaseplanmodel1" cmmnElementRef="onecaseplanmodel1">
<dc:Bounds height="585.0" width="581.0" x="30.0" y="45.0"></dc:Bounds>
<cmmndi:CMMNLabel></cmmndi:CMMNLabel>
</cmmndi:CMMNShape>
<cmmndi:CMMNShape id="CMMNShape_planItem5" cmmnElementRef="planItem5">
<dc:Bounds height="305.0" width="488.0" x="75.0" y="105.0"></dc:Bounds>
<cmmndi:CMMNLabel></cmmndi:CMMNLabel>
</cmmndi:CMMNShape>
<cmmndi:CMMNShape id="CMMNShape_planItem1" cmmnElementRef="planItem1">
<dc:Bounds height="80.0" width="100.0" x="121.0" y="151.0"></dc:Bounds>
<cmmndi:CMMNLabel></cmmndi:CMMNLabel>
</cmmndi:CMMNShape>
<cmmndi:CMMNShape id="CMMNShape_planItem2" cmmnElementRef="planItem2">
<dc:Bounds height="80.0" width="100.0" x="121.0" y="285.0"></dc:Bounds>
<cmmndi:CMMNLabel></cmmndi:CMMNLabel>
</cmmndi:CMMNShape>
<cmmndi:CMMNShape id="CMMNShape_planItem3" cmmnElementRef="planItem3">
<dc:Bounds height="80.0" width="100.0" x="255.0" y="285.0"></dc:Bounds>
<cmmndi:CMMNLabel></cmmndi:CMMNLabel>
</cmmndi:CMMNShape>
<cmmndi:CMMNShape id="CMMNShape_planItem4" cmmnElementRef="planItem4">
<dc:Bounds height="80.0" width="100.0" x="390.0" y="285.0"></dc:Bounds>
<cmmndi:CMMNLabel></cmmndi:CMMNLabel>
</cmmndi:CMMNShape>
<cmmndi:CMMNShape id="CMMNShape_planItem6" cmmnElementRef="planItem6">
<dc:Bounds height="80.0" width="100.0" x="121.0" y="480.0"></dc:Bounds>
<cmmndi:CMMNLabel></cmmndi:CMMNLabel>
</cmmndi:CMMNShape>
<cmmndi:CMMNShape id="CMMNShape_planItem7" cmmnElementRef="planItem7">
<dc:Bounds height="80.0" width="100.0" x="255.0" y="480.0"></dc:Bounds>
<cmmndi:CMMNLabel></cmmndi:CMMNLabel>
</cmmndi:CMMNShape>
<cmmndi:CMMNShape id="CMMNShape_planItem8" cmmnElementRef="planItem8">
<dc:Bounds height="80.0" width="100.0" x="390.0" y="480.0"></dc:Bounds>
<cmmndi:CMMNLabel></cmmndi:CMMNLabel>
</cmmndi:CMMNShape>
</cmmndi:CMMNDiagram>
</cmmndi:CMMNDI>
</definitions>
``` | /content/code_sandbox/modules/flowable-cmmn-engine/src/test/resources/org/flowable/cmmn/test/runtime/Case_And_Stage_Completion_With_Child_Items_Test.cmmn.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 2,490 |
```xml
/* eslint-disable import/prefer-default-export */
import type { Logger } from '@slack/logger';
import { CodedError, ErrorCode } from '../errors';
import { ReceiverEvent } from '../types';
export class SocketModeFunctions {
// ------------------------------------------
// Error handlers for event processing
// ------------------------------------------
// The default processEventErrorHandler implementation:
// Developers can customize this behavior by passing processEventErrorHandler to the constructor
public static async defaultProcessEventErrorHandler(
args: SocketModeReceiverProcessEventErrorHandlerArgs,
): Promise<boolean> {
const { error, logger, event } = args;
// TODO: more details like envelop_id, payload type etc. here
// To make them available, we need to enhance underlying SocketModeClient
// to return more properties to 'slack_event' listeners
logger.error(`An unhandled error occurred while Bolt processed (type: ${event.body?.type}, error: ${error})`);
logger.debug(`Error details: ${error}, retry num: ${event.retryNum}, retry reason: ${event.retryReason}`);
const errorCode = (error as CodedError).code;
if (errorCode === ErrorCode.AuthorizationError) {
// The `authorize` function threw an exception, which means there is no valid installation data.
// In this case, we can tell the Slack server-side to stop retries.
return true;
}
return false;
}
}
// The arguments for the processEventErrorHandler,
// which handles errors `await app.processEvent(even)` method throws
export interface SocketModeReceiverProcessEventErrorHandlerArgs {
error: Error | CodedError;
logger: Logger;
event: ReceiverEvent,
}
``` | /content/code_sandbox/src/receivers/SocketModeFunctions.ts | xml | 2016-07-19T02:46:33 | 2024-08-16T12:34:33 | bolt-js | slackapi/bolt-js | 2,729 | 349 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="path_to_url">
<!-- General -->
<PropertyGroup Label="Globals">
<OutDir>$(SolutionDir)..\bin\$(Configuration)$(PlatformArchitecture)\plugins\</OutDir>
<IntDir>$(ProjectDir)obj\$(Configuration)$(PlatformArchitecture)\</IntDir>
<CodeAnalysisRuleSet>NativeRecommendedRules.ruleset</CodeAnalysisRuleSet>
<UseDebugLibraries Condition="'$(Configuration)'=='Debug'">true</UseDebugLibraries>
<UseDebugLibraries Condition="'$(Configuration)'=='Release'">false</UseDebugLibraries>
<LinkIncremental Condition="'$(Configuration)'=='Debug'">false</LinkIncremental>
<LinkIncremental Condition="'$(Configuration)'=='Release'">false</LinkIncremental>
<WholeProgramOptimization Condition="'$(Configuration)'=='Debug'">false</WholeProgramOptimization>
<WholeProgramOptimization Condition="'$(Configuration)'=='Release'">true</WholeProgramOptimization>
<GenerateManifest>false</GenerateManifest>
<!-- Debugging -->
<LocalDebuggerCommand>$(SolutionDir)..\bin\$(Configuration)$(PlatformArchitecture)\SystemInformer.exe</LocalDebuggerCommand>
<LocalDebuggerWorkingDirectory>$(SolutionDir)..\bin\$(Configuration)$(PlatformArchitecture)\</LocalDebuggerWorkingDirectory>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<!-- Global -->
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(SolutionDir)include;$(SolutionDir)..\sdk\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<TreatWarningAsError>true</TreatWarningAsError>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<MinimalRebuild>false</MinimalRebuild>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<LanguageStandard>stdcpplatest</LanguageStandard>
<LanguageStandard_C Condition="'$(MSBuildVersion)' < '17.11'">stdc17</LanguageStandard_C>
<LanguageStandard_C Condition="'$(MSBuildVersion)' >= '17.11'">stdclatest</LanguageStandard_C>
<StringPooling>true</StringPooling>
<SupportJustMyCode>false</SupportJustMyCode>
<CallingConvention>StdCall</CallingConvention>
<BuildStlModules>false</BuildStlModules>
</ClCompile>
<Link>
<AdditionalDependencies>SystemInformer.lib;thirdparty.lib;ntdll.lib;noenv.obj;noarg.obj;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalOptions>/NATVIS:$(SolutionDir)\..\SystemInformer.natvis %(AdditionalOptions)</AdditionalOptions>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
</Link>
<BuildLog>
<Path>$(IntDir)$(MSBuildProjectName).log</Path>
</BuildLog>
<PostBuildEvent>
<Command>"$(SolutionDir)..\tools\CustomBuildTool\bin\Release\$(PROCESSOR_ARCHITECTURE)\CustomBuildTool.exe" -kph-sign $(OutDir)$(TargetName)$(TargetExt)</Command>
</PostBuildEvent>
<ResourceCompile>
<AdditionalOptions>/c 65001 %(AdditionalOptions)</AdditionalOptions>
<PreprocessorDefinitions>%(PreprocessorDefinitions);$(ExternalCompilerOptions)</PreprocessorDefinitions>
</ResourceCompile>
</ItemDefinitionGroup>
<!-- Debug Builds -->
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<Optimization>Disabled</Optimization>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<FunctionLevelLinking>false</FunctionLevelLinking>
<IntrinsicFunctions>false</IntrinsicFunctions>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
</ItemDefinitionGroup>
<!-- Release Builds -->
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<Optimization>Full</Optimization>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<WholeProgramOptimization>true</WholeProgramOptimization>
<ControlFlowGuard>Guard</ControlFlowGuard>
</ClCompile>
<Link>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<SetChecksum>true</SetChecksum>
<LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
</Link>
</ItemDefinitionGroup>
<!-- ARM64 Builds -->
<ItemDefinitionGroup Condition="'$(Platform)'=='ARM64'">
<Link>
<AdditionalLibraryDirectories>$(SolutionDir)..\sdk\lib\arm64;$(SolutionDir)..\tools\thirdparty\bin\$(Configuration)$(PlatformArchitecture);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<TargetMachine>MachineARM64</TargetMachine>
<MinimumRequiredVersion>10.0</MinimumRequiredVersion>
</Link>
</ItemDefinitionGroup>
<!-- Win32 Builds -->
<ItemDefinitionGroup Condition="'$(Platform)'=='Win32'">
<ClCompile>
<CallingConvention>StdCall</CallingConvention>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
</ClCompile>
<Link>
<AdditionalLibraryDirectories>$(SolutionDir)..\sdk\lib\i386;$(SolutionDir)..\tools\thirdparty\bin\$(Configuration)$(PlatformArchitecture);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<TargetMachine>MachineX86</TargetMachine>
<MinimumRequiredVersion>6.01</MinimumRequiredVersion>
</Link>
</ItemDefinitionGroup>
<!-- x64 Builds -->
<ItemDefinitionGroup Condition="'$(Platform)'=='x64'">
<ClCompile>
<CallingConvention>StdCall</CallingConvention>
</ClCompile>
<Link>
<AdditionalLibraryDirectories>$(SolutionDir)..\sdk\lib\amd64;$(SolutionDir)..\tools\thirdparty\bin\$(Configuration)$(PlatformArchitecture);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<TargetMachine>MachineX64</TargetMachine>
<MinimumRequiredVersion>6.01</MinimumRequiredVersion>
</Link>
</ItemDefinitionGroup>
<!-- Debug|ARM64 Builds -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
<ClCompile>
<PreprocessorDefinitions>WIN64;DEBUG;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions);$(ExternalCompilerOptions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<AdditionalOptions>/DEPENDENTLOADFLAG:0x800 /FILEALIGN:0x1000 %(AdditionalOptions) $(ExternalLinkerOptions)</AdditionalOptions>
</Link>
</ItemDefinitionGroup>
<!-- Debug|Win32 Builds -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;DEBUG;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions);$(ExternalCompilerOptions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<AdditionalOptions>/DEPENDENTLOADFLAG:0x800 /FILEALIGN:0x1000 %(AdditionalOptions) $(ExternalLinkerOptions)</AdditionalOptions>
</Link>
</ItemDefinitionGroup>
<!-- Debug|x64 Builds -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PreprocessorDefinitions>WIN64;DEBUG;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions);$(ExternalCompilerOptions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<AdditionalOptions>/DEPENDENTLOADFLAG:0x800 /FILEALIGN:0x1000 %(AdditionalOptions) $(ExternalLinkerOptions)</AdditionalOptions>
</Link>
</ItemDefinitionGroup>
<!-- Release|ARM64 Builds -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
<ClCompile>
<PreprocessorDefinitions>WIN64;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions);$(ExternalCompilerOptions)</PreprocessorDefinitions>
<AdditionalOptions>/utf-8 /d1nodatetime %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<AdditionalOptions>/BREPRO /DEPENDENTLOADFLAG:0x800 /PDBALTPATH:%_PDB% /FILEALIGN:0x1000 %(AdditionalOptions) $(ExternalLinkerOptions)</AdditionalOptions>
</Link>
</ItemDefinitionGroup>
<!-- Release|Win32 Builds -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions);$(ExternalCompilerOptions)</PreprocessorDefinitions>
<SpectreMitigation>Spectre</SpectreMitigation>
<IntelJCCErratum>true</IntelJCCErratum>
<AdditionalOptions>/utf-8 /d1nodatetime %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<CETCompat>true</CETCompat>
<AdditionalOptions>/BREPRO /DEPENDENTLOADFLAG:0x800 /PDBALTPATH:%_PDB% /FILEALIGN:0x1000 %(AdditionalOptions) $(ExternalLinkerOptions)</AdditionalOptions>
</Link>
</ItemDefinitionGroup>
<!-- Release|x64 Builds -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PreprocessorDefinitions>WIN64;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions);$(ExternalCompilerOptions)</PreprocessorDefinitions>
<SpectreMitigation>Spectre</SpectreMitigation>
<IntelJCCErratum>true</IntelJCCErratum>
<GuardEHContMetadata>true</GuardEHContMetadata>
<AdditionalOptions>/utf-8 /d1nodatetime /guard:xfg %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<CETCompat>true</CETCompat>
<AdditionalOptions>/BREPRO /DEPENDENTLOADFLAG:0x800 /PDBALTPATH:%_PDB% /FILEALIGN:0x1000 /guard:xfg %(AdditionalOptions) $(ExternalLinkerOptions)</AdditionalOptions>
</Link>
</ItemDefinitionGroup>
</Project>
``` | /content/code_sandbox/plugins/Plugins.props | xml | 2016-02-01T08:10:21 | 2024-08-16T17:50:20 | systeminformer | winsiderss/systeminformer | 10,712 | 2,388 |
```xml
import React, {CSSProperties} from 'react';
import styled from 'styled-components';
import {ClickView} from './ClickView';
import {Text} from './Text';
import {appTheme} from '../Style/appTheme';
import {ShellUtil} from '../Util/ShellUtil';
type Props = {
url?: string | (() => string);
onClick?: (defaultOnClick: () => void) => void;
style?: CSSProperties;
className?: string;
}
type State = {
}
export class Link extends React.Component<Props, State> {
private handleClick() {
const defaultOnClick = () => {
if (typeof this.props.url === 'function') {
ShellUtil.openExternal(this.props.url());
} else {
ShellUtil.openExternal(this.props.url);
}
}
if (this.props.onClick) {
this.props.onClick(defaultOnClick);
} else if (this.props.url) {
defaultOnClick();
}
}
render() {
return (
<ClickView onClick={() => this.handleClick()} style={{display: 'inline'}}>
<LinkText className={this.props.className} style={this.props.style}>{this.props.children}</LinkText>
</ClickView>
);
}
}
const LinkText = styled(Text)`
font-size: inherit;
color: ${() => appTheme().text.link};
text-decoration: underline;
`;
``` | /content/code_sandbox/src/Renderer/Library/View/Link.tsx | xml | 2016-05-10T12:55:31 | 2024-08-11T04:32:50 | jasper | jasperapp/jasper | 1,318 | 288 |
```xml
import { EntityIdentifierUtils } from '@gitkraken/provider-apis';
import { Disposable, Uri, window } from 'vscode';
import type { GHPRPullRequest } from '../../../commands/ghpr/openOrCreateWorktree';
import { Commands } from '../../../constants';
import type { Container } from '../../../container';
import type { FeatureAccess, RepoFeatureAccess } from '../../../features';
import { PlusFeatures } from '../../../features';
import { add as addRemote } from '../../../git/actions/remote';
import * as RepoActions from '../../../git/actions/repository';
import type { GitBranch } from '../../../git/models/branch';
import { getLocalBranchByUpstream } from '../../../git/models/branch';
import type { SearchedIssue } from '../../../git/models/issue';
import { serializeIssue } from '../../../git/models/issue';
import type { PullRequestShape, SearchedPullRequest } from '../../../git/models/pullRequest';
import {
PullRequestMergeableState,
PullRequestReviewDecision,
serializePullRequest,
} from '../../../git/models/pullRequest';
import { createReference } from '../../../git/models/reference';
import type { GitRemote } from '../../../git/models/remote';
import type { Repository, RepositoryChangeEvent } from '../../../git/models/repository';
import { RepositoryChange, RepositoryChangeComparisonMode } from '../../../git/models/repository';
import type { GitWorktree } from '../../../git/models/worktree';
import { getWorktreeForBranch } from '../../../git/models/worktree';
import { parseGitRemoteUrl } from '../../../git/parsers/remoteParser';
import type { RemoteProvider } from '../../../git/remotes/remoteProvider';
import { executeCommand } from '../../../system/command';
import { debug } from '../../../system/decorators/log';
import { Logger } from '../../../system/logger';
import { getLogScope } from '../../../system/logger.scope';
import { PageableResult } from '../../../system/paging';
import { getSettledValue } from '../../../system/promise';
import type { IpcMessage } from '../../../webviews/protocol';
import type { WebviewHost, WebviewProvider } from '../../../webviews/webviewProvider';
import type { EnrichableItem, EnrichedItem } from '../../focus/enrichmentService';
import { convertRemoteProviderToEnrichProvider } from '../../focus/enrichmentService';
import type { SubscriptionChangeEvent } from '../../gk/account/subscriptionService';
import { getEntityIdentifierInput } from '../../integrations/providers/utils';
import type { ShowInCommitGraphCommandArgs } from '../graph/protocol';
import type {
OpenBranchParams,
OpenWorktreeParams,
PinIssueParams,
PinPrParams,
SnoozeIssueParams,
SnoozePrParams,
State,
SwitchToBranchParams,
} from './protocol';
import {
DidChangeNotification,
OpenBranchCommand,
OpenWorktreeCommand,
PinIssueCommand,
PinPRCommand,
SnoozeIssueCommand,
SnoozePRCommand,
SwitchToBranchCommand,
} from './protocol';
interface RepoWithRichRemote {
repo: Repository;
remote: GitRemote<RemoteProvider>;
isConnected: boolean;
isGitHub: boolean;
}
interface SearchedPullRequestWithRemote extends SearchedPullRequest {
repoAndRemote: RepoWithRichRemote;
branch?: GitBranch;
hasLocalBranch?: boolean;
isCurrentBranch?: boolean;
hasWorktree?: boolean;
isCurrentWorktree?: boolean;
rank: number;
enriched?: EnrichedItem[];
}
interface SearchedIssueWithRank extends SearchedIssue {
repoAndRemote: RepoWithRichRemote;
rank: number;
enriched?: EnrichedItem[];
}
export class FocusWebviewProvider implements WebviewProvider<State> {
private _pullRequests: SearchedPullRequestWithRemote[] = [];
private _issues: SearchedIssueWithRank[] = [];
private _discovering: Promise<number | undefined> | undefined;
private readonly _disposable: Disposable;
private _etag?: number;
private _etagSubscription?: number;
private _repositoryEventsDisposable?: Disposable;
private _repos?: RepoWithRichRemote[];
private _enrichedItems?: EnrichedItem[];
constructor(
private readonly container: Container,
private readonly host: WebviewHost,
) {
this._disposable = Disposable.from(
this.container.subscription.onDidChange(this.onSubscriptionChanged, this),
this.container.git.onDidChangeRepositories(async () => {
if (this._etag !== this.container.git.etag) {
if (this._discovering != null) {
this._etag = await this._discovering;
if (this._etag === this.container.git.etag) return;
}
void this.host.refresh(true);
}
}),
);
}
dispose() {
if (this.enrichmentExpirationTimeout != null) {
clearTimeout(this.enrichmentExpirationTimeout);
this.enrichmentExpirationTimeout = undefined;
}
this._disposable.dispose();
}
onMessageReceived(e: IpcMessage) {
switch (true) {
case OpenBranchCommand.is(e):
void this.onOpenBranch(e.params);
break;
case SwitchToBranchCommand.is(e):
void this.onSwitchBranch(e.params);
break;
case OpenWorktreeCommand.is(e):
void this.onOpenWorktree(e.params);
break;
case SnoozePRCommand.is(e):
void this.onSnoozePr(e.params);
break;
case PinPRCommand.is(e):
void this.onPinPr(e.params);
break;
case SnoozeIssueCommand.is(e):
void this.onSnoozeIssue(e.params);
break;
case PinIssueCommand.is(e):
void this.onPinIssue(e.params);
break;
}
}
@debug({ args: false })
private async onPinIssue({ issue, pin }: PinIssueParams) {
const issueWithRemote = this._issues?.find(r => r.issue.nodeId === issue.nodeId);
if (issueWithRemote == null) return;
if (pin) {
await this.container.enrichments.unpinItem(pin);
this._enrichedItems = this._enrichedItems?.filter(e => e.id !== pin);
issueWithRemote.enriched = issueWithRemote.enriched?.filter(e => e.id !== pin);
} else {
const focusItem: EnrichableItem = {
type: 'issue',
id: EntityIdentifierUtils.encode(getEntityIdentifierInput(issueWithRemote.issue)),
provider: convertRemoteProviderToEnrichProvider(issueWithRemote.repoAndRemote.remote.provider),
url: issueWithRemote.issue.url,
};
const enrichedItem = await this.container.enrichments.pinItem(focusItem);
if (enrichedItem == null) return;
if (this._enrichedItems == null) {
this._enrichedItems = [];
}
this._enrichedItems.push(enrichedItem);
if (issueWithRemote.enriched == null) {
issueWithRemote.enriched = [];
}
issueWithRemote.enriched.push(enrichedItem);
}
void this.notifyDidChangeState();
}
@debug({ args: false })
private async onSnoozeIssue({ issue, snooze, expiresAt }: SnoozeIssueParams) {
const issueWithRemote = this._issues?.find(r => r.issue.nodeId === issue.nodeId);
if (issueWithRemote == null) return;
if (snooze) {
await this.container.enrichments.unsnoozeItem(snooze);
this._enrichedItems = this._enrichedItems?.filter(e => e.id !== snooze);
issueWithRemote.enriched = issueWithRemote.enriched?.filter(e => e.id !== snooze);
} else {
const focusItem: EnrichableItem = {
type: 'issue',
id: EntityIdentifierUtils.encode(getEntityIdentifierInput(issueWithRemote.issue)),
provider: convertRemoteProviderToEnrichProvider(issueWithRemote.repoAndRemote.remote.provider),
url: issueWithRemote.issue.url,
};
if (expiresAt != null) {
focusItem.expiresAt = expiresAt;
}
const enrichedItem = await this.container.enrichments.snoozeItem(focusItem);
if (enrichedItem == null) return;
if (this._enrichedItems == null) {
this._enrichedItems = [];
}
this._enrichedItems.push(enrichedItem);
if (issueWithRemote.enriched == null) {
issueWithRemote.enriched = [];
}
issueWithRemote.enriched.push(enrichedItem);
}
void this.notifyDidChangeState();
}
@debug({ args: false })
private async onPinPr({ pullRequest, pin }: PinPrParams) {
const prWithRemote = this._pullRequests?.find(r => r.pullRequest.nodeId === pullRequest.nodeId);
if (prWithRemote == null) return;
if (pin) {
await this.container.enrichments.unpinItem(pin);
this._enrichedItems = this._enrichedItems?.filter(e => e.id !== pin);
prWithRemote.enriched = prWithRemote.enriched?.filter(e => e.id !== pin);
} else {
const focusItem: EnrichableItem = {
type: 'pr',
id: EntityIdentifierUtils.encode(getEntityIdentifierInput(prWithRemote.pullRequest)),
provider: convertRemoteProviderToEnrichProvider(prWithRemote.repoAndRemote.remote.provider),
url: prWithRemote.pullRequest.url,
};
const enrichedItem = await this.container.enrichments.pinItem(focusItem);
if (enrichedItem == null) return;
if (this._enrichedItems == null) {
this._enrichedItems = [];
}
this._enrichedItems.push(enrichedItem);
if (prWithRemote.enriched == null) {
prWithRemote.enriched = [];
}
prWithRemote.enriched.push(enrichedItem);
}
void this.notifyDidChangeState();
}
@debug({ args: false })
private async onSnoozePr({ pullRequest, snooze, expiresAt }: SnoozePrParams) {
const prWithRemote = this._pullRequests?.find(r => r.pullRequest.nodeId === pullRequest.nodeId);
if (prWithRemote == null) return;
if (snooze) {
await this.container.enrichments.unsnoozeItem(snooze);
this._enrichedItems = this._enrichedItems?.filter(e => e.id !== snooze);
prWithRemote.enriched = prWithRemote.enriched?.filter(e => e.id !== snooze);
} else {
const focusItem: EnrichableItem = {
type: 'pr',
id: EntityIdentifierUtils.encode(getEntityIdentifierInput(prWithRemote.pullRequest)),
provider: convertRemoteProviderToEnrichProvider(prWithRemote.repoAndRemote.remote.provider),
url: prWithRemote.pullRequest.url,
};
if (expiresAt != null) {
focusItem.expiresAt = expiresAt;
}
const enrichedItem = await this.container.enrichments.snoozeItem(focusItem);
if (enrichedItem == null) return;
if (this._enrichedItems == null) {
this._enrichedItems = [];
}
this._enrichedItems.push(enrichedItem);
if (prWithRemote.enriched == null) {
prWithRemote.enriched = [];
}
prWithRemote.enriched.push(enrichedItem);
}
void this.notifyDidChangeState();
}
private findSearchedPullRequest(pullRequest: PullRequestShape): SearchedPullRequestWithRemote | undefined {
return this._pullRequests?.find(r => r.pullRequest.id === pullRequest.id);
}
private async getRemoteBranch(searchedPullRequest: SearchedPullRequestWithRemote) {
const pullRequest = searchedPullRequest.pullRequest;
const repoAndRemote = searchedPullRequest.repoAndRemote;
const localUri = repoAndRemote.repo.uri;
const repo = await repoAndRemote.repo.getCommonRepository();
if (repo == null) {
void window.showWarningMessage(
`Unable to find main repository(${localUri.toString()}) for PR #${pullRequest.id}`,
);
return;
}
const rootOwner = pullRequest.refs!.base.owner;
const rootUri = Uri.parse(pullRequest.refs!.base.url);
const ref = pullRequest.refs!.head.branch;
const remoteUri = Uri.parse(pullRequest.refs!.head.url);
const remoteUrl = remoteUri.toString();
const [, remoteDomain, remotePath] = parseGitRemoteUrl(remoteUrl);
let remote: GitRemote | undefined;
[remote] = await repo.getRemotes({ filter: r => r.matches(remoteDomain, remotePath) });
let remoteBranchName;
if (remote != null) {
remoteBranchName = `${remote.name}/${ref}`;
// Ensure we have the latest from the remote
await this.container.git.fetch(repo.path, { remote: remote.name });
} else {
const result = await window.showInformationMessage(
`Unable to find a remote for '${remoteUrl}'. Would you like to add a new remote?`,
{ modal: true },
{ title: 'Add Remote' },
{ title: 'Cancel', isCloseAffordance: true },
);
if (result?.title !== 'Yes') return;
const remoteOwner = pullRequest.refs!.head.owner;
await addRemote(repo, remoteOwner, remoteUrl, {
confirm: false,
fetch: true,
reveal: false,
});
[remote] = await repo.getRemotes({ filter: r => r.url === remoteUrl });
if (remote == null) return;
remoteBranchName = `${remote.name}/${ref}`;
const rootRepository = pullRequest.refs!.base.repo;
const localBranchName = `pr/${rootUri.toString() === remoteUri.toString() ? ref : remoteBranchName}`;
// Save the PR number in the branch config
// path_to_url#L18
void this.container.git.setConfig(
repo.path,
`branch.${localBranchName}.github-pr-owner-number`,
`${rootOwner}#${rootRepository}#${pullRequest.id}`,
);
}
const reference = createReference(remoteBranchName, repo.path, {
refType: 'branch',
name: remoteBranchName,
remote: true,
});
return {
remote: remote,
reference: reference,
};
}
@debug({ args: false })
private async onOpenBranch({ pullRequest }: OpenBranchParams) {
const prWithRemote = this.findSearchedPullRequest(pullRequest);
if (prWithRemote == null) return;
const remoteBranch = await this.getRemoteBranch(prWithRemote);
if (remoteBranch == null) {
void window.showErrorMessage(
`Unable to find remote branch for '${prWithRemote.pullRequest.refs?.head.owner}:${prWithRemote.pullRequest.refs?.head.branch}'`,
);
return;
}
void executeCommand<ShowInCommitGraphCommandArgs>(Commands.ShowInCommitGraph, { ref: remoteBranch.reference });
}
@debug({ args: false })
private async onSwitchBranch({ pullRequest }: SwitchToBranchParams) {
const prWithRemote = this.findSearchedPullRequest(pullRequest);
if (prWithRemote == null || prWithRemote.isCurrentBranch) return;
if (prWithRemote.branch != null) {
return RepoActions.switchTo(prWithRemote.branch.repoPath, prWithRemote.branch);
}
const remoteBranch = await this.getRemoteBranch(prWithRemote);
if (remoteBranch == null) {
void window.showErrorMessage(
`Unable to find remote branch for '${prWithRemote.pullRequest.refs?.head.owner}:${prWithRemote.pullRequest.refs?.head.branch}'`,
);
return;
}
return RepoActions.switchTo(remoteBranch.remote.repoPath, remoteBranch.reference);
}
@debug({ args: false })
private async onOpenWorktree({ pullRequest }: OpenWorktreeParams) {
const searchedPullRequestWithRemote = this.findSearchedPullRequest(pullRequest);
if (searchedPullRequestWithRemote?.repoAndRemote == null) {
return;
}
const baseUri = Uri.parse(pullRequest.refs!.base.url);
const localUri = searchedPullRequestWithRemote.repoAndRemote.repo.uri;
return executeCommand<GHPRPullRequest>(Commands.OpenOrCreateWorktreeForGHPR, {
base: {
repositoryCloneUrl: {
repositoryName: pullRequest.refs!.base.repo,
owner: pullRequest.refs!.base.owner,
url: baseUri,
},
},
githubRepository: {
rootUri: localUri,
},
head: {
ref: pullRequest.refs!.head.branch,
sha: pullRequest.refs!.head.sha,
repositoryCloneUrl: {
repositoryName: pullRequest.refs!.head.repo,
owner: pullRequest.refs!.head.owner,
url: Uri.parse(pullRequest.refs!.head.url),
},
},
item: {
number: parseInt(pullRequest.id, 10),
},
});
}
private onSubscriptionChanged(e: SubscriptionChangeEvent) {
if (e.etag === this._etagSubscription) return;
this._etagSubscription = e.etag;
this._access = undefined;
void this.notifyDidChangeState();
}
private _access: FeatureAccess | RepoFeatureAccess | undefined;
@debug()
private async getAccess(force?: boolean) {
if (force || this._access == null) {
this._access = await this.container.git.access(PlusFeatures.Focus);
}
return this._access;
}
private enrichmentExpirationTimeout?: ReturnType<typeof setTimeout>;
private ensureEnrichmentExpirationCore(appliedEnrichments?: EnrichedItem[]) {
if (this.enrichmentExpirationTimeout != null) {
clearTimeout(this.enrichmentExpirationTimeout);
this.enrichmentExpirationTimeout = undefined;
}
if (appliedEnrichments == null || appliedEnrichments.length === 0) return;
const nowTime = Date.now();
let expirableEnrichmentTime: number | undefined;
for (const item of appliedEnrichments) {
if (item.expiresAt == null) continue;
const expiresAtTime = new Date(item.expiresAt).getTime();
if (
expirableEnrichmentTime == null ||
(expiresAtTime > nowTime && expiresAtTime < expirableEnrichmentTime)
) {
expirableEnrichmentTime = expiresAtTime;
}
}
if (expirableEnrichmentTime == null) return;
const debounceTime = expirableEnrichmentTime + 1000 * 60 * 15; // 15 minutes
// find the item in appliedEnrichments with largest expiresAtTime that is less than the debounce time + expirableEnrichmentTime
for (const item of appliedEnrichments) {
if (item.expiresAt == null) continue;
const expiresAtTime = new Date(item.expiresAt).getTime();
if (expiresAtTime > expirableEnrichmentTime && expiresAtTime < debounceTime) {
expirableEnrichmentTime = expiresAtTime;
}
}
const expiresTimeout = expirableEnrichmentTime - nowTime + 60000;
this.enrichmentExpirationTimeout = setTimeout(() => {
void this.notifyDidChangeState(true);
}, expiresTimeout);
}
@debug()
private async getState(force?: boolean, deferState?: boolean): Promise<State> {
const baseState = this.host.baseWebviewState;
this._etag = this.container.git.etag;
if (this.container.git.isDiscoveringRepositories) {
this._discovering = this.container.git.isDiscoveringRepositories.then(r => {
this._discovering = undefined;
return r;
});
this._etag = await this._discovering;
}
const access = await this.getAccess(force);
if (access.allowed !== true) {
return {
...baseState,
access: access,
};
}
const allRichRepos = await this.getRichRepos(force);
const githubRepos = filterGithubRepos(allRichRepos);
const connectedRepos = filterUsableRepos(githubRepos);
const hasConnectedRepos = connectedRepos.length > 0;
if (!hasConnectedRepos) {
return {
...baseState,
access: access,
repos: githubRepos.map(r => serializeRepoWithRichRemote(r)),
};
}
const repos = connectedRepos.map(r => serializeRepoWithRichRemote(r));
const statePromise = Promise.allSettled([
this.getMyPullRequests(connectedRepos, force),
this.getMyIssues(connectedRepos, force),
this.getEnrichedItems(force),
]);
const getStateCore = async () => {
const [prsResult, issuesResult, enrichedItems] = await statePromise;
const appliedEnrichments: EnrichedItem[] = [];
const pullRequests = getSettledValue(prsResult)?.map(pr => {
const itemEnrichments = findEnrichedItems(pr, getSettledValue(enrichedItems));
if (itemEnrichments != null) {
appliedEnrichments.push(...itemEnrichments);
}
return {
pullRequest: serializePullRequest(pr.pullRequest),
reasons: pr.reasons,
isCurrentBranch: pr.isCurrentBranch ?? false,
isCurrentWorktree: pr.isCurrentWorktree ?? false,
hasWorktree: pr.hasWorktree ?? false,
hasLocalBranch: pr.hasLocalBranch ?? false,
enriched: serializeEnrichedItems(itemEnrichments),
rank: pr.rank,
};
});
const issues = getSettledValue(issuesResult)?.map(issue => {
const itemEnrichments = findEnrichedItems(issue, getSettledValue(enrichedItems));
if (itemEnrichments != null) {
appliedEnrichments.push(...itemEnrichments);
}
return {
issue: serializeIssue(issue.issue),
reasons: issue.reasons,
enriched: serializeEnrichedItems(itemEnrichments),
rank: issue.rank,
};
});
this.ensureEnrichmentExpirationCore(appliedEnrichments);
return {
...baseState,
access: access,
repos: repos,
pullRequests: pullRequests,
issues: issues,
};
};
if (deferState) {
queueMicrotask(async () => {
const state = await getStateCore();
void this.host.notify(DidChangeNotification, { state: state });
});
return {
...baseState,
access: access,
repos: repos,
};
}
const state = await getStateCore();
return state;
}
async includeBootstrap(): Promise<State> {
return this.getState(true, true);
}
@debug()
private async getRichRepos(force?: boolean): Promise<RepoWithRichRemote[]> {
if (force || this._repos == null) {
const repos = [];
const disposables = [];
for (const repo of this.container.git.openRepositories) {
const remoteWithIntegration = await repo.getBestRemoteWithIntegration({ includeDisconnected: true });
if (
remoteWithIntegration == null ||
repos.findIndex(repo => repo.remote === remoteWithIntegration) > -1
) {
continue;
}
disposables.push(repo.onDidChange(this.onRepositoryChanged, this));
const integration = await this.container.integrations.getByRemote(remoteWithIntegration);
repos.push({
repo: repo,
remote: remoteWithIntegration,
isConnected: integration?.maybeConnected ?? (await integration?.isConnected()) ?? false,
isGitHub: remoteWithIntegration.provider.id === 'github',
});
}
if (this._repositoryEventsDisposable) {
this._repositoryEventsDisposable.dispose();
this._repositoryEventsDisposable = undefined;
}
this._repositoryEventsDisposable = Disposable.from(...disposables);
this._repos = repos;
}
return this._repos;
}
private onRepositoryChanged(e: RepositoryChangeEvent) {
if (e.changed(RepositoryChange.RemoteProviders, RepositoryChangeComparisonMode.Any)) {
void this.notifyDidChangeState(true);
}
}
@debug({ args: { 0: false } })
private async getMyPullRequests(
richRepos: RepoWithRichRemote[],
force?: boolean,
): Promise<SearchedPullRequestWithRemote[]> {
const scope = getLogScope();
if (force || this._pullRequests == null) {
const allPrs: SearchedPullRequestWithRemote[] = [];
const branchesByRepo = new Map<Repository, PageableResult<GitBranch>>();
const worktreesByRepo = new Map<Repository, GitWorktree[]>();
const queries = richRepos.map(
r => [r, this.container.integrations.getMyPullRequestsForRemotes(r.remote)] as const,
);
for (const [r, query] of queries) {
let prs;
try {
prs = await query;
} catch (ex) {
Logger.error(ex, scope, `Failed to get prs for '${r.remote.url}'`);
}
if (prs?.error != null) {
Logger.error(prs.error, scope, `Failed to get prs for '${r.remote.url}'`);
continue;
}
if (prs?.value == null) continue;
for (const pr of prs.value) {
if (pr.reasons.length === 0) continue;
const entry: SearchedPullRequestWithRemote = {
...pr,
repoAndRemote: r,
isCurrentWorktree: false,
isCurrentBranch: false,
rank: getPrRank(pr),
};
const remoteBranchName = `${entry.pullRequest.refs!.head.owner}/${
entry.pullRequest.refs!.head.branch
}`; // TODO@eamodio really need to check for upstream url rather than name
let branches = branchesByRepo.get(entry.repoAndRemote.repo);
if (branches == null) {
branches = new PageableResult<GitBranch>(paging =>
entry.repoAndRemote.repo.getBranches(paging != null ? { paging: paging } : undefined),
);
branchesByRepo.set(entry.repoAndRemote.repo, branches);
}
let worktrees = worktreesByRepo.get(entry.repoAndRemote.repo);
if (worktrees == null) {
worktrees = await entry.repoAndRemote.repo.getWorktrees();
worktreesByRepo.set(entry.repoAndRemote.repo, worktrees);
}
const worktree = await getWorktreeForBranch(
entry.repoAndRemote.repo,
entry.pullRequest.refs!.head.branch,
remoteBranchName,
worktrees,
branches,
);
entry.hasWorktree = worktree != null;
entry.isCurrentWorktree = worktree?.opened === true;
const branch = await getLocalBranchByUpstream(r.repo, remoteBranchName, branches);
if (branch) {
entry.branch = branch;
entry.hasLocalBranch = true;
entry.isCurrentBranch = branch.current;
}
allPrs.push(entry);
}
}
this._pullRequests = allPrs.sort((a, b) => {
const scoreA = a.rank;
const scoreB = b.rank;
if (scoreA === scoreB) {
return a.pullRequest.updatedDate.getTime() - b.pullRequest.updatedDate.getTime();
}
return (scoreB ?? 0) - (scoreA ?? 0);
});
}
return this._pullRequests;
}
@debug({ args: { 0: false } })
private async getMyIssues(richRepos: RepoWithRichRemote[], force?: boolean): Promise<SearchedIssueWithRank[]> {
const scope = getLogScope();
if (force || this._pullRequests == null) {
const allIssues = [];
const queries = richRepos.map(
r => [r, this.container.integrations.getMyIssuesForRemotes(r.remote)] as const,
);
for (const [r, query] of queries) {
let issues;
try {
issues = await query;
} catch (ex) {
Logger.error(ex, scope, `Failed to get issues for '${r.remote.url}'`);
}
if (issues == null) continue;
for (const issue of issues) {
if (issue.reasons.length === 0) continue;
allIssues.push({
...issue,
repoAndRemote: r,
rank: 0, // getIssueRank(issue),
});
}
}
// this._issues = allIssues.sort((a, b) => {
// const scoreA = a.rank;
// const scoreB = b.rank;
// if (scoreA === scoreB) {
// return b.issue.updatedDate.getTime() - a.issue.updatedDate.getTime();
// }
// return (scoreB ?? 0) - (scoreA ?? 0);
// });
this._issues = allIssues.sort((a, b) => b.issue.updatedDate.getTime() - a.issue.updatedDate.getTime());
}
return this._issues;
}
@debug()
private async getEnrichedItems(force?: boolean): Promise<EnrichedItem[] | undefined> {
// TODO needs cache invalidation
if (force || this._enrichedItems == null) {
const enrichedItems = await this.container.enrichments.get();
this._enrichedItems = enrichedItems;
}
return this._enrichedItems;
}
private async notifyDidChangeState(force?: boolean, deferState?: boolean) {
void this.host.notify(DidChangeNotification, { state: await this.getState(force, deferState) });
}
}
function findEnrichedItems(
item: SearchedPullRequestWithRemote | SearchedIssueWithRank,
enrichedItems?: EnrichedItem[],
) {
if (enrichedItems == null || enrichedItems.length === 0) {
item.enriched = undefined;
return;
}
let result;
// TODO: filter by entity id, type, and gitRepositoryId
if ((item as SearchedPullRequestWithRemote).pullRequest != null) {
result = enrichedItems.filter(e => e.entityUrl === (item as SearchedPullRequestWithRemote).pullRequest.url);
} else {
result = enrichedItems.filter(e => e.entityUrl === (item as SearchedIssueWithRank).issue.url);
}
if (result.length === 0) return;
item.enriched = result;
return result;
}
function serializeEnrichedItems(enrichedItems: EnrichedItem[] | undefined) {
if (enrichedItems == null || enrichedItems.length === 0) return;
return enrichedItems.map(enrichedItem => {
return {
id: enrichedItem.id,
type: enrichedItem.type,
expiresAt: enrichedItem.expiresAt,
};
});
}
function getPrRank(pr: SearchedPullRequest) {
let score = 0;
if (pr.reasons.includes('authored')) {
score += 1000;
} else if (pr.reasons.includes('assigned')) {
score += 900;
} else if (pr.reasons.includes('review-requested')) {
score += 800;
} else if (pr.reasons.includes('mentioned')) {
score += 700;
}
if (pr.pullRequest.reviewDecision === PullRequestReviewDecision.Approved) {
if (pr.pullRequest.mergeableState === PullRequestMergeableState.Mergeable) {
score += 100;
} else if (pr.pullRequest.mergeableState === PullRequestMergeableState.Conflicting) {
score += 90;
} else {
score += 80;
}
} else if (pr.pullRequest.reviewDecision === PullRequestReviewDecision.ChangesRequested) {
score += 70;
}
return score;
}
// function getIssueRank(issue: SearchedIssue) {
// let score = 0;
// if (issue.reasons.includes('authored')) {
// score += 1000;
// } else if (issue.reasons.includes('assigned')) {
// score += 900;
// } else if (issue.reasons.includes('mentioned')) {
// score += 700;
// }
// return score;
// }
function filterGithubRepos(list: RepoWithRichRemote[]): RepoWithRichRemote[] {
return list.filter(entry => entry.isGitHub);
}
function filterUsableRepos(list: RepoWithRichRemote[]): RepoWithRichRemote[] {
return list.filter(entry => entry.isConnected && entry.isGitHub);
}
function serializeRepoWithRichRemote(entry: RepoWithRichRemote) {
return {
repo: entry.repo.path,
isGitHub: entry.isGitHub,
isConnected: entry.isConnected,
};
}
``` | /content/code_sandbox/src/plus/webviews/focus/focusWebview.ts | xml | 2016-08-08T14:50:30 | 2024-08-15T21:25:09 | vscode-gitlens | gitkraken/vscode-gitlens | 8,889 | 7,332 |
```xml
<?xml version='1.0' encoding="utf-8"?>
<charsets>
<copyright>
Use is subject to license terms
This program is free software; you can redistribute it and/or modify
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
</copyright>
<charset name="koi8u">
<ctype>
<map>
00
20 20 20 20 20 20 20 20 20 28 28 28 28 28 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
48 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
84 84 84 84 84 84 84 84 84 84 10 10 10 10 10 10
10 81 81 81 81 81 81 01 01 01 01 01 01 01 01 01
01 01 01 01 01 01 01 01 01 01 01 10 10 10 10 10
10 82 82 82 82 82 82 02 02 02 02 02 02 02 02 02
02 02 02 02 02 02 02 02 02 02 02 10 10 10 10 20
10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
10 10 10 02 02 10 02 02 10 10 10 10 10 02 10 10
10 10 10 01 01 10 01 01 10 10 10 10 10 01 10 10
02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02
02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
</map>
</ctype>
<lower>
<map>
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F
30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F
40 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F
70 71 72 73 74 75 76 77 78 79 7A 5B 5C 5D 5E 5F
20 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F
70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 A3 A4 20 A6 A7 20 20 20 20 20 AD 20 20
20 20 20 A3 A4 20 A6 A7 20 20 20 20 20 AD 20 20
C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF
D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF
C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF
D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF
</map>
</lower>
<upper>
<map>
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F
30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F
40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F
20 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
50 51 52 53 54 55 56 57 58 59 5A 7B 7C 7D 7E 7F
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
20 20 20 B3 B4 20 B6 B7 20 20 20 20 20 BD 20 20
20 20 20 B3 B4 20 B6 B7 20 20 20 20 20 BD 20 20
E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF
F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF
E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF
F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF
</map>
</upper>
<unicode>
<map>
0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 000A 000B 000C 000D 000E 000F
0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 001A 001B 001C 001D 001E 001F
0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 002A 002B 002C 002D 002E 002F
0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 003A 003B 003C 003D 003E 003F
0040 0041 0042 0043 0044 0045 0046 0047 0048 0049 004A 004B 004C 004D 004E 004F
0050 0051 0052 0053 0054 0055 0056 0057 0058 0059 005A 005B 005C 005D 005E 005F
0060 0061 0062 0063 0064 0065 0066 0067 0068 0069 006A 006B 006C 006D 006E 006F
0070 0071 0072 0073 0074 0075 0076 0077 0078 0079 007A 007B 007C 007D 007E 007F
2500 2502 250C 2510 2514 2518 251C 2524 252C 2534 253C 2580 2584 2588 258C 2590
2591 2592 2593 2320 25A0 2022 221A 2248 2264 2265 00A0 2321 00B0 00B2 00B7 00F7
2550 2551 2552 0451 0454 2554 0456 0457 2557 2558 2559 255A 255B 0491 255D 255E
255F 2560 2561 0401 0404 2563 0406 0407 2566 2567 2568 2569 256A 0490 256C 00A9
044E 0430 0431 0446 0434 0435 0444 0433 0445 0438 0439 043A 043B 043C 043D 043E
043F 044F 0440 0441 0442 0443 0436 0432 044C 044B 0437 0448 044D 0449 0447 044A
042E 0410 0411 0426 0414 0415 0424 0413 0425 0418 0419 041A 041B 041C 041D 041E
041F 042F 0420 0421 0422 0423 0416 0412 042C 042B 0417 0428 042D 0429 0427 042A
</map>
</unicode>
<collation name="koi8u_general_ci">
<map>
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F
30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F
40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F
20 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
50 51 52 53 54 55 56 57 58 59 5A 7B 7C 7D 7E 7F
A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 B2 B3 B4
B5 B6 B7 B8 B9 BA BB BC BD BE BF C0 C1 C2 C3 C4
C5 C6 C7 88 87 C8 8C 8D C9 CA CB CC CD 84 CE CF
D0 D1 D2 88 87 D3 8C 8D D4 D5 D6 D7 D8 84 D9 DA
A3 80 81 9B 85 86 99 83 9A 8B 8E 8F 90 91 92 93
94 A4 95 96 97 98 89 82 A1 A0 8A 9D A2 9E 9C 9F
A3 80 81 9B 85 86 99 83 9A 8B 8E 8F 90 91 92 93
94 A4 95 96 97 98 89 82 A1 A0 8A 9D A2 9E 9C 9F
</map>
</collation>
<collation name="koi8u_bin" flag="binary"/>
</charset>
</charsets>
``` | /content/code_sandbox/sql/share/charsets/koi8u.xml | xml | 2016-07-27T08:05:00 | 2024-08-13T18:56:19 | AliSQL | alibaba/AliSQL | 4,695 | 4,240 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="pl_PL">
<context>
<name>AbstractAlert</name>
<message>
<source>Close</source>
<translation>Zamknij</translation>
</message>
<message>
<source>Snooze Update</source>
<translation>Zaktualizuj pniej</translation>
</message>
<message>
<source>Reboot and Update</source>
<translation>Uruchom ponownie i zaktualizuj</translation>
</message>
</context>
<context>
<name>AdvancedNetworking</name>
<message>
<source>Back</source>
<translation>Wr</translation>
</message>
<message>
<source>Enable Tethering</source>
<translation>Wcz hotspot osobisty</translation>
</message>
<message>
<source>Tethering Password</source>
<translation>Haso do hotspotu</translation>
</message>
<message>
<source>EDIT</source>
<translation>EDYTUJ</translation>
</message>
<message>
<source>Enter new tethering password</source>
<translation>Wprowad nowe haso do hotspotu</translation>
</message>
<message>
<source>IP Address</source>
<translation>Adres IP</translation>
</message>
<message>
<source>Enable Roaming</source>
<translation>Wcz roaming danych</translation>
</message>
<message>
<source>APN Setting</source>
<translation>Ustawienia APN</translation>
</message>
<message>
<source>Enter APN</source>
<translation>Wprowad APN</translation>
</message>
<message>
<source>leave blank for automatic configuration</source>
<translation>Pozostaw puste, aby uy domylnej konfiguracji</translation>
</message>
<message>
<source>Cellular Metered</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Prevent large data uploads when on a metered connection</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>AnnotatedCameraWidget</name>
<message>
<source>km/h</source>
<translation>km/h</translation>
</message>
<message>
<source>mph</source>
<translation>mph</translation>
</message>
<message>
<source>MAX</source>
<translation>MAX</translation>
</message>
<message>
<source>SPEED</source>
<translation>PRDKO</translation>
</message>
<message>
<source>LIMIT</source>
<translation>OGRANICZENIE</translation>
</message>
</context>
<context>
<name>ConfirmationDialog</name>
<message>
<source>Ok</source>
<translation>Ok</translation>
</message>
<message>
<source>Cancel</source>
<translation>Anuluj</translation>
</message>
</context>
<context>
<name>DeclinePage</name>
<message>
<source>You must accept the Terms and Conditions in order to use openpilot.</source>
<translation>Aby korzysta z openpilota musisz zaakceptowa regulamin.</translation>
</message>
<message>
<source>Back</source>
<translation>Wr</translation>
</message>
<message>
<source>Decline, uninstall %1</source>
<translation>Odrzu, odinstaluj %1</translation>
</message>
</context>
<context>
<name>DevicePanel</name>
<message>
<source>Dongle ID</source>
<translation>ID adaptera</translation>
</message>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>Serial</source>
<translation>Numer seryjny</translation>
</message>
<message>
<source>Driver Camera</source>
<translation>Kamera kierowcy</translation>
</message>
<message>
<source>PREVIEW</source>
<translation>PODGLD</translation>
</message>
<message>
<source>Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)</source>
<translation>Wywietl podgld z kamery skierowanej na kierowc, aby upewni si, e monitoring kierowcy ma dobry zakres widzenia. (pojazd musi by wyczony)</translation>
</message>
<message>
<source>Reset Calibration</source>
<translation>Zresetuj kalibracj</translation>
</message>
<message>
<source>RESET</source>
<translation>ZRESETUJ</translation>
</message>
<message>
<source>Are you sure you want to reset calibration?</source>
<translation>Czy na pewno chcesz zresetowa kalibracj?</translation>
</message>
<message>
<source>Review Training Guide</source>
<translation>Zapoznaj si z samouczkiem</translation>
</message>
<message>
<source>REVIEW</source>
<translation>ZAPOZNAJ SI</translation>
</message>
<message>
<source>Review the rules, features, and limitations of openpilot</source>
<translation>Zapoznaj si z zasadami, funkcjami i ograniczeniami openpilota</translation>
</message>
<message>
<source>Are you sure you want to review the training guide?</source>
<translation>Czy na pewno chcesz si zapozna z samouczkiem?</translation>
</message>
<message>
<source>Regulatory</source>
<translation>Regulacja</translation>
</message>
<message>
<source>VIEW</source>
<translation>WIDOK</translation>
</message>
<message>
<source>Change Language</source>
<translation>Zmie jzyk</translation>
</message>
<message>
<source>CHANGE</source>
<translation>ZMIE</translation>
</message>
<message>
<source>Select a language</source>
<translation>Wybierz jzyk</translation>
</message>
<message>
<source>Reboot</source>
<translation>Uruchom ponownie</translation>
</message>
<message>
<source>Power Off</source>
<translation>Wycz</translation>
</message>
<message>
<source>openpilot requires the device to be mounted within 4 left or right and within 5 up or 8 down. openpilot is continuously calibrating, resetting is rarely required.</source>
<translation>openpilot wymaga, aby urzdzenie byo zamontowane z maksymalnym odchyem 4 poziomo, 5 w gr oraz 8 w d. openpilot jest cigle kalibrowany, rzadko konieczne jest resetowania urzdzenia.</translation>
</message>
<message>
<source> Your device is pointed %1 %2 and %3 %4.</source>
<translation> Twoje urzdzenie jest skierowane %1 %2 oraz %3 %4.</translation>
</message>
<message>
<source>down</source>
<translation>w d</translation>
</message>
<message>
<source>up</source>
<translation>w gr</translation>
</message>
<message>
<source>left</source>
<translation>w lewo</translation>
</message>
<message>
<source>right</source>
<translation>w prawo</translation>
</message>
<message>
<source>Are you sure you want to reboot?</source>
<translation>Czy na pewno chcesz uruchomi ponownie urzdzenie?</translation>
</message>
<message>
<source>Disengage to Reboot</source>
<translation>Aby uruchomi ponownie, odcz sterowanie</translation>
</message>
<message>
<source>Are you sure you want to power off?</source>
<translation>Czy na pewno chcesz wyczy urzdzenie?</translation>
</message>
<message>
<source>Disengage to Power Off</source>
<translation>Aby wyczy urzdzenie, odcz sterowanie</translation>
</message>
</context>
<context>
<name>DriveStats</name>
<message>
<source>Drives</source>
<translation>Przejazdy</translation>
</message>
<message>
<source>Hours</source>
<translation>Godziny</translation>
</message>
<message>
<source>ALL TIME</source>
<translation>CAKOWICIE</translation>
</message>
<message>
<source>PAST WEEK</source>
<translation>OSTATNI TYDZIE</translation>
</message>
<message>
<source>KM</source>
<translation>KM</translation>
</message>
<message>
<source>Miles</source>
<translation>Mile</translation>
</message>
</context>
<context>
<name>DriverViewScene</name>
<message>
<source>camera starting</source>
<translation>uruchamianie kamery</translation>
</message>
</context>
<context>
<name>InputDialog</name>
<message>
<source>Cancel</source>
<translation>Anuluj</translation>
</message>
<message numerus="yes">
<source>Need at least %n character(s)!</source>
<translation>
<numerusform>Wpisana warto powinna skada si przynajmniej z %n znaku!</numerusform>
<numerusform>Wpisana warto powinna skda si przynajmniej z %n znakw!</numerusform>
<numerusform>Wpisana warto powinna skda si przynajmniej z %n znakw!</numerusform>
</translation>
</message>
</context>
<context>
<name>Installer</name>
<message>
<source>Installing...</source>
<translation>Instalowanie...</translation>
</message>
<message>
<source>Receiving objects: </source>
<translation>Odbieranie obiektw: </translation>
</message>
<message>
<source>Resolving deltas: </source>
<translation>Rozwizywanie rnic: </translation>
</message>
<message>
<source>Updating files: </source>
<translation>Aktualizacja plikw: </translation>
</message>
</context>
<context>
<name>MapETA</name>
<message>
<source>eta</source>
<translation>przewidywany czas</translation>
</message>
<message>
<source>min</source>
<translation>min</translation>
</message>
<message>
<source>hr</source>
<translation>godz</translation>
</message>
<message>
<source>km</source>
<translation>km</translation>
</message>
<message>
<source>mi</source>
<translation>mi</translation>
</message>
</context>
<context>
<name>MapInstructions</name>
<message>
<source> km</source>
<translation> km</translation>
</message>
<message>
<source> m</source>
<translation> m</translation>
</message>
<message>
<source> mi</source>
<translation> mi</translation>
</message>
<message>
<source> ft</source>
<translation> ft</translation>
</message>
</context>
<context>
<name>MapPanel</name>
<message>
<source>Current Destination</source>
<translation>Miejsce docelowe</translation>
</message>
<message>
<source>CLEAR</source>
<translation>WYCZY</translation>
</message>
<message>
<source>Recent Destinations</source>
<translation>Ostatnie miejsca docelowe</translation>
</message>
<message>
<source>Try the Navigation Beta</source>
<translation>Wyprbuj nawigacj w wersji beta</translation>
</message>
<message>
<source>Get turn-by-turn directions displayed and more with a comma
prime subscription. Sign up now: path_to_url
<translation>Odblokuj nawigacj zakrt po zakcie i wiele wicej subskrybujc
comma prime. Zarejestruj si teraz: path_to_url
</message>
<message>
<source>No home
location set</source>
<translation>Lokalizacja domu
nie zostaa ustawiona</translation>
</message>
<message>
<source>No work
location set</source>
<translation>Miejsce pracy
nie zostao ustawione</translation>
</message>
<message>
<source>no recent destinations</source>
<translation>brak ostatnich miejsc docelowych</translation>
</message>
</context>
<context>
<name>MapWindow</name>
<message>
<source>Map Loading</source>
<translation>adowanie Mapy</translation>
</message>
<message>
<source>Waiting for GPS</source>
<translation>Oczekiwanie na sygna GPS</translation>
</message>
</context>
<context>
<name>MultiOptionDialog</name>
<message>
<source>Select</source>
<translation>Wybierz</translation>
</message>
<message>
<source>Cancel</source>
<translation>Anuluj</translation>
</message>
</context>
<context>
<name>Networking</name>
<message>
<source>Advanced</source>
<translation>Zaawansowane</translation>
</message>
<message>
<source>Enter password</source>
<translation>Wprowad haso</translation>
</message>
<message>
<source>for "%1"</source>
<translation>do "%1"</translation>
</message>
<message>
<source>Wrong password</source>
<translation>Niepoprawne haso</translation>
</message>
</context>
<context>
<name>OffroadHome</name>
<message>
<source>UPDATE</source>
<translation>UAKTUALNIJ</translation>
</message>
<message>
<source> ALERTS</source>
<translation> ALERTY</translation>
</message>
<message>
<source> ALERT</source>
<translation> ALERT</translation>
</message>
</context>
<context>
<name>PairingPopup</name>
<message>
<source>Pair your device to your comma account</source>
<translation>Sparuj swoje urzadzenie ze swoim kontem comma</translation>
</message>
<message>
<source>Go to path_to_url on your phone</source>
<translation>Wejd na stron path_to_url na swoim telefonie</translation>
</message>
<message>
<source>Click "add new device" and scan the QR code on the right</source>
<translation>Kliknij "add new device" i zeskanuj kod QR znajdujcy si po prawej stronie</translation>
</message>
<message>
<source>Bookmark connect.comma.ai to your home screen to use it like an app</source>
<translation>Dodaj connect.comma.ai do zakadek na swoim ekranie pocztkowym, aby korzysta z niej jak z aplikacji</translation>
</message>
</context>
<context>
<name>PrimeAdWidget</name>
<message>
<source>Upgrade Now</source>
<translation>Uaktualnij teraz</translation>
</message>
<message>
<source>Become a comma prime member at connect.comma.ai</source>
<translation>Zosta czonkiem comma prime na connect.comma.ai</translation>
</message>
<message>
<source>PRIME FEATURES:</source>
<translation>FUNKCJE PRIME:</translation>
</message>
<message>
<source>Remote access</source>
<translation>Zdalny dostp</translation>
</message>
<message>
<source>1 year of storage</source>
<translation>1 rok przechowywania danych</translation>
</message>
<message>
<source>Developer perks</source>
<translation>Udogodnienia dla programistw</translation>
</message>
</context>
<context>
<name>PrimeUserWidget</name>
<message>
<source> SUBSCRIBED</source>
<translation> ZASUBSKRYBOWANO</translation>
</message>
<message>
<source>comma prime</source>
<translation>comma prime</translation>
</message>
<message>
<source>CONNECT.COMMA.AI</source>
<translation>CONNECT.COMMA.AI</translation>
</message>
<message>
<source>COMMA POINTS</source>
<translation>COMMA POINTS</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Reboot</source>
<translation>Uruchom Ponownie</translation>
</message>
<message>
<source>Exit</source>
<translation>Wyjd</translation>
</message>
<message>
<source>dashcam</source>
<translation>wideorejestrator</translation>
</message>
<message>
<source>openpilot</source>
<translation>openpilot</translation>
</message>
<message numerus="yes">
<source>%n minute(s) ago</source>
<translation>
<numerusform>%n minut temu</numerusform>
<numerusform>%n minuty temu</numerusform>
<numerusform>%n minut temu</numerusform>
</translation>
</message>
<message numerus="yes">
<source>%n hour(s) ago</source>
<translation>
<numerusform>% godzin temu</numerusform>
<numerusform>%n godziny temu</numerusform>
<numerusform>%n godzin temu</numerusform>
</translation>
</message>
<message numerus="yes">
<source>%n day(s) ago</source>
<translation>
<numerusform>%n dzie temu</numerusform>
<numerusform>%n dni temu</numerusform>
<numerusform>%n dni temu</numerusform>
</translation>
</message>
</context>
<context>
<name>Reset</name>
<message>
<source>Reset failed. Reboot to try again.</source>
<translation>Wymazywanie zakoczone niepowodzeniem. Aby sprbowa ponownie, uruchom ponownie urzdzenie.</translation>
</message>
<message>
<source>Are you sure you want to reset your device?</source>
<translation>Czy na pewno chcesz wymaza urzdzenie?</translation>
</message>
<message>
<source>Resetting device...</source>
<translation>Wymazywanie urzdzenia...</translation>
</message>
<message>
<source>System Reset</source>
<translation>Przywr do ustawie fabrycznych</translation>
</message>
<message>
<source>System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot.</source>
<translation>Przywracanie do ustawie fabrycznych. Wcinij potwierd, aby usun wszystkie dane oraz ustawienia. Wcinij anuluj, aby wznowi uruchamianie.</translation>
</message>
<message>
<source>Cancel</source>
<translation>Anuluj</translation>
</message>
<message>
<source>Reboot</source>
<translation>Uruchom ponownie</translation>
</message>
<message>
<source>Confirm</source>
<translation>Potwied</translation>
</message>
<message>
<source>Unable to mount data partition. Press confirm to reset your device.</source>
<translation>Partycja nie zostaa zamontowana poprawnie. Wcinij potwierd, aby uruchomi ponownie urzdzenie.</translation>
</message>
</context>
<context>
<name>RichTextDialog</name>
<message>
<source>Ok</source>
<translation>Ok</translation>
</message>
</context>
<context>
<name>SettingsWindow</name>
<message>
<source></source>
<translation>x</translation>
</message>
<message>
<source>Device</source>
<translation>Urzdzenie</translation>
</message>
<message>
<source>Network</source>
<translation>Sie</translation>
</message>
<message>
<source>Toggles</source>
<translation>Przeczniki</translation>
</message>
<message>
<source>Software</source>
<translation>Oprogramowanie</translation>
</message>
<message>
<source>Navigation</source>
<translation>Nawigacja</translation>
</message>
</context>
<context>
<name>Setup</name>
<message>
<source>WARNING: Low Voltage</source>
<translation>OSTRZEENIE: Niskie Napicie</translation>
</message>
<message>
<source>Power your device in a car with a harness or proceed at your own risk.</source>
<translation>Podcz swoje urzdzenie do zasilania poprzez podczenienie go do pojazdu lub kontynuuj na wasn odpowiedzialno.</translation>
</message>
<message>
<source>Power off</source>
<translation>Wycz</translation>
</message>
<message>
<source>Continue</source>
<translation>Kontynuuj</translation>
</message>
<message>
<source>Getting Started</source>
<translation>Zacznij</translation>
</message>
<message>
<source>Before we get on the road, lets finish installation and cover some details.</source>
<translation>Zanim ruszysz w drog, dokocz instalacj i podaj kilka szczegw.</translation>
</message>
<message>
<source>Connect to Wi-Fi</source>
<translation>Pocz z Wi-Fi</translation>
</message>
<message>
<source>Back</source>
<translation>Wr</translation>
</message>
<message>
<source>Continue without Wi-Fi</source>
<translation>Kontynuuj bez poczenia z Wif-Fi</translation>
</message>
<message>
<source>Waiting for internet</source>
<translation>Oczekiwanie na poczenie sieciowe</translation>
</message>
<message>
<source>Choose Software to Install</source>
<translation>Wybierz oprogramowanie do instalacji</translation>
</message>
<message>
<source>Dashcam</source>
<translation>Wideorejestrator</translation>
</message>
<message>
<source>Custom Software</source>
<translation>Wasne oprogramowanie</translation>
</message>
<message>
<source>Enter URL</source>
<translation>Wprowad adres URL</translation>
</message>
<message>
<source>for Custom Software</source>
<translation>do wasnego oprogramowania</translation>
</message>
<message>
<source>Downloading...</source>
<translation>Pobieranie...</translation>
</message>
<message>
<source>Download Failed</source>
<translation>Pobieranie nie powiodo si</translation>
</message>
<message>
<source>Ensure the entered URL is valid, and the devices internet connection is good.</source>
<translation>Upewnij si, e wpisany adres URL jest poprawny, a poczenie internetowe dziaa poprawnie.</translation>
</message>
<message>
<source>Reboot device</source>
<translation>Uruchom ponownie</translation>
</message>
<message>
<source>Start over</source>
<translation>Zacznij od pocztku</translation>
</message>
</context>
<context>
<name>SetupWidget</name>
<message>
<source>Finish Setup</source>
<translation>Zakocz konfiguracj</translation>
</message>
<message>
<source>Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.</source>
<translation>Sparuj swoje urzdzenie z comma connect (connect.comma.ai) i wybierz swoj ofert comma prime.</translation>
</message>
<message>
<source>Pair device</source>
<translation>Sparuj urzdzenie</translation>
</message>
</context>
<context>
<name>Sidebar</name>
<message>
<source>CONNECT</source>
<translation>POCZENIE</translation>
</message>
<message>
<source>OFFLINE</source>
<translation>OFFLINE</translation>
</message>
<message>
<source>ONLINE</source>
<translation>ONLINE</translation>
</message>
<message>
<source>ERROR</source>
<translation>BD</translation>
</message>
<message>
<source>TEMP</source>
<translation>TEMP</translation>
</message>
<message>
<source>HIGH</source>
<translation>WYSOKA</translation>
</message>
<message>
<source>GOOD</source>
<translation>DOBRA</translation>
</message>
<message>
<source>OK</source>
<translation>OK</translation>
</message>
<message>
<source>VEHICLE</source>
<translation>POJAZD</translation>
</message>
<message>
<source>NO</source>
<translation>BRAK</translation>
</message>
<message>
<source>PANDA</source>
<translation>PANDA</translation>
</message>
<message>
<source>GPS</source>
<translation>GPS</translation>
</message>
<message>
<source>SEARCH</source>
<translation>SZUKAJ</translation>
</message>
<message>
<source>--</source>
<translation>--</translation>
</message>
<message>
<source>Wi-Fi</source>
<translation>Wi-FI</translation>
</message>
<message>
<source>ETH</source>
<translation>ETH</translation>
</message>
<message>
<source>2G</source>
<translation>2G</translation>
</message>
<message>
<source>3G</source>
<translation>3G</translation>
</message>
<message>
<source>LTE</source>
<translation>LTE</translation>
</message>
<message>
<source>5G</source>
<translation>5G</translation>
</message>
</context>
<context>
<name>SoftwarePanel</name>
<message>
<source>Git Branch</source>
<translation type="vanished">Ga Git</translation>
</message>
<message>
<source>Git Commit</source>
<translation type="vanished">Git commit</translation>
</message>
<message>
<source>OS Version</source>
<translation type="vanished">Wersja systemu</translation>
</message>
<message>
<source>Version</source>
<translation type="vanished">Wersja</translation>
</message>
<message>
<source>Last Update Check</source>
<translation type="vanished">Ostatnie sprawdzenie aktualizacji</translation>
</message>
<message>
<source>The last time openpilot successfully checked for an update. The updater only runs while the car is off.</source>
<translation type="vanished">Ostatni raz kiedy openpilot znalaz aktualizacj. Aktualizator moe by uruchomiony wycznie wtedy, kiedy pojazd jest wyczony.</translation>
</message>
<message>
<source>Check for Update</source>
<translation type="vanished">Sprawd uaktualnienia</translation>
</message>
<message>
<source>CHECKING</source>
<translation type="vanished">SPRAWDZANIE</translation>
</message>
<message>
<source>Switch Branch</source>
<translation type="vanished">Zmie g</translation>
</message>
<message>
<source>ENTER</source>
<translation type="vanished">WPROWAD</translation>
</message>
<message>
<source>The new branch will be pulled the next time the updater runs.</source>
<translation type="vanished">Nowa ga bdzie pobrana przy nastpnym uruchomieniu aktualizatora.</translation>
</message>
<message>
<source>Enter branch name</source>
<translation type="vanished">Wprowad nazw gazi</translation>
</message>
<message>
<source>Uninstall %1</source>
<translation>Odinstaluj %1</translation>
</message>
<message>
<source>UNINSTALL</source>
<translation>ODINSTALUJ</translation>
</message>
<message>
<source>Are you sure you want to uninstall?</source>
<translation>Czy na pewno chcesz odinstalowa?</translation>
</message>
<message>
<source>failed to fetch update</source>
<translation type="vanished">pobieranie aktualizacji zakoczone niepowodzeniem</translation>
</message>
<message>
<source>CHECK</source>
<translation>SPRAWD</translation>
</message>
<message>
<source>Updates are only downloaded while the car is off.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Current Version</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Download</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Install Update</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>INSTALL</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Target Branch</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>SELECT</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select a branch</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SshControl</name>
<message>
<source>SSH Keys</source>
<translation>Klucze SSH</translation>
</message>
<message>
<source>Warning: This grants SSH access to all public keys in your GitHub settings. Never enter a GitHub username other than your own. A comma employee will NEVER ask you to add their GitHub username.</source>
<translation>Ostrzeenie: To spowoduje przekazanie dostpu do wszystkich Twoich publicznych kuczy z ustawie GitHuba. Nigdy nie wprowadzaj nazwy uytkownika innej ni swoja. Pracownik comma NIGDY nie poprosi o dodanie swojej nazwy uzytkownika.</translation>
</message>
<message>
<source>ADD</source>
<translation>DODAJ</translation>
</message>
<message>
<source>Enter your GitHub username</source>
<translation>Wpisz swoj nazw uytkownika GitHub</translation>
</message>
<message>
<source>LOADING</source>
<translation>ADOWANIE</translation>
</message>
<message>
<source>REMOVE</source>
<translation>USU</translation>
</message>
<message>
<source>Username '%1' has no keys on GitHub</source>
<translation>Uytkownik '%1' nie posiada adnych kluczy na GitHubie</translation>
</message>
<message>
<source>Request timed out</source>
<translation>Limit czasu rzdania</translation>
</message>
<message>
<source>Username '%1' doesn't exist on GitHub</source>
<translation>Uytkownik '%1' nie istnieje na GitHubie</translation>
</message>
</context>
<context>
<name>SshToggle</name>
<message>
<source>Enable SSH</source>
<translation>Wcz SSH</translation>
</message>
</context>
<context>
<name>TermsPage</name>
<message>
<source>Terms & Conditions</source>
<translation>Regulamin</translation>
</message>
<message>
<source>Decline</source>
<translation>Odrzu</translation>
</message>
<message>
<source>Scroll to accept</source>
<translation>Przewi w d, aby zaakceptowa</translation>
</message>
<message>
<source>Agree</source>
<translation>Zaakceptuj</translation>
</message>
</context>
<context>
<name>TogglesPanel</name>
<message>
<source>Enable openpilot</source>
<translation>Wcz openpilota</translation>
</message>
<message>
<source>Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off.</source>
<translation>Uyj openpilota do zachowania bezpiecznego odstpu midzy pojazdami i do asystowania w utrzymywaniu pasa ruchu. Twoja pena uwaga jest wymagana przez cay czas korzystania z tej funkcji. Ustawienie to moe by wdroone wycznie wtedy, gdy pojazd jest wyczony.</translation>
</message>
<message>
<source>Enable Lane Departure Warnings</source>
<translation>Wcz ostrzeganie przed zmian pasa ruchu</translation>
</message>
<message>
<source>Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h).</source>
<translation>Otrzymuj alerty o powrocie na waciwy pas, kiedy Twj pojazd przekroczy lini bez wczonego kierunkowskazu jadc powyej 50 km/h (31 mph).</translation>
</message>
<message>
<source>Use Metric System</source>
<translation>Korzystaj z systemu metrycznego</translation>
</message>
<message>
<source>Display speed in km/h instead of mph.</source>
<translation>Wywietl prdko w km/h zamiast mph.</translation>
</message>
<message>
<source>Record and Upload Driver Camera</source>
<translation>Nagraj i przelij nagranie z kamery kierowcy</translation>
</message>
<message>
<source>Upload data from the driver facing camera and help improve the driver monitoring algorithm.</source>
<translation>Przelij dane z kamery skierowanej na kierowc i pom poprawia algorytm monitorowania kierowcy.</translation>
</message>
<message>
<source>Disengage on Accelerator Pedal</source>
<translation>Odcz poprzez nacinicie gazu</translation>
</message>
<message>
<source>When enabled, pressing the accelerator pedal will disengage openpilot.</source>
<translation>Po wczeniu, nacinicie na peda gazu odczy openpilota.</translation>
</message>
<message>
<source>Show ETA in 24h Format</source>
<translation>Poka oczekiwany czas dojazdu w formacie 24-godzinnym</translation>
</message>
<message>
<source>Use 24h format instead of am/pm</source>
<translation>Korzystaj z formatu 24-godzinnego zamiast 12-godzinnego</translation>
</message>
<message>
<source>Show Map on Left Side of UI</source>
<translation>Poka map po lewej stronie ekranu</translation>
</message>
<message>
<source>Show map on left side when in split screen view.</source>
<translation>Poka map po lewej stronie kiedy ekran jest podzielony.</translation>
</message>
<message>
<source>openpilot Longitudinal Control</source>
<translation type="vanished">Kontrola wzduna openpilota</translation>
</message>
<message>
<source>openpilot will disable the car's radar and will take over control of gas and brakes. Warning: this disables AEB!</source>
<translation type="vanished">openpilot wyczy radar samochodu i przejmie kontrol nad gazem i hamulcem. Ostrzeenie: wyczony zostanie system AEB!</translation>
</message>
<message>
<source> End-to-end longitudinal (extremely alpha) </source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Experimental openpilot Longitudinal Control</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><b>WARNING: openpilot longitudinal control is experimental for this car and will disable AEB.</b></source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would. Super experimental.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>openpilot longitudinal control is not currently available for this car.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Enable experimental longitudinal control to enable this.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Updater</name>
<message>
<source>Update Required</source>
<translation>Wymagana Aktualizacja</translation>
</message>
<message>
<source>An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. The download size is approximately 1GB.</source>
<translation>Wymagana aktualizacja systemu operacyjnego. Aby przyspieszy proces aktualizacji pocz swoje urzedzenie do Wi-Fi. Rozmiar pobieranej paczki wynosi okoo 1GB.</translation>
</message>
<message>
<source>Connect to Wi-Fi</source>
<translation>Pocz si z Wi-Fi</translation>
</message>
<message>
<source>Install</source>
<translation>Zainstaluj</translation>
</message>
<message>
<source>Back</source>
<translation>Wr</translation>
</message>
<message>
<source>Loading...</source>
<translation>adowanie...</translation>
</message>
<message>
<source>Reboot</source>
<translation>Uruchom ponownie</translation>
</message>
<message>
<source>Update failed</source>
<translation>Aktualizacja nie powioda si</translation>
</message>
</context>
<context>
<name>WifiUI</name>
<message>
<source>Scanning for networks...</source>
<translation>Wyszukiwanie sieci...</translation>
</message>
<message>
<source>CONNECTING...</source>
<translation>CZENIE...</translation>
</message>
<message>
<source>FORGET</source>
<translation>ZAPOMNIJ</translation>
</message>
<message>
<source>Forget Wi-Fi Network "%1"?</source>
<translation>Czy chcesz zapomnie sie "%1"?</translation>
</message>
</context>
</TS>
``` | /content/code_sandbox/selfdrive/ui/translations/main_pl.ts | xml | 2016-11-24T01:33:30 | 2024-08-16T19:18:04 | openpilot | commaai/openpilot | 49,010 | 9,478 |
```xml
let x = [1, 1+1, 2];
``` | /content/code_sandbox/tests/decompile-test/cases/array_literal.ts | xml | 2016-01-24T19:35:52 | 2024-08-16T16:39:39 | pxt | microsoft/pxt | 2,069 | 15 |
```xml
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'angular-test'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('angular-test');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.content span')?.textContent).toContain('angular-test app is running!');
});
});
``` | /content/code_sandbox/examples/angular/src/app/app.component.spec.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 207 |
```xml
import * as React from 'react';
import { render } from '@testing-library/react';
import { ListContext, ResourceContextProvider } from 'ra-core';
import { TextInput } from '../../input';
import { Filter } from './Filter';
describe('<Filter />', () => {
describe('With form context', () => {
const defaultProps: any = {
context: 'form',
resource: 'posts',
setFilters: jest.fn(),
hideFilter: jest.fn(),
showFilter: jest.fn(),
displayedFilters: { title: true },
};
it('should render a <FilterForm /> component', () => {
const { queryByLabelText } = render(
<ResourceContextProvider value="posts">
<ListContext.Provider value={defaultProps}>
<Filter>
<TextInput source="title" />
</Filter>
</ListContext.Provider>
</ResourceContextProvider>
);
expect(queryByLabelText('Title')).not.toBeNull();
});
it('should pass `filterValues` as `initialValues` props', () => {
const { getByDisplayValue } = render(
<ResourceContextProvider value="posts">
<ListContext.Provider
value={{
...defaultProps,
filterValues: { title: 'Lorem' },
}}
>
<Filter>
<TextInput source="title" />
</Filter>
</ListContext.Provider>
</ResourceContextProvider>
);
expect(getByDisplayValue('Lorem')).not.toBeNull();
});
});
});
``` | /content/code_sandbox/packages/ra-ui-materialui/src/list/filter/Filter.spec.tsx | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 321 |
```xml
<!--
-->
<resources>
<string name="app_name">AppRuntimeFix</string>
</resources>
``` | /content/code_sandbox/appruntimefix/src/main/res/values/strings.xml | xml | 2016-05-25T11:58:00 | 2024-08-11T00:32:36 | RocooFix | dodola/RocooFix | 1,573 | 24 |
```xml
// Type definitions for ag-grid v6.2.1
// Project: path_to_url
// Definitions by: Niall Crosby <path_to_url
// Definitions: path_to_url
import { ColumnGroupChild } from "./columnGroupChild";
import { ColGroupDef } from "./colDef";
import { Column } from "./column";
import { AbstractColDef } from "./colDef";
import { OriginalColumnGroup } from "./originalColumnGroup";
export declare class ColumnGroup implements ColumnGroupChild {
static HEADER_GROUP_SHOW_OPEN: string;
static HEADER_GROUP_SHOW_CLOSED: string;
static EVENT_LEFT_CHANGED: string;
private children;
private displayedChildren;
private groupId;
private instanceId;
private originalColumnGroup;
private moving;
private left;
private eventService;
private parent;
constructor(originalColumnGroup: OriginalColumnGroup, groupId: string, instanceId: number);
getParent(): ColumnGroupChild;
setParent(parent: ColumnGroupChild): void;
getUniqueId(): string;
checkLeft(): void;
getLeft(): number;
setLeft(left: number): void;
addEventListener(eventType: string, listener: Function): void;
removeEventListener(eventType: string, listener: Function): void;
setMoving(moving: boolean): void;
isMoving(): boolean;
getGroupId(): string;
getInstanceId(): number;
isChildInThisGroupDeepSearch(wantedChild: ColumnGroupChild): boolean;
getActualWidth(): number;
getMinWidth(): number;
addChild(child: ColumnGroupChild): void;
getDisplayedChildren(): ColumnGroupChild[];
getLeafColumns(): Column[];
getDisplayedLeafColumns(): Column[];
getDefinition(): AbstractColDef;
getColGroupDef(): ColGroupDef;
isPadding(): boolean;
isExpandable(): boolean;
isExpanded(): boolean;
setExpanded(expanded: boolean): void;
private addDisplayedLeafColumns(leafColumns);
private addLeafColumns(leafColumns);
getChildren(): ColumnGroupChild[];
getColumnGroupShow(): string;
getOriginalColumnGroup(): OriginalColumnGroup;
calculateDisplayedColumns(): void;
}
``` | /content/code_sandbox/services/dashboard/assets-dev/js/vendor/ag-grid/dist/lib/entities/columnGroup.d.ts | xml | 2016-06-21T19:39:58 | 2024-08-12T19:23:26 | mylg | mehrdadrad/mylg | 2,691 | 457 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is part of some open source application.
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
path_to_url
Unless required by applicable law or agreed to in writing,
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
specific language governing permissions and limitations
Contact: Txus Ballesteros <txus.ballesteros@gmail.com>
-->
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorPrimaryDarkAlpha">#84303f9f</color>
<color name="colorAccent">#FF4081</color>
<color name="white">#ffffffff</color>
<color name="page1">#ff21B8AC</color>
<color name="page2">#ff218AB8</color>
<color name="page3">#ff21A5B8</color>
<color name="page4">#ff1F8B9B</color>
<color name="rocket">#e55555</color>
<color name="avatar1">#e1f4f8</color>
<color name="avatar2">#c6b9e7</color>
<color name="avatar3">#f8e71d</color>
<color name="avatar4">#65aa01</color>
<color name="avatar5">#4ee4c1</color>
</resources>
``` | /content/code_sandbox/app/src/main/res/values/colors.xml | xml | 2016-03-29T14:50:44 | 2024-07-10T06:28:10 | welcome-coordinator | txusballesteros/welcome-coordinator | 1,244 | 353 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--Default-->
<color name="colorPrimary">#FFFFFF</color>
<color name="colorPrimaryDark">#666666</color>
<color name="colorPrimaryDark_23">#e8e8e8</color>
<color name="colorAccent">#b2b2b2</color>
<!--Theme-->
<color name="themeColor_taki">#67B5E6</color>
<color name="theme_dark_color_taki">#70A3B4</color>
<color name="themeColor_mistuha">#EF7265</color>
<color name="theme_dark_color_mistuha">#b3371f</color>
<color name="themeColor_custom_default">#8BC34A</color>
<color name="theme_dark_color_custom_default">#388E3C</color>
<!--Button-->
<color name="button_boarder_color">#cccccc</color>
<color name="button_text_color">#b2b2b2</color>
<color name="button_text_color_p">#ffffff</color>
<color name="button_disable_color">#9D9FA2</color>
<!--ImageButton-->
<color name="imagebutton_hint_color">#b2b2b2</color>
<!--Main-->
<color name="topic_divider">#CACACA</color>
<!--Memo-->
<color name="memo_icon_tint">#718698</color>
<!--entries-->
<!--diary-->
<color name="diary_photo_layout_delete_bg">#003400</color>
<color name="diary_photo_layout_boarder">#e6e6e6</color>
<!--radio_button-->
<color name="radio_button_unselected_color">@android:color/transparent</color>
<!--My diary custom button-->
<color name="custom_button_disable_bg_color">#E1E2E3</color>
<!--dialog-->
<color name="edittext_hint">#d4d2d4</color>
<!--Edittext-->
<color name="edit_stroke">#CACACA</color>
<color name="edit_content_background">#ffffff</color>
<!--Textview-->
<color name="textview_shadow">#000000</color>
<color name="textview_hint">#d4d2d4</color>
<!--Contacts-->
<color name="contacts_photo_tint">#AFABAE</color>
<color name="contacts_latter_text">#f9f9f9</color>
<color name="contacts_latter_text_shadow">#949494</color>
<!--Setting-->
<color name="setting_hint_text_color">#828282</color>
<!--Backup-->
<color name="backup_hint_text_color">#828282</color>
<!--OOBE-->
<color name="OOBE_bg_color">#e570A3B4</color>
</resources>
``` | /content/code_sandbox/app/src/main/res/values/colors.xml | xml | 2016-11-04T02:04:13 | 2024-08-07T01:13:41 | MyDiary | DaxiaK/MyDiary | 1,580 | 636 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="path_to_url">
<gradient
android:angle="180"
android:centerColor="@android:color/transparent"
android:endColor="@color/colorPrimary"
android:startColor="@color/colorPrimary" />
</shape>
``` | /content/code_sandbox/feature/utilcode/pkg/src/main/res/drawable/bar_status_custom.xml | xml | 2016-07-30T18:18:32 | 2024-08-16T01:37:59 | AndroidUtilCode | Blankj/AndroidUtilCode | 33,178 | 69 |
```xml
import { addWeeks } from 'date-fns';
import { SelectedPlan } from '@proton/components/payments/core';
import { pick } from '@proton/shared/lib/helpers/object';
import {
getPlanFromIds,
getPlanNameFromIDs,
getPricingFromPlanIDs,
getTotalFromPricing,
} from '@proton/shared/lib/helpers/planIDs';
import type {
PlanIDs,
PlansMap,
Subscription,
SubscriptionCheckResponse,
SubscriptionPlan,
} from '@proton/shared/lib/interfaces';
import { BillingPlatform, ChargebeeEnabled, External, Renew } from '@proton/shared/lib/interfaces';
// that has to be a very granular import, because in general @proton/testing depends on jest while @proton/shared
// still uses Karma. The payments data specifically don't need jest, so it's safe to impoet it directly
import { PLANS_MAP, getSubscriptionMock, getUserMock } from '@proton/testing/data';
import { ADDON_NAMES, COUPON_CODES, CYCLE, PLANS } from '../../lib/constants';
import type { AggregatedPricing } from '../../lib/helpers/subscription';
import {
allCycles,
customCycles,
getNormalCycleFromCustomCycle,
getPlanIDs,
hasCancellablePlan,
hasLifetime,
hasSomeAddonOrPlan,
isManagedExternally,
isTrial,
isTrialExpired,
regularCycles,
willTrialExpire,
} from '../../lib/helpers/subscription';
let subscription: Subscription;
let defaultPlan: SubscriptionPlan;
beforeEach(() => {
subscription = {
ID: 'id-123',
InvoiceID: 'invoice-id-123',
Cycle: CYCLE.MONTHLY,
PeriodStart: 123,
PeriodEnd: 777,
CreateTime: 123,
CouponCode: null,
Currency: 'EUR',
Amount: 123,
RenewAmount: 123,
Discount: 123,
RenewDiscount: 123,
Plans: [],
External: External.Default,
Renew: Renew.Enabled,
};
defaultPlan = {
ID: 'plan-id-123',
Type: 0,
Cycle: CYCLE.MONTHLY,
Name: PLANS.BUNDLE,
Title: 'Bundle',
Currency: 'EUR',
Amount: 123,
MaxDomains: 123,
MaxAddresses: 123,
MaxSpace: 123,
MaxCalendars: 123,
MaxMembers: 123,
MaxVPN: 123,
MaxTier: 123,
Services: 123,
Features: 123,
Quantity: 123,
State: 123,
Offer: 'default',
};
});
describe('getPlanIDs', () => {
it('should extract plans properly', () => {
expect(
getPlanIDs({
...subscription,
Plans: [
{ ...defaultPlan, Name: PLANS.BUNDLE_PRO, Quantity: 1 },
{ ...defaultPlan, Name: PLANS.BUNDLE_PRO, Quantity: 1 },
{ ...defaultPlan, Name: ADDON_NAMES.MEMBER_BUNDLE_PRO, Quantity: 3 },
],
})
).toEqual({
[PLANS.BUNDLE_PRO]: 2,
[ADDON_NAMES.MEMBER_BUNDLE_PRO]: 3,
});
});
});
describe('hasLifetime', () => {
it('should have LIFETIME', () => {
subscription = {
...subscription,
CouponCode: COUPON_CODES.LIFETIME,
};
expect(hasLifetime(subscription)).toBe(true);
});
it('should not have LIFETIME', () => {
subscription = {
...subscription,
CouponCode: 'PANDA',
};
expect(hasLifetime(subscription)).toBe(false);
});
});
describe('isTrial', () => {
it('should be a trial - V4', () => {
expect(isTrial({ ...subscription, CouponCode: COUPON_CODES.REFERRAL })).toBe(true);
});
it('should not be a trial - V4', () => {
expect(isTrial({ ...subscription, CouponCode: 'PANDA' })).toBe(false);
});
it('should be a trial - V5', () => {
expect(isTrial({ ...subscription, IsTrial: true })).toBe(true);
expect(isTrial({ ...subscription, IsTrial: 1 as any })).toBe(true);
});
it('should not be a trial - V5', () => {
expect(isTrial({ ...subscription, IsTrial: false })).toBe(false);
expect(isTrial({ ...subscription, IsTrial: 0 as any })).toBe(false);
});
});
describe('isTrialExpired', () => {
it('should detect expired subscription', () => {
const ts = Math.round((new Date().getTime() - 1000) / 1000);
expect(isTrialExpired({ ...subscription, PeriodEnd: ts })).toBe(true);
});
it('should detect non-expired subscription', () => {
const ts = Math.round((new Date().getTime() + 1000) / 1000);
expect(isTrialExpired({ ...subscription, PeriodEnd: ts })).toBe(false);
});
});
describe('willTrialExpire', () => {
it('should detect close expiration', () => {
const ts = Math.round((addWeeks(new Date(), 1).getTime() - 1000) / 1000);
expect(willTrialExpire({ ...subscription, PeriodEnd: ts })).toBe(true);
});
it('should detect far expiration', () => {
// Add 2 weeks from now and convert Date to unix timestamp
const ts = Math.round(addWeeks(new Date(), 2).getTime() / 1000);
expect(willTrialExpire({ ...subscription, PeriodEnd: ts })).toBe(false);
});
});
describe('isManagedExternally', () => {
it('should return true if managed by Android', () => {
const result = isManagedExternally({
ID: 'id-123',
InvoiceID: 'invoice-id-123',
Cycle: CYCLE.MONTHLY,
PeriodStart: 123,
PeriodEnd: 777,
CreateTime: 123,
CouponCode: null,
Currency: 'CHF',
Amount: 1199,
RenewAmount: 1199,
Discount: 0,
Plans: [],
External: External.Android,
});
expect(result).toEqual(true);
});
it('should return true if managed by Apple', () => {
const result = isManagedExternally({
ID: 'id-123',
InvoiceID: 'invoice-id-123',
Cycle: CYCLE.MONTHLY,
PeriodStart: 123,
PeriodEnd: 777,
CreateTime: 123,
CouponCode: null,
Currency: 'CHF',
Amount: 1199,
RenewAmount: 1199,
Discount: 0,
Plans: [],
External: External.iOS,
});
expect(result).toEqual(true);
});
it('should return false if managed by us', () => {
const result = isManagedExternally({
ID: 'id-123',
InvoiceID: 'invoice-id-123',
Cycle: CYCLE.MONTHLY,
PeriodStart: 123,
PeriodEnd: 777,
CreateTime: 123,
CouponCode: null,
Currency: 'CHF',
Amount: 1199,
RenewAmount: 1199,
Discount: 0,
Plans: [],
External: External.Default,
});
expect(result).toEqual(false);
});
});
describe('getPricingFromPlanIDs', () => {
it('returns the correct pricing for a single plan ID', () => {
const planIDs: PlanIDs = { pass2023: 1 };
const plansMap: PlansMap = {
pass2023: {
ID: 'id123',
ParentMetaPlanID: '',
Type: 1,
Name: PLANS.PASS,
Title: 'Pass Plus',
MaxDomains: 0,
MaxAddresses: 0,
MaxCalendars: 0,
MaxSpace: 0,
MaxMembers: 0,
MaxVPN: 0,
MaxTier: 0,
Services: 8,
Features: 0,
State: 1,
Pricing: {
'1': 499,
'12': 1200,
'24': 7176,
},
PeriodEnd: {
'1': 1678452604,
'12': 1707569404,
'24': 1739191804,
},
Currency: 'CHF',
Quantity: 1,
Offers: [
{
Name: 'passlaunch',
StartTime: 1684758588,
EndTime: 1688110913,
Pricing: {
'12': 1200,
},
},
],
Cycle: 1,
Amount: 499,
},
};
const expected: AggregatedPricing = {
defaultMonthlyPrice: 499,
defaultMonthlyPriceWithoutAddons: 499,
all: {
'1': 499,
'3': 0,
'12': 1200,
'15': 0,
'18': 0,
'24': 7176,
'30': 0,
},
membersNumber: 1,
members: {
'1': 499,
'3': 0,
'12': 1200,
'15': 0,
'18': 0,
'24': 7176,
'30': 0,
},
plans: {
'1': 499,
'3': 0,
'12': 1200,
'15': 0,
'18': 0,
'24': 7176,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
it('should return correct pricing for Mail Pro: no addons', () => {
const planIDs: PlanIDs = {
[PLANS.MAIL_PRO]: 1,
};
const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.MAIL_PRO]);
const expected: AggregatedPricing = {
defaultMonthlyPrice: 799,
defaultMonthlyPriceWithoutAddons: 799,
all: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
membersNumber: 1,
members: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
plans: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
it('should return correct pricing for Mail Pro: with addons', () => {
const planIDs: PlanIDs = {
[PLANS.MAIL_PRO]: 1,
[ADDON_NAMES.MEMBER_MAIL_PRO]: 7,
};
const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.MAIL_PRO, ADDON_NAMES.MEMBER_MAIL_PRO]);
const expected: AggregatedPricing = {
defaultMonthlyPrice: 6392,
defaultMonthlyPriceWithoutAddons: 799,
all: {
'1': 6392,
'3': 0,
'12': 67104,
'15': 0,
'18': 0,
'24': 124608,
'30': 0,
},
membersNumber: 8,
members: {
'1': 6392,
'3': 0,
'12': 67104,
'15': 0,
'18': 0,
'24': 124608,
'30': 0,
},
plans: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
it('should return correct pricing for Bundle Pro: no addons', () => {
const planIDs: PlanIDs = {
[PLANS.BUNDLE_PRO]: 1,
};
const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.BUNDLE_PRO]);
const expected: AggregatedPricing = {
defaultMonthlyPrice: 1299,
defaultMonthlyPriceWithoutAddons: 1299,
all: {
'1': 1299,
'3': 0,
'12': 13188,
'15': 0,
'18': 0,
'24': 23976,
'30': 0,
},
membersNumber: 1,
members: {
'1': 1299,
'3': 0,
'12': 13188,
'15': 0,
'18': 0,
'24': 23976,
'30': 0,
},
plans: {
'1': 1299,
'3': 0,
'12': 13188,
'15': 0,
'18': 0,
'24': 23976,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
it('should return correct pricing for Bundle Pro: with addons', () => {
const planIDs: PlanIDs = {
[PLANS.BUNDLE_PRO]: 1,
[ADDON_NAMES.MEMBER_BUNDLE_PRO]: 7,
[ADDON_NAMES.DOMAIN_BUNDLE_PRO]: 9,
};
const plansMap: PlansMap = pick(PLANS_MAP, [
PLANS.BUNDLE_PRO,
ADDON_NAMES.MEMBER_BUNDLE_PRO,
ADDON_NAMES.DOMAIN_BUNDLE_PRO,
]);
const expected: AggregatedPricing = {
defaultMonthlyPrice: 11742,
defaultMonthlyPriceWithoutAddons: 1299,
all: {
'1': 11742,
'3': 0,
'12': 120624,
'15': 0,
'18': 0,
'24': 219888,
'30': 0,
},
membersNumber: 8,
members: {
'1': 10392,
'3': 0,
'12': 105504,
'15': 0,
'18': 0,
'24': 191808,
'30': 0,
},
plans: {
'1': 1299,
'3': 0,
'12': 13188,
'15': 0,
'18': 0,
'24': 23976,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
it('should return correct pricing for Family', () => {
const planIDs: PlanIDs = {
[PLANS.FAMILY]: 1,
};
const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.FAMILY]);
const expected: AggregatedPricing = {
defaultMonthlyPrice: 2999,
defaultMonthlyPriceWithoutAddons: 2999,
all: {
'1': 2999,
'3': 0,
'12': 28788,
'15': 0,
'18': 0,
'24': 47976,
'30': 0,
},
// Even though Family Plan does have up to 6 users, we still count as 1 member for price displaying
// purposes
membersNumber: 1,
members: {
'1': 2999,
'3': 0,
'12': 28788,
'15': 0,
'18': 0,
'24': 47976,
'30': 0,
},
plans: {
'1': 2999,
'3': 0,
'12': 28788,
'15': 0,
'18': 0,
'24': 47976,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
it('should return correct pricing for VPN Essentials: no addons', () => {
const planIDs: PlanIDs = {
[PLANS.VPN_PRO]: 1,
};
const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.VPN_PRO]);
const expected: AggregatedPricing = {
defaultMonthlyPrice: 1798,
defaultMonthlyPriceWithoutAddons: 1798,
all: {
'1': 1798,
'3': 0,
'12': 16776,
'15': 0,
'18': 0,
'24': 28752,
'30': 0,
},
membersNumber: 2,
members: {
'1': 1798,
'3': 0,
'12': 16776,
'15': 0,
'18': 0,
'24': 28752,
'30': 0,
},
plans: {
'1': 1798,
'3': 0,
'12': 16776,
'15': 0,
'18': 0,
'24': 28752,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
it('should return correct pricing for VPN Essentials: with addons', () => {
const planIDs: PlanIDs = {
// be default VPN Pro has 2 members, so overall there's 9 members for the price calculation purposes
[PLANS.VPN_PRO]: 1,
[ADDON_NAMES.MEMBER_VPN_PRO]: 7,
};
const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.VPN_PRO, ADDON_NAMES.MEMBER_VPN_PRO]);
const expected: AggregatedPricing = {
defaultMonthlyPrice: 8091,
defaultMonthlyPriceWithoutAddons: 1798,
all: {
'1': 8091,
'3': 0,
'12': 75492,
'15': 0,
'18': 0,
'24': 129384,
'30': 0,
},
membersNumber: 9,
members: {
'1': 8091,
'3': 0,
'12': 75492,
'15': 0,
'18': 0,
'24': 129384,
'30': 0,
},
plans: {
'1': 1798,
'3': 0,
'12': 16776,
'15': 0,
'18': 0,
'24': 28752,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
it('should return correct pricing for VPN Business: no addons', () => {
const planIDs: PlanIDs = {
[PLANS.VPN_BUSINESS]: 1,
};
const plansMap: PlansMap = pick(PLANS_MAP, [PLANS.VPN_BUSINESS]);
// VPN Business has 2 members and 1 IP by default.
// monthly: each user currently costs 11.99 and IP 49.99.
// yearly: (2*9.99 + 39.99) * 12
// 2 years: (2*8.99 + 35.99) * 24
const expected: AggregatedPricing = {
defaultMonthlyPrice: 7397,
defaultMonthlyPriceWithoutAddons: 7397,
all: {
'1': 7397,
'3': 0,
'12': 71964,
'15': 0,
'18': 0,
'24': 129528,
'30': 0,
},
membersNumber: 2,
members: {
'1': 2398,
'3': 0,
'12': 23976,
'15': 0,
'18': 0,
'24': 43152,
'30': 0,
},
plans: {
'1': 7397,
'3': 0,
'12': 71964,
'15': 0,
'18': 0,
'24': 129528,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
it('should return correct pricing for VPN Business: with addons', () => {
const planIDs: PlanIDs = {
[PLANS.VPN_BUSINESS]: 1,
[ADDON_NAMES.MEMBER_VPN_BUSINESS]: 7,
[ADDON_NAMES.IP_VPN_BUSINESS]: 3,
};
const plansMap: PlansMap = pick(PLANS_MAP, [
PLANS.VPN_BUSINESS,
ADDON_NAMES.MEMBER_VPN_BUSINESS,
ADDON_NAMES.IP_VPN_BUSINESS,
]);
// VPN Business has 2 members and 1 IP by default.
// monthly: each user currently costs 11.99 and IP 49.99.
// yearly: (2*9.99 + 39.99) * 12
// 2 years: (2*8.99 + 35.99) * 24
const expected: AggregatedPricing = {
defaultMonthlyPrice: 30787,
defaultMonthlyPriceWithoutAddons: 7397,
all: {
'1': 30787,
'3': 0,
'12': 299844,
'15': 0,
'18': 0,
'24': 539688,
'30': 0,
},
// Pricing for 9 members
membersNumber: 9,
members: {
'1': 10791,
'3': 0,
'12': 107892,
'15': 0,
'18': 0,
'24': 194184,
'30': 0,
},
plans: {
'1': 7397,
'3': 0,
'12': 71964,
'15': 0,
'18': 0,
'24': 129528,
'30': 0,
},
};
const result = getPricingFromPlanIDs(planIDs, plansMap);
expect(result).toEqual(expected);
});
});
describe('getTotalFromPricing', () => {
it('should calculate the prices correctly', () => {
const pricing: AggregatedPricing = {
defaultMonthlyPrice: 8596,
defaultMonthlyPriceWithoutAddons: 499,
all: {
'1': 8596,
'3': 0,
'12': 83952,
'15': 0,
'18': 0,
'24': 151104,
'30': 0,
},
members: {
'1': 3597,
'3': 0,
'12': 35964,
'15': 0,
'18': 0,
'24': 64728,
'30': 0,
},
membersNumber: 3,
plans: {
'1': 7397,
'3': 0,
'12': 71964,
'15': 0,
'18': 0,
'24': 129528,
'30': 0,
},
};
expect(getTotalFromPricing(pricing, 1)).toEqual({
discount: 0,
discountPercentage: 0,
discountedTotal: 8596,
totalPerMonth: 8596,
totalNoDiscountPerMonth: 8596,
perUserPerMonth: 1199,
viewPricePerMonth: 8596,
});
expect(getTotalFromPricing(pricing, 12)).toEqual({
discount: 19200,
discountPercentage: 19,
discountedTotal: 83952,
totalPerMonth: 6996,
totalNoDiscountPerMonth: 8596,
perUserPerMonth: 999,
viewPricePerMonth: 6996,
});
expect(getTotalFromPricing(pricing, 24)).toEqual({
discount: 55200,
discountPercentage: 27,
discountedTotal: 151104,
totalPerMonth: 6296,
totalNoDiscountPerMonth: 8596,
perUserPerMonth: 899,
viewPricePerMonth: 6296,
});
});
it('should calculate the prices correctly from a different monthly price', () => {
const pricing: AggregatedPricing = {
defaultMonthlyPrice: 999,
defaultMonthlyPriceWithoutAddons: 499,
all: {
'1': 899,
'3': 0,
'12': 7188,
'15': 14985,
'18': 0,
'24': 11976,
'30': 29970,
},
members: {
'1': 899,
'3': 0,
'12': 7188,
'15': 14985,
'18': 0,
'24': 11976,
'30': 29970,
},
plans: {
'1': 899,
'3': 0,
'12': 7188,
'15': 14985,
'18': 0,
'24': 11976,
'30': 29970,
},
membersNumber: 1,
};
expect(getTotalFromPricing(pricing, 1)).toEqual({
discount: 0,
discountPercentage: 0,
discountedTotal: 899,
totalPerMonth: 899,
totalNoDiscountPerMonth: 999,
perUserPerMonth: 899,
viewPricePerMonth: 899,
});
expect(getTotalFromPricing(pricing, 12)).toEqual({
discount: 4800,
discountPercentage: 40,
discountedTotal: 7188,
totalPerMonth: 599,
totalNoDiscountPerMonth: 999,
perUserPerMonth: 599,
viewPricePerMonth: 599,
});
expect(getTotalFromPricing(pricing, 24)).toEqual({
discount: 12000,
discountPercentage: 50,
discountedTotal: 11976,
totalPerMonth: 499,
totalNoDiscountPerMonth: 999,
perUserPerMonth: 499,
viewPricePerMonth: 499,
});
});
it('should calculate the prices correctly - Mail Essentials', () => {
const pricing: AggregatedPricing = {
defaultMonthlyPrice: 799,
defaultMonthlyPriceWithoutAddons: 799,
all: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
members: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
plans: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
membersNumber: 1,
};
const selectedPlan = new SelectedPlan({ [PLANS.MAIL_PRO]: 1 }, PLANS_MAP, CYCLE.YEARLY, 'USD');
expect(getTotalFromPricing(pricing, 12, 'all', [], selectedPlan)).toEqual({
discount: 1200,
discountedTotal: 8388,
perUserPerMonth: 699,
viewPricePerMonth: 699,
discountPercentage: 13,
totalPerMonth: 699,
totalNoDiscountPerMonth: 799,
});
});
it('should calculate the prices correctly - Mail Essentials with scribe', () => {
const pricing: AggregatedPricing = {
defaultMonthlyPrice: 1198,
defaultMonthlyPriceWithoutAddons: 799,
all: {
'1': 1198,
'3': 0,
'12': 11976,
'15': 0,
'18': 0,
'24': 22752,
'30': 0,
},
members: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
plans: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
membersNumber: 1,
};
const selectedPlan = new SelectedPlan(
{ [PLANS.MAIL_PRO]: 1, [ADDON_NAMES.MEMBER_SCRIBE_MAIL_PRO]: 1 },
PLANS_MAP,
CYCLE.YEARLY,
'USD'
);
expect(getTotalFromPricing(pricing, 12, 'all', [], selectedPlan)).toEqual({
discount: 2400,
discountedTotal: 11976,
perUserPerMonth: 699,
viewPricePerMonth: 699,
discountPercentage: 17,
totalPerMonth: 998,
totalNoDiscountPerMonth: 1198,
});
});
it('should calculate the prices correctly - Mail Essentials with discount', () => {
const pricing: AggregatedPricing = {
defaultMonthlyPrice: 799,
defaultMonthlyPriceWithoutAddons: 799,
all: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
members: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
plans: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
membersNumber: 1,
};
const selectedPlan = new SelectedPlan({ [PLANS.MAIL_PRO]: 1 }, PLANS_MAP, CYCLE.YEARLY, 'USD');
expect(
getTotalFromPricing(
pricing,
12,
'all',
[
{
Amount: 799,
Currency: 'USD',
AmountDue: 0,
Proration: 0,
CouponDiscount: -200,
Gift: 0,
Credit: -599,
UnusedCredit: 0,
Coupon: {
Code: 'ONETEST25',
Description: 'One-time 25% discount',
MaximumRedemptionsPerUser: 1,
},
Cycle: 1,
SubscriptionMode: 0,
TaxInclusive: 1,
Taxes: [
{
Name: 'Mehrwertsteuer (MWST)',
Rate: 8.1,
Amount: 45,
},
],
PeriodEnd: 0,
},
{
Amount: 8388,
Currency: 'USD',
AmountDue: 0,
Proration: 0,
CouponDiscount: -2097,
Gift: 0,
Credit: -6291,
UnusedCredit: 0,
Coupon: {
Code: 'ONETEST25',
Description: 'One-time 25% discount',
MaximumRedemptionsPerUser: 1,
},
Cycle: 12,
SubscriptionMode: 0,
TaxInclusive: 1,
Taxes: [
{
Name: 'Mehrwertsteuer (MWST)',
Rate: 8.1,
Amount: 471,
},
],
PeriodEnd: 0,
},
],
selectedPlan
)
).toEqual({
discount: 3297,
discountedTotal: 6291,
perUserPerMonth: 524.25,
viewPricePerMonth: 524.25,
discountPercentage: 34,
totalPerMonth: 524.25,
totalNoDiscountPerMonth: 799,
});
});
it('should calculate the prices correctly - Mail Essentials with discount and scribe', () => {
const pricing: AggregatedPricing = {
defaultMonthlyPrice: 1198,
defaultMonthlyPriceWithoutAddons: 799,
all: {
'1': 1198,
'3': 0,
'12': 11976,
'15': 0,
'18': 0,
'24': 22752,
'30': 0,
},
members: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
plans: {
'1': 799,
'3': 0,
'12': 8388,
'15': 0,
'18': 0,
'24': 15576,
'30': 0,
},
membersNumber: 1,
};
const cycle = CYCLE.YEARLY;
const mode = 'all';
const checkResults: SubscriptionCheckResponse[] = [
{
PeriodEnd: 0,
Amount: 1198,
Currency: 'USD',
AmountDue: 0,
Proration: 0,
CouponDiscount: -300,
Gift: 0,
Credit: -898,
UnusedCredit: 0,
Coupon: {
Code: 'ONETEST25',
Description: 'One-time 25% discount',
MaximumRedemptionsPerUser: 1,
},
Cycle: 1,
SubscriptionMode: 0,
TaxInclusive: 1,
Taxes: [
{
Name: 'Mehrwertsteuer (MWST)',
Rate: 8.1,
Amount: 67,
},
],
},
{
PeriodEnd: 0,
Amount: 11976,
Currency: 'USD',
AmountDue: 0,
Proration: 0,
CouponDiscount: -2994,
Gift: 0,
Credit: -8982,
UnusedCredit: 0,
Coupon: {
Code: 'ONETEST25',
Description: 'One-time 25% discount',
MaximumRedemptionsPerUser: 1,
},
Cycle: 12,
SubscriptionMode: 0,
TaxInclusive: 1,
Taxes: [
{
Name: 'Mehrwertsteuer (MWST)',
Rate: 8.1,
Amount: 673,
},
],
},
];
const selectedPlan = new SelectedPlan(
{ [PLANS.MAIL_PRO]: 1, [ADDON_NAMES.MEMBER_SCRIBE_MAIL_PRO]: 1 },
PLANS_MAP,
cycle,
'USD'
);
expect(getTotalFromPricing(pricing, 12, mode, checkResults, selectedPlan)).toEqual({
discount: 5394,
discountPercentage: 38,
discountedTotal: 8982,
totalPerMonth: 748.5,
totalNoDiscountPerMonth: 1198,
perUserPerMonth: 524.25,
viewPricePerMonth: 524.25,
});
});
});
describe('getPlanFromIds', () => {
it('should return the correct plan when it exists in planIDs', () => {
const planIDs: PlanIDs = {
[PLANS.BUNDLE_PRO]: 1,
};
const result = getPlanFromIds(planIDs);
expect(result).toEqual(PLANS.BUNDLE_PRO);
});
it('should return undefined when no plan exists in planIDs', () => {
const planIDs: PlanIDs = {};
const result = getPlanFromIds(planIDs);
expect(result).toBeUndefined();
});
it('should choose the plan instead of addons', () => {
const planIDs: PlanIDs = {
[ADDON_NAMES.MEMBER_BUNDLE_PRO]: 1,
[ADDON_NAMES.DOMAIN_BUNDLE_PRO]: 1,
[PLANS.BUNDLE_PRO]: 1,
};
const result = getPlanFromIds(planIDs);
expect(result).toEqual(PLANS.BUNDLE_PRO);
});
});
describe('getPlanNameFromIDs', () => {
it('should return the correct plan name', () => {
const planIDs: PlanIDs = {
[PLANS.VPN_PRO]: 1,
[ADDON_NAMES.MEMBER_VPN_PRO]: 12,
};
// these two checks are equivalent. I wanted to add them for expressiveness and readability
expect(getPlanNameFromIDs(planIDs)).toEqual('vpnpro2023' as any);
expect(getPlanNameFromIDs(planIDs)).toEqual(PLANS.VPN_PRO);
});
it('should return undefined if there are no plan IDs', () => {
expect(getPlanNameFromIDs({})).toBeUndefined();
});
});
describe('hasSomeAddOn', () => {
it('Should test a single add-on Name', () => {
subscription = {
...subscription,
Plans: [...subscription.Plans, { ...defaultPlan, Name: ADDON_NAMES.MEMBER_SCRIBE_MAILPLUS, Quantity: 1 }],
};
const result = hasSomeAddonOrPlan(subscription, ADDON_NAMES.MEMBER_SCRIBE_MAILPLUS);
expect(result).toEqual(true);
});
it('Should test a list of add-on Name', () => {
subscription = {
...subscription,
Plans: [...subscription.Plans, { ...defaultPlan, Name: ADDON_NAMES.MEMBER_SCRIBE_MAILPLUS, Quantity: 1 }],
};
const result = hasSomeAddonOrPlan(subscription, [
ADDON_NAMES.MEMBER_SCRIBE_MAILPLUS,
ADDON_NAMES.MEMBER_DRIVE_PRO,
]);
expect(result).toEqual(true);
});
it('Should test a list of add-on Name with no match', () => {
subscription = {
...subscription,
Plans: [...subscription.Plans, { ...defaultPlan, Name: ADDON_NAMES.MEMBER_SCRIBE_MAILPLUS, Quantity: 1 }],
};
const result = hasSomeAddonOrPlan(subscription, [ADDON_NAMES.MEMBER_DRIVE_PRO, ADDON_NAMES.MEMBER_VPN_PRO]);
expect(result).toEqual(false);
});
});
describe('cycles', () => {
it('should have all cycles', () => {
expect(allCycles).toEqual([
CYCLE.MONTHLY,
CYCLE.THREE,
CYCLE.YEARLY,
CYCLE.FIFTEEN,
CYCLE.EIGHTEEN,
CYCLE.TWO_YEARS,
CYCLE.THIRTY,
]);
});
it('should have regular cycles', () => {
expect(regularCycles).toEqual([CYCLE.MONTHLY, CYCLE.YEARLY, CYCLE.TWO_YEARS]);
});
it('should have custom cycles', () => {
expect(customCycles).toEqual([CYCLE.THREE, CYCLE.FIFTEEN, CYCLE.EIGHTEEN, CYCLE.THIRTY]);
});
it('should return normal cycle from custom cycle - undefined', () => {
expect(getNormalCycleFromCustomCycle(undefined)).toEqual(undefined);
});
it('should return normal cycle from custom cycle - monthly', () => {
expect(getNormalCycleFromCustomCycle(CYCLE.THREE)).toEqual(CYCLE.MONTHLY);
});
it('should return normal cycle from custom cycle - three', () => {
expect(getNormalCycleFromCustomCycle(CYCLE.THREE)).toEqual(CYCLE.MONTHLY);
});
it('should return normal cycle from custom cycle - yearly', () => {
expect(getNormalCycleFromCustomCycle(CYCLE.YEARLY)).toEqual(CYCLE.YEARLY);
});
it('should return normal cycle from custom cycle - fifteen', () => {
expect(getNormalCycleFromCustomCycle(CYCLE.FIFTEEN)).toEqual(CYCLE.YEARLY);
});
it('should return normal cycle from custom cycle - eighteen', () => {
expect(getNormalCycleFromCustomCycle(CYCLE.EIGHTEEN)).toEqual(CYCLE.YEARLY);
});
it('should return normal cycle from custom cycle - two years', () => {
expect(getNormalCycleFromCustomCycle(CYCLE.TWO_YEARS)).toEqual(CYCLE.TWO_YEARS);
});
it('should return normal cycle from custom cycle - thirty', () => {
expect(getNormalCycleFromCustomCycle(CYCLE.THIRTY)).toEqual(CYCLE.TWO_YEARS);
});
});
describe('hasCancellablePlan', () => {
it('should be cancellable with inhouse subscription', () => {
const testCases = [PLANS.PASS, PLANS.VPN, PLANS.VPN2024, PLANS.VPN_PASS_BUNDLE];
const subscription = getSubscriptionMock({ BillingPlatform: BillingPlatform.Proton });
const user = getUserMock({ ChargebeeUser: ChargebeeEnabled.INHOUSE_FORCED, ChargebeeUserExists: 0 });
testCases.forEach((plan) => {
subscription.Plans[0].Name = plan;
expect(hasCancellablePlan(subscription, user)).toEqual(true);
});
});
it('should not be cancellable with inhouse subscription', () => {
const testCases = [
PLANS.BUNDLE,
PLANS.BUNDLE_PRO,
PLANS.BUNDLE_PRO_2024,
PLANS.DRIVE,
PLANS.DRIVE_PRO,
PLANS.DUO,
PLANS.ENTERPRISE,
PLANS.FAMILY,
PLANS.FREE,
PLANS.MAIL,
PLANS.MAIL_BUSINESS,
PLANS.MAIL_PRO,
PLANS.PASS_BUSINESS,
PLANS.PASS_PRO,
PLANS.VISIONARY,
PLANS.VPN_BUSINESS,
PLANS.VPN_PRO,
PLANS.WALLET,
];
const subscription = getSubscriptionMock({ BillingPlatform: BillingPlatform.Proton });
const user = getUserMock({ ChargebeeUser: ChargebeeEnabled.INHOUSE_FORCED, ChargebeeUserExists: 0 });
testCases.forEach((plan) => {
subscription.Plans[0].Name = plan;
expect(hasCancellablePlan(subscription, user)).withContext(`plan: ${plan}`).toEqual(false);
});
});
it('should have cancellable plan if user is on-session migration eligible', () => {
const testCases = [PLANS.PASS, PLANS.VPN, PLANS.VPN2024, PLANS.VPN_PASS_BUNDLE];
const subscription = getSubscriptionMock({ BillingPlatform: BillingPlatform.Proton });
const user = getUserMock({ ChargebeeUser: ChargebeeEnabled.CHARGEBEE_FORCED, ChargebeeUserExists: 0 });
testCases.forEach((plan) => {
subscription.Plans[0].Name = plan;
expect(hasCancellablePlan(subscription, user)).withContext(`plan: ${plan}`).toEqual(true);
});
});
it('should not have cancellable plan if user is on-session migration eligible', () => {
const testCases = [
PLANS.BUNDLE,
PLANS.BUNDLE_PRO,
PLANS.BUNDLE_PRO_2024,
PLANS.DRIVE,
PLANS.DRIVE_PRO,
PLANS.DUO,
PLANS.ENTERPRISE,
PLANS.FAMILY,
PLANS.FREE,
PLANS.MAIL,
PLANS.MAIL_BUSINESS,
PLANS.MAIL_PRO,
PLANS.PASS_BUSINESS,
PLANS.PASS_PRO,
PLANS.VISIONARY,
PLANS.VPN_BUSINESS,
PLANS.VPN_PRO,
PLANS.WALLET,
];
const subscription = getSubscriptionMock({ BillingPlatform: BillingPlatform.Proton });
const user = getUserMock({ ChargebeeUser: ChargebeeEnabled.CHARGEBEE_FORCED, ChargebeeUserExists: 0 });
testCases.forEach((plan) => {
subscription.Plans[0].Name = plan;
expect(hasCancellablePlan(subscription, user)).withContext(`plan: ${plan}`).toEqual(false);
});
});
it('should have all plans cancellable if user is true chargebee user', () => {
const testCases = [
PLANS.PASS,
PLANS.VPN,
PLANS.VPN2024,
PLANS.VPN_PASS_BUNDLE,
// ---
PLANS.BUNDLE,
PLANS.BUNDLE_PRO,
PLANS.BUNDLE_PRO_2024,
PLANS.DRIVE,
PLANS.DRIVE_PRO,
PLANS.DUO,
PLANS.ENTERPRISE,
PLANS.FAMILY,
PLANS.FREE,
PLANS.MAIL,
PLANS.MAIL_BUSINESS,
PLANS.MAIL_PRO,
PLANS.PASS_BUSINESS,
PLANS.PASS_PRO,
PLANS.VISIONARY,
PLANS.VPN_BUSINESS,
PLANS.VPN_PRO,
PLANS.WALLET,
];
const subscription = getSubscriptionMock({ BillingPlatform: BillingPlatform.Chargebee });
const user = getUserMock({ ChargebeeUser: ChargebeeEnabled.CHARGEBEE_FORCED, ChargebeeUserExists: 1 });
testCases.forEach((plan) => {
subscription.Plans[0].Name = plan;
expect(hasCancellablePlan(subscription, user)).withContext(`plan: ${plan}`).toEqual(true);
});
});
it('should have all plans cancellable if user is splitted', () => {
const testCases = [
PLANS.PASS,
PLANS.VPN,
PLANS.VPN2024,
PLANS.VPN_PASS_BUNDLE,
// ---
PLANS.BUNDLE,
PLANS.BUNDLE_PRO,
PLANS.BUNDLE_PRO_2024,
PLANS.DRIVE,
PLANS.DRIVE_PRO,
PLANS.DUO,
PLANS.ENTERPRISE,
PLANS.FAMILY,
PLANS.FREE,
PLANS.MAIL,
PLANS.MAIL_BUSINESS,
PLANS.MAIL_PRO,
PLANS.PASS_BUSINESS,
PLANS.PASS_PRO,
PLANS.VISIONARY,
PLANS.VPN_BUSINESS,
PLANS.VPN_PRO,
PLANS.WALLET,
];
const subscription = getSubscriptionMock({ BillingPlatform: BillingPlatform.Proton });
const user = getUserMock({ ChargebeeUser: ChargebeeEnabled.CHARGEBEE_FORCED, ChargebeeUserExists: 1 });
testCases.forEach((plan) => {
subscription.Plans[0].Name = plan;
expect(hasCancellablePlan(subscription, user)).withContext(`plan: ${plan}`).toEqual(true);
});
});
});
``` | /content/code_sandbox/packages/shared/test/helpers/subscription.spec.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 10,722 |
```xml
import chai, { expect } from 'chai';
import { spy, stub } from 'sinon';
import sinonChai from 'sinon-chai';
import Choices from './choices';
import { EVENTS, ACTION_TYPES, KEY_CODES } from './constants';
import { WrappedSelect, WrappedInput } from './components/index';
import { removeItem } from './actions/items';
import templates from './templates';
import { Choice } from './interfaces/choice';
import { Group } from './interfaces/group';
import { Item } from './interfaces/item';
import { DEFAULT_CONFIG } from './defaults';
chai.use(sinonChai);
describe('choices', () => {
let instance;
let output;
let passedElement;
beforeEach(() => {
passedElement = document.createElement('input');
passedElement.type = 'text';
passedElement.className = 'js-choices';
document.body.appendChild(passedElement);
instance = new Choices(passedElement, { allowHTML: true });
});
afterEach(() => {
output = null;
instance = null;
});
describe('constructor', () => {
describe('config', () => {
describe('not passing config options', () => {
it('uses the default config', () => {
document.body.innerHTML = `
<input data-choice type="text" id="input-1" />
`;
instance = new Choices();
expect(instance.config).to.eql(DEFAULT_CONFIG);
});
});
describe('passing config options', () => {
it('merges the passed config with the default config', () => {
document.body.innerHTML = `
<input data-choice type="text" id="input-1" />
`;
const config = {
allowHTML: true,
renderChoiceLimit: 5,
};
instance = new Choices('[data-choice]', config);
expect(instance.config).to.eql({
...DEFAULT_CONFIG,
...config,
});
});
describe('passing the searchEnabled config option with a value of false', () => {
describe('passing a select-multiple element', () => {
it('sets searchEnabled to true', () => {
document.body.innerHTML = `
<select data-choice multiple></select>
`;
instance = new Choices('[data-choice]', {
allowHTML: true,
searchEnabled: false,
});
expect(instance.config.searchEnabled).to.equal(true);
});
});
});
describe('passing the renderSelectedChoices config option with an unexpected value', () => {
it('sets renderSelectedChoices to "auto"', () => {
document.body.innerHTML = `
<select data-choice multiple></select>
`;
instance = new Choices('[data-choice]', {
allowHTML: true,
renderSelectedChoices: 'test' as any,
});
expect(instance.config.renderSelectedChoices).to.equal('auto');
});
});
});
});
describe('not passing an element', () => {
it('returns a Choices instance for the first element with a "data-choice" attribute', () => {
document.body.innerHTML = `
<input data-choice type="text" id="input-1" />
<input data-choice type="text" id="input-2" />
<input data-choice type="text" id="input-3" />
`;
const inputs = document.querySelectorAll('[data-choice]');
expect(inputs.length).to.equal(3);
instance = new Choices(undefined, { allowHTML: true });
expect(instance.passedElement.element.id).to.equal(inputs[0].id);
});
describe('when an element cannot be found in the DOM', () => {
it('throws an error', () => {
document.body.innerHTML = ``;
expect(() => new Choices(undefined, { allowHTML: true })).to.throw(
TypeError,
'Expected one of the following types text|select-one|select-multiple',
);
});
});
});
describe('passing an element', () => {
describe('passing an element that has not been initialised with Choices', () => {
beforeEach(() => {
document.body.innerHTML = `
<input type="text" id="input-1" />
`;
});
it('sets the initialised flag to true', () => {
instance = new Choices('#input-1', { allowHTML: true });
expect(instance.initialised).to.equal(true);
});
it('intialises', () => {
const initSpy = spy();
// initialise with the same element
instance = new Choices('#input-1', {
allowHTML: true,
silent: true,
callbackOnInit: initSpy,
});
expect(initSpy.called).to.equal(true);
});
});
describe('passing an element that has already be initialised with Choices', () => {
beforeEach(() => {
document.body.innerHTML = `
<input type="text" id="input-1" />
`;
// initialise once
new Choices('#input-1', { allowHTML: true, silent: true });
});
it('sets the initialised flag to true', () => {
// initialise with the same element
instance = new Choices('#input-1', { allowHTML: true, silent: true });
expect(instance.initialised).to.equal(true);
});
it('does not reinitialise', () => {
const initSpy = spy();
// initialise with the same element
instance = new Choices('#input-1', {
allowHTML: true,
silent: true,
callbackOnInit: initSpy,
});
expect(initSpy.called).to.equal(false);
});
});
describe(`passing an element as a DOMString`, () => {
describe('passing a input element type', () => {
it('sets the "passedElement" instance property as an instance of WrappedInput', () => {
document.body.innerHTML = `
<input data-choice type="text" id="input-1" />
`;
instance = new Choices('[data-choice]', { allowHTML: true });
expect(instance.passedElement).to.be.an.instanceOf(WrappedInput);
});
});
describe('passing a select element type', () => {
it('sets the "passedElement" instance property as an instance of WrappedSelect', () => {
document.body.innerHTML = `
<select data-choice id="select-1"></select>
`;
instance = new Choices('[data-choice]', { allowHTML: true });
expect(instance.passedElement).to.be.an.instanceOf(WrappedSelect);
});
});
});
describe(`passing an element as a HTMLElement`, () => {
describe('passing a input element type', () => {
it('sets the "passedElement" instance property as an instance of WrappedInput', () => {
document.body.innerHTML = `
<input data-choice type="text" id="input-1" />
`;
instance = new Choices('[data-choice]', { allowHTML: true });
expect(instance.passedElement).to.be.an.instanceOf(WrappedInput);
});
});
describe('passing a select element type', () => {
it('sets the "passedElement" instance property as an instance of WrappedSelect', () => {
document.body.innerHTML = `
<select data-choice id="select-1"></select>
`;
instance = new Choices('[data-choice]', { allowHTML: true });
expect(instance.passedElement).to.be.an.instanceOf(WrappedSelect);
});
});
});
describe('passing an invalid element type', () => {
it('throws an TypeError', () => {
document.body.innerHTML = `
<div data-choice id="div-1"></div>
`;
expect(
() => new Choices('[data-choice]', { allowHTML: true }),
).to.throw(
TypeError,
'Expected one of the following types text|select-one|select-multiple',
);
});
});
});
});
describe('public methods', () => {
describe('init', () => {
const callbackOnInitSpy = spy();
beforeEach(() => {
instance = new Choices(passedElement, {
allowHTML: true,
callbackOnInit: callbackOnInitSpy,
silent: true,
});
});
describe('when already initialised', () => {
beforeEach(() => {
instance.initialised = true;
instance.init();
});
it("doesn't set initialise flag", () => {
expect(instance.initialised).to.not.equal(false);
});
});
describe('not already initialised', () => {
let createTemplatesSpy;
let createInputSpy;
let storeSubscribeSpy;
let renderSpy;
let addEventListenersSpy;
beforeEach(() => {
createTemplatesSpy = spy(instance, '_createTemplates');
createInputSpy = spy(instance, '_createStructure');
storeSubscribeSpy = spy(instance._store, 'subscribe');
renderSpy = spy(instance, '_render');
addEventListenersSpy = spy(instance, '_addEventListeners');
instance.initialised = false;
instance.init();
});
afterEach(() => {
createTemplatesSpy.restore();
createInputSpy.restore();
storeSubscribeSpy.restore();
renderSpy.restore();
addEventListenersSpy.restore();
});
it('sets initialise flag', () => {
expect(instance.initialised).to.equal(true);
});
it('creates templates', () => {
expect(createTemplatesSpy.called).to.equal(true);
});
it('creates input', () => {
expect(createInputSpy.called).to.equal(true);
});
it('subscribes to store with render method', () => {
expect(storeSubscribeSpy.called).to.equal(true);
expect(storeSubscribeSpy.lastCall.args[0]).to.equal(instance._render);
});
it('fires initial render', () => {
expect(renderSpy.called).to.equal(true);
});
it('adds event listeners', () => {
expect(addEventListenersSpy.called).to.equal(true);
});
it('fires callback', () => {
expect(callbackOnInitSpy.called).to.equal(true);
});
});
});
describe('destroy', () => {
beforeEach(() => {
passedElement = document.createElement('input');
passedElement.type = 'text';
passedElement.className = 'js-choices';
document.body.appendChild(passedElement);
instance = new Choices(passedElement, { allowHTML: true });
});
describe('not already initialised', () => {
beforeEach(() => {
instance.initialised = false;
instance.destroy();
});
it("doesn't set initialise flag", () => {
expect(instance.initialised).to.not.equal(true);
});
});
describe('when already initialised', () => {
let removeEventListenersSpy;
let passedElementRevealSpy;
let containerOuterUnwrapSpy;
let clearStoreSpy;
beforeEach(() => {
removeEventListenersSpy = spy(instance, '_removeEventListeners');
passedElementRevealSpy = spy(instance.passedElement, 'reveal');
containerOuterUnwrapSpy = spy(instance.containerOuter, 'unwrap');
clearStoreSpy = spy(instance, 'clearStore');
instance.initialised = true;
instance.destroy();
});
afterEach(() => {
removeEventListenersSpy.restore();
passedElementRevealSpy.restore();
containerOuterUnwrapSpy.restore();
clearStoreSpy.restore();
});
it('removes event listeners', () => {
expect(removeEventListenersSpy.called).to.equal(true);
});
it('reveals passed element', () => {
expect(passedElementRevealSpy.called).to.equal(true);
});
it('reverts outer container', () => {
expect(containerOuterUnwrapSpy.called).to.equal(true);
expect(containerOuterUnwrapSpy.lastCall.args[0]).to.equal(
instance.passedElement.element,
);
});
it('clears store', () => {
expect(clearStoreSpy.called).to.equal(true);
});
it('restes templates config', () => {
expect(instance._templates).to.deep.equal(templates);
});
it('resets initialise flag', () => {
expect(instance.initialised).to.equal(false);
});
});
});
describe('enable', () => {
let passedElementEnableSpy;
let addEventListenersSpy;
let containerOuterEnableSpy;
let inputEnableSpy;
beforeEach(() => {
addEventListenersSpy = spy(instance, '_addEventListeners');
passedElementEnableSpy = spy(instance.passedElement, 'enable');
containerOuterEnableSpy = spy(instance.containerOuter, 'enable');
inputEnableSpy = spy(instance.input, 'enable');
});
afterEach(() => {
addEventListenersSpy.restore();
passedElementEnableSpy.restore();
containerOuterEnableSpy.restore();
inputEnableSpy.restore();
});
describe('when already enabled', () => {
beforeEach(() => {
instance.passedElement.isDisabled = false;
instance.containerOuter.isDisabled = false;
output = instance.enable();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('returns early', () => {
expect(passedElementEnableSpy.called).to.equal(false);
expect(addEventListenersSpy.called).to.equal(false);
expect(inputEnableSpy.called).to.equal(false);
expect(containerOuterEnableSpy.called).to.equal(false);
});
});
describe('when not already enabled', () => {
beforeEach(() => {
instance.passedElement.isDisabled = true;
instance.containerOuter.isDisabled = true;
instance.enable();
});
it('adds event listeners', () => {
expect(addEventListenersSpy.called).to.equal(true);
});
it('enables input', () => {
expect(inputEnableSpy.called).to.equal(true);
});
it('enables containerOuter', () => {
expect(containerOuterEnableSpy.called).to.equal(true);
});
});
});
describe('disable', () => {
let removeEventListenersSpy;
let passedElementDisableSpy;
let containerOuterDisableSpy;
let inputDisableSpy;
beforeEach(() => {
removeEventListenersSpy = spy(instance, '_removeEventListeners');
passedElementDisableSpy = spy(instance.passedElement, 'disable');
containerOuterDisableSpy = spy(instance.containerOuter, 'disable');
inputDisableSpy = spy(instance.input, 'disable');
});
afterEach(() => {
removeEventListenersSpy.restore();
passedElementDisableSpy.restore();
containerOuterDisableSpy.restore();
inputDisableSpy.restore();
});
describe('when already disabled', () => {
beforeEach(() => {
instance.passedElement.isDisabled = true;
instance.containerOuter.isDisabled = true;
output = instance.disable();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('returns early', () => {
expect(removeEventListenersSpy.called).to.equal(false);
expect(passedElementDisableSpy.called).to.equal(false);
expect(containerOuterDisableSpy.called).to.equal(false);
expect(inputDisableSpy.called).to.equal(false);
});
});
describe('when not already disabled', () => {
beforeEach(() => {
instance.passedElement.isDisabled = false;
instance.containerOuter.isDisabled = false;
output = instance.disable();
});
it('removes event listeners', () => {
expect(removeEventListenersSpy.called).to.equal(true);
});
it('disables input', () => {
expect(inputDisableSpy.called).to.equal(true);
});
it('enables containerOuter', () => {
expect(containerOuterDisableSpy.called).to.equal(true);
});
});
});
describe('showDropdown', () => {
let containerOuterOpenSpy;
let dropdownShowSpy;
let inputFocusSpy;
let passedElementTriggerEventStub;
beforeEach(() => {
containerOuterOpenSpy = spy(instance.containerOuter, 'open');
dropdownShowSpy = spy(instance.dropdown, 'show');
inputFocusSpy = spy(instance.input, 'focus');
passedElementTriggerEventStub = stub();
instance.passedElement.triggerEvent = passedElementTriggerEventStub;
});
afterEach(() => {
containerOuterOpenSpy.restore();
dropdownShowSpy.restore();
inputFocusSpy.restore();
instance.passedElement.triggerEvent.reset();
});
describe('dropdown active', () => {
beforeEach(() => {
instance.dropdown.isActive = true;
output = instance.showDropdown();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('returns early', () => {
expect(containerOuterOpenSpy.called).to.equal(false);
expect(dropdownShowSpy.called).to.equal(false);
expect(inputFocusSpy.called).to.equal(false);
expect(passedElementTriggerEventStub.called).to.equal(false);
});
});
describe('dropdown inactive', () => {
beforeEach(() => {
instance.dropdown.isActive = false;
output = instance.showDropdown();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('opens containerOuter', (done) => {
requestAnimationFrame(() => {
expect(containerOuterOpenSpy.called).to.equal(true);
done();
});
});
it('shows dropdown with blurInput flag', (done) => {
requestAnimationFrame(() => {
expect(dropdownShowSpy.called).to.equal(true);
done();
});
});
it('triggers event on passedElement', (done) => {
requestAnimationFrame(() => {
expect(passedElementTriggerEventStub.called).to.equal(true);
expect(passedElementTriggerEventStub.lastCall.args[0]).to.eql(
EVENTS.showDropdown,
);
expect(passedElementTriggerEventStub.lastCall.args[1]).to.eql({});
done();
});
});
describe('passing true focusInput flag with canSearch set to true', () => {
beforeEach(() => {
instance.dropdown.isActive = false;
instance._canSearch = true;
output = instance.showDropdown(true);
});
it('focuses input', (done) => {
requestAnimationFrame(() => {
expect(inputFocusSpy.called).to.equal(true);
done();
});
});
});
});
});
describe('hideDropdown', () => {
let containerOuterCloseSpy;
let dropdownHideSpy;
let inputBlurSpy;
let inputRemoveActiveDescendantSpy;
let passedElementTriggerEventStub;
beforeEach(() => {
containerOuterCloseSpy = spy(instance.containerOuter, 'close');
dropdownHideSpy = spy(instance.dropdown, 'hide');
inputBlurSpy = spy(instance.input, 'blur');
inputRemoveActiveDescendantSpy = spy(
instance.input,
'removeActiveDescendant',
);
passedElementTriggerEventStub = stub();
instance.passedElement.triggerEvent = passedElementTriggerEventStub;
});
afterEach(() => {
containerOuterCloseSpy.restore();
dropdownHideSpy.restore();
inputBlurSpy.restore();
inputRemoveActiveDescendantSpy.restore();
instance.passedElement.triggerEvent.reset();
});
describe('dropdown inactive', () => {
beforeEach(() => {
instance.dropdown.isActive = false;
output = instance.hideDropdown();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('returns early', () => {
expect(containerOuterCloseSpy.called).to.equal(false);
expect(dropdownHideSpy.called).to.equal(false);
expect(inputBlurSpy.called).to.equal(false);
expect(passedElementTriggerEventStub.called).to.equal(false);
});
});
describe('dropdown active', () => {
beforeEach(() => {
instance.dropdown.isActive = true;
output = instance.hideDropdown();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('closes containerOuter', (done) => {
requestAnimationFrame(() => {
expect(containerOuterCloseSpy.called).to.equal(true);
done();
});
});
it('hides dropdown with blurInput flag', (done) => {
requestAnimationFrame(() => {
expect(dropdownHideSpy.called).to.equal(true);
done();
});
});
it('triggers event on passedElement', (done) => {
requestAnimationFrame(() => {
expect(passedElementTriggerEventStub.called).to.equal(true);
expect(passedElementTriggerEventStub.lastCall.args[0]).to.eql(
EVENTS.hideDropdown,
);
expect(passedElementTriggerEventStub.lastCall.args[1]).to.eql({});
done();
});
});
describe('passing true blurInput flag with canSearch set to true', () => {
beforeEach(() => {
instance.dropdown.isActive = true;
instance._canSearch = true;
output = instance.hideDropdown(true);
});
it('removes active descendants', (done) => {
requestAnimationFrame(() => {
expect(inputRemoveActiveDescendantSpy.called).to.equal(true);
done();
});
});
it('blurs input', (done) => {
requestAnimationFrame(() => {
expect(inputBlurSpy.called).to.equal(true);
done();
});
});
});
});
});
describe('highlightItem', () => {
let passedElementTriggerEventStub;
let storeDispatchSpy;
let storeGetGroupByIdStub;
const groupIdValue = 'Test';
beforeEach(() => {
passedElementTriggerEventStub = stub();
storeGetGroupByIdStub = stub().returns({
value: groupIdValue,
});
storeDispatchSpy = spy(instance._store, 'dispatch');
instance._store.getGroupById = storeGetGroupByIdStub;
instance.passedElement.triggerEvent = passedElementTriggerEventStub;
});
afterEach(() => {
storeDispatchSpy.restore();
instance._store.getGroupById.reset();
instance.passedElement.triggerEvent.reset();
});
describe('no item passed', () => {
beforeEach(() => {
output = instance.highlightItem();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('returns early', () => {
expect(passedElementTriggerEventStub.called).to.equal(false);
expect(storeDispatchSpy.called).to.equal(false);
expect(storeGetGroupByIdStub.called).to.equal(false);
});
});
describe('item passed', () => {
const item: Item = {
id: 1234,
value: 'Test',
label: 'Test',
};
describe('passing truthy second paremeter', () => {
beforeEach(() => {
output = instance.highlightItem(item, true);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('dispatches highlightItem action with correct arguments', () => {
expect(storeDispatchSpy.called).to.equal(true);
expect(storeDispatchSpy.lastCall.args[0]).to.eql({
type: ACTION_TYPES.HIGHLIGHT_ITEM,
id: item.id,
highlighted: true,
});
});
describe('item with negative groupId', () => {
beforeEach(() => {
item.groupId = -1;
output = instance.highlightItem(item);
});
it('triggers event with null groupValue', () => {
expect(passedElementTriggerEventStub.called).to.equal(true);
expect(passedElementTriggerEventStub.lastCall.args[0]).to.equal(
EVENTS.highlightItem,
);
expect(passedElementTriggerEventStub.lastCall.args[1]).to.eql({
id: item.id,
value: item.value,
label: item.label,
groupValue: null,
});
});
});
describe('item without groupId', () => {
beforeEach(() => {
item.groupId = 1;
output = instance.highlightItem(item);
});
it('triggers event with groupValue', () => {
expect(passedElementTriggerEventStub.called).to.equal(true);
expect(passedElementTriggerEventStub.lastCall.args[0]).to.equal(
EVENTS.highlightItem,
);
expect(passedElementTriggerEventStub.lastCall.args[1]).to.eql({
id: item.id,
value: item.value,
label: item.label,
groupValue: groupIdValue,
});
});
});
});
describe('passing falsey second paremeter', () => {
beforeEach(() => {
output = instance.highlightItem(item, false);
});
it("doesn't trigger event", () => {
expect(passedElementTriggerEventStub.called).to.equal(false);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
});
});
});
describe('unhighlightItem', () => {
let passedElementTriggerEventStub;
let storeDispatchSpy;
let storeGetGroupByIdStub;
const groupIdValue = 'Test';
beforeEach(() => {
passedElementTriggerEventStub = stub();
storeGetGroupByIdStub = stub().returns({
value: groupIdValue,
});
storeDispatchSpy = spy(instance._store, 'dispatch');
instance._store.getGroupById = storeGetGroupByIdStub;
instance.passedElement.triggerEvent = passedElementTriggerEventStub;
});
afterEach(() => {
storeDispatchSpy.restore();
instance._store.getGroupById.reset();
instance.passedElement.triggerEvent.reset();
});
describe('no item passed', () => {
beforeEach(() => {
output = instance.unhighlightItem();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('returns early', () => {
expect(passedElementTriggerEventStub.called).to.equal(false);
expect(storeDispatchSpy.called).to.equal(false);
expect(storeGetGroupByIdStub.called).to.equal(false);
});
});
describe('item passed', () => {
const item: Item = {
id: 1234,
value: 'Test',
label: 'Test',
};
describe('passing truthy second paremeter', () => {
beforeEach(() => {
output = instance.unhighlightItem(item, true);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('dispatches highlightItem action with correct arguments', () => {
expect(storeDispatchSpy.called).to.equal(true);
expect(storeDispatchSpy.lastCall.args[0]).to.eql({
type: ACTION_TYPES.HIGHLIGHT_ITEM,
id: item.id,
highlighted: false,
});
});
describe('item with negative groupId', () => {
beforeEach(() => {
item.groupId = -1;
output = instance.unhighlightItem(item);
});
it('triggers event with null groupValue', () => {
expect(passedElementTriggerEventStub.called).to.equal(true);
expect(passedElementTriggerEventStub.lastCall.args[0]).to.equal(
EVENTS.highlightItem,
);
expect(passedElementTriggerEventStub.lastCall.args[1]).to.eql({
id: item.id,
value: item.value,
label: item.label,
groupValue: null,
});
});
});
describe('item without groupId', () => {
beforeEach(() => {
item.groupId = 1;
output = instance.highlightItem(item);
});
it('triggers event with groupValue', () => {
expect(passedElementTriggerEventStub.called).to.equal(true);
expect(passedElementTriggerEventStub.lastCall.args[0]).to.equal(
EVENTS.highlightItem,
);
expect(passedElementTriggerEventStub.lastCall.args[1]).to.eql({
id: item.id,
value: item.value,
label: item.label,
groupValue: groupIdValue,
});
});
});
});
describe('passing falsey second paremeter', () => {
beforeEach(() => {
output = instance.highlightItem(item, false);
});
it("doesn't trigger event", () => {
expect(passedElementTriggerEventStub.called).to.equal(false);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
});
});
});
describe('highlightAll', () => {
let storeGetItemsStub;
let highlightItemStub;
const items = [
{
id: 1,
value: 'Test 1',
},
{
id: 2,
value: 'Test 2',
},
];
beforeEach(() => {
storeGetItemsStub = stub(instance._store, 'items').get(() => items);
highlightItemStub = stub();
instance.highlightItem = highlightItemStub;
output = instance.highlightAll();
});
afterEach(() => {
highlightItemStub.reset();
storeGetItemsStub.reset();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('highlights each item in store', () => {
expect(highlightItemStub.callCount).to.equal(items.length);
expect(highlightItemStub.firstCall.args[0]).to.equal(items[0]);
expect(highlightItemStub.lastCall.args[0]).to.equal(items[1]);
});
});
describe('unhighlightAll', () => {
let storeGetItemsStub;
let unhighlightItemStub;
const items = [
{
id: 1,
value: 'Test 1',
},
{
id: 2,
value: 'Test 2',
},
];
beforeEach(() => {
storeGetItemsStub = stub(instance._store, 'items').get(() => items);
unhighlightItemStub = stub();
instance.unhighlightItem = unhighlightItemStub;
output = instance.unhighlightAll();
});
afterEach(() => {
instance.unhighlightItem.reset();
storeGetItemsStub.reset();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('unhighlights each item in store', () => {
expect(unhighlightItemStub.callCount).to.equal(items.length);
expect(unhighlightItemStub.firstCall.args[0]).to.equal(items[0]);
expect(unhighlightItemStub.lastCall.args[0]).to.equal(items[1]);
});
});
describe('clearChoices', () => {
let storeDispatchStub;
beforeEach(() => {
storeDispatchStub = stub();
instance._store.dispatch = storeDispatchStub;
output = instance.clearChoices();
});
afterEach(() => {
instance._store.dispatch.reset();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('dispatches clearChoices action', () => {
expect(storeDispatchStub.lastCall.args[0]).to.eql({
type: ACTION_TYPES.CLEAR_CHOICES,
});
});
});
describe('clearStore', () => {
let storeDispatchStub;
beforeEach(() => {
storeDispatchStub = stub();
instance._store.dispatch = storeDispatchStub;
output = instance.clearStore();
});
afterEach(() => {
instance._store.dispatch.reset();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('dispatches clearAll action', () => {
expect(storeDispatchStub.lastCall.args[0]).to.eql({
type: ACTION_TYPES.CLEAR_ALL,
});
});
});
describe('clearInput', () => {
let inputClearSpy;
let storeDispatchStub;
beforeEach(() => {
inputClearSpy = spy(instance.input, 'clear');
storeDispatchStub = stub();
instance._store.dispatch = storeDispatchStub;
output = instance.clearInput();
});
afterEach(() => {
inputClearSpy.restore();
instance._store.dispatch.reset();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
describe('text element', () => {
beforeEach(() => {
instance._isSelectOneElement = false;
instance._isTextElement = false;
output = instance.clearInput();
});
it('clears input with correct arguments', () => {
expect(inputClearSpy.called).to.equal(true);
expect(inputClearSpy.lastCall.args[0]).to.equal(true);
});
});
describe('select element with search enabled', () => {
beforeEach(() => {
instance._isSelectOneElement = true;
instance._isTextElement = false;
instance.config.searchEnabled = true;
output = instance.clearInput();
});
it('clears input with correct arguments', () => {
expect(inputClearSpy.called).to.equal(true);
expect(inputClearSpy.lastCall.args[0]).to.equal(false);
});
it('resets search flag', () => {
expect(instance._isSearching).to.equal(false);
});
it('dispatches activateChoices action', () => {
expect(storeDispatchStub.called).to.equal(true);
expect(storeDispatchStub.lastCall.args[0]).to.eql({
type: ACTION_TYPES.ACTIVATE_CHOICES,
active: true,
});
});
});
});
describe('setChoices with callback/Promise', () => {
describe('not initialised', () => {
beforeEach(() => {
instance.initialised = false;
});
it('should throw', () => {
expect(() => instance.setChoices(null)).Throw(ReferenceError);
});
});
describe('text element', () => {
beforeEach(() => {
instance._isSelectElement = false;
});
it('should throw', () => {
expect(() => instance.setChoices(null)).Throw(TypeError);
});
});
describe('passing invalid function', () => {
beforeEach(() => {
instance._isSelectElement = true;
});
it('should throw on non function', () => {
expect(() => instance.setChoices(null)).Throw(TypeError, /Promise/i);
});
it(`should throw on function that doesn't return promise`, () => {
expect(() => instance.setChoices(() => 'boo')).to.throw(
TypeError,
/promise/i,
);
});
});
describe('select element', () => {
it('fetches and sets choices', async () => {
document.body.innerHTML = '<select id="test" />';
const choice = new Choices('#test', { allowHTML: true });
const handleLoadingStateSpy = spy(choice, '_handleLoadingState');
let fetcherCalled = false;
const fetcher = async (inst): Promise<Choice[]> => {
expect(inst).to.eq(choice);
fetcherCalled = true;
// eslint-disable-next-line no-promise-executor-return
await new Promise((resolve) => setTimeout(resolve, 800));
return [
{ label: 'l1', value: 'v1', customProperties: { prop1: true } },
{ label: 'l2', value: 'v2', customProperties: { prop2: false } },
];
};
expect(choice._store.choices.length).to.equal(0);
const promise = choice.setChoices(fetcher);
expect(fetcherCalled).to.be.true;
const res = await promise;
expect(res).to.equal(choice);
expect(handleLoadingStateSpy.callCount).to.equal(2);
expect(choice._store.choices[1].value).to.equal('v2');
expect(choice._store.choices[1].label).to.equal('l2');
expect(choice._store.choices[1].customProperties).to.deep.equal({
prop2: false,
});
});
});
});
describe('setValue', () => {
let setChoiceOrItemStub;
const values = [
'Value 1',
{
value: 'Value 2',
},
];
beforeEach(() => {
setChoiceOrItemStub = stub();
instance._setChoiceOrItem = setChoiceOrItemStub;
});
afterEach(() => {
instance._setChoiceOrItem.reset();
});
describe('not already initialised', () => {
beforeEach(() => {
instance.initialised = false;
output = instance.setValue(values);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('returns early', () => {
expect(setChoiceOrItemStub.called).to.equal(false);
});
});
describe('when already initialised', () => {
beforeEach(() => {
instance.initialised = true;
output = instance.setValue(values);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('sets each value', () => {
expect(setChoiceOrItemStub.callCount).to.equal(2);
expect(setChoiceOrItemStub.firstCall.args[0]).to.equal(values[0]);
expect(setChoiceOrItemStub.secondCall.args[0]).to.equal(values[1]);
});
});
});
describe('setChoiceByValue', () => {
let findAndSelectChoiceByValueStub;
beforeEach(() => {
findAndSelectChoiceByValueStub = stub();
instance._findAndSelectChoiceByValue = findAndSelectChoiceByValueStub;
});
afterEach(() => {
instance._findAndSelectChoiceByValue.reset();
});
describe('not already initialised', () => {
beforeEach(() => {
instance.initialised = false;
output = instance.setChoiceByValue([]);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('returns early', () => {
expect(findAndSelectChoiceByValueStub.called).to.equal(false);
});
});
describe('when already initialised and not text element', () => {
beforeEach(() => {
instance.initialised = true;
instance._isTextElement = false;
});
describe('passing a string value', () => {
const value = 'Test value';
beforeEach(() => {
output = instance.setChoiceByValue(value);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('sets each choice with same value', () => {
expect(findAndSelectChoiceByValueStub.called).to.equal(true);
expect(findAndSelectChoiceByValueStub.firstCall.args[0]).to.equal(
value,
);
});
});
describe('passing an array of values', () => {
const values = ['Value 1', 'Value 2'];
beforeEach(() => {
output = instance.setChoiceByValue(values);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('sets each choice with same value', () => {
expect(findAndSelectChoiceByValueStub.callCount).to.equal(2);
expect(findAndSelectChoiceByValueStub.firstCall.args[0]).to.equal(
values[0],
);
expect(findAndSelectChoiceByValueStub.secondCall.args[0]).to.equal(
values[1],
);
});
});
});
});
describe('getValue', () => {
let activeItemsStub;
const items = [
{
id: '1',
value: 'Test value 1',
},
{
id: '2',
value: 'Test value 2',
},
];
beforeEach(() => {
activeItemsStub = stub(instance._store, 'activeItems').get(() => items);
});
afterEach(() => {
activeItemsStub.reset();
});
describe('passing true valueOnly flag', () => {
describe('select one input', () => {
beforeEach(() => {
instance._isSelectOneElement = true;
output = instance.getValue(true);
});
it('returns a single action value', () => {
expect(output).to.equal(items[0].value);
});
});
describe('non select one input', () => {
beforeEach(() => {
instance._isSelectOneElement = false;
output = instance.getValue(true);
});
it('returns all active item values', () => {
expect(output).to.eql(items.map((item) => item.value));
});
});
});
describe('passing false valueOnly flag', () => {
describe('select one input', () => {
beforeEach(() => {
instance._isSelectOneElement = true;
output = instance.getValue(false);
});
it('returns a single active item', () => {
expect(output).to.equal(items[0]);
});
});
describe('non select one input', () => {
beforeEach(() => {
instance._isSelectOneElement = false;
output = instance.getValue(false);
});
it('returns all active items', () => {
expect(output).to.eql(items);
});
});
});
});
describe('removeActiveItemsByValue', () => {
let activeItemsStub;
let removeItemStub;
const value = 'Removed';
const items = [
{
id: '1',
value: 'Not removed',
},
{
id: '2',
value: 'Removed',
},
{
id: '3',
value: 'Removed',
},
];
beforeEach(() => {
removeItemStub = stub();
activeItemsStub = stub(instance._store, 'activeItems').get(() => items);
instance._removeItem = removeItemStub;
output = instance.removeActiveItemsByValue(value);
});
afterEach(() => {
activeItemsStub.reset();
instance._removeItem.reset();
});
it('removes each active item in store with matching value', () => {
expect(removeItemStub.callCount).to.equal(2);
expect(removeItemStub.firstCall.args[0]).to.equal(items[1]);
expect(removeItemStub.secondCall.args[0]).to.equal(items[2]);
});
});
describe('removeActiveItems', () => {
let activeItemsStub;
let removeItemStub;
const items = [
{
id: '1',
value: 'Not removed',
},
{
id: '2',
value: 'Removed',
},
{
id: '3',
value: 'Removed',
},
];
beforeEach(() => {
removeItemStub = stub();
activeItemsStub = stub(instance._store, 'activeItems').get(() => items);
instance._removeItem = removeItemStub;
});
afterEach(() => {
activeItemsStub.reset();
instance._removeItem.reset();
});
describe('not passing id to exclude', () => {
beforeEach(() => {
output = instance.removeActiveItems();
});
it('removes all active items in store', () => {
expect(removeItemStub.callCount).to.equal(items.length);
expect(removeItemStub.firstCall.args[0]).to.equal(items[0]);
expect(removeItemStub.secondCall.args[0]).to.equal(items[1]);
expect(removeItemStub.thirdCall.args[0]).to.equal(items[2]);
});
});
describe('passing id to exclude', () => {
const idToExclude = '2';
beforeEach(() => {
output = instance.removeActiveItems(idToExclude);
});
it('removes all active items in store with id that does match excludedId', () => {
expect(removeItemStub.callCount).to.equal(2);
expect(removeItemStub.firstCall.args[0]).to.equal(items[0]);
expect(removeItemStub.secondCall.args[0]).to.equal(items[2]);
});
});
});
describe('removeHighlightedItems', () => {
let highlightedActiveItemsStub;
let removeItemStub;
let triggerChangeStub;
const items = [
{
id: 1,
value: 'Test 1',
},
{
id: 2,
value: 'Test 2',
},
];
beforeEach(() => {
highlightedActiveItemsStub = stub(
instance._store,
'highlightedActiveItems',
).get(() => items);
removeItemStub = stub();
triggerChangeStub = stub();
instance._removeItem = removeItemStub;
instance._triggerChange = triggerChangeStub;
});
afterEach(() => {
highlightedActiveItemsStub.reset();
instance._removeItem.reset();
instance._triggerChange.reset();
});
describe('runEvent parameter being passed', () => {
beforeEach(() => {
output = instance.removeHighlightedItems();
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('removes each highlighted item in store', () => {
expect(removeItemStub.callCount).to.equal(2);
});
});
describe('runEvent parameter not being passed', () => {
beforeEach(() => {
output = instance.removeHighlightedItems(true);
});
it('returns this', () => {
expect(output).to.eql(instance);
});
it('triggers event with item value', () => {
expect(triggerChangeStub.callCount).to.equal(2);
expect(triggerChangeStub.firstCall.args[0]).to.equal(items[0].value);
expect(triggerChangeStub.secondCall.args[0]).to.equal(items[1].value);
});
});
});
describe('setChoices', () => {
let clearChoicesStub;
let addGroupStub;
let addChoiceStub;
let containerOuterRemoveLoadingStateStub;
const value = 'value';
const label = 'label';
const choices: Choice[] = [
{
id: 1,
value: '1',
label: 'Test 1',
selected: false,
disabled: false,
},
{
id: 2,
value: '2',
label: 'Test 2',
selected: false,
disabled: true,
},
];
const groups: Group[] = [
{
...choices[0],
choices,
},
choices[1],
];
beforeEach(() => {
clearChoicesStub = stub();
addGroupStub = stub();
addChoiceStub = stub();
containerOuterRemoveLoadingStateStub = stub();
instance.clearChoices = clearChoicesStub;
instance._addGroup = addGroupStub;
instance._addChoice = addChoiceStub;
instance.containerOuter.removeLoadingState =
containerOuterRemoveLoadingStateStub;
});
afterEach(() => {
instance.clearChoices.reset();
instance._addGroup.reset();
instance._addChoice.reset();
instance.containerOuter.removeLoadingState.reset();
});
describe('when element is not select element', () => {
beforeEach(() => {
instance._isSelectElement = false;
});
it('throws', () => {
expect(() =>
instance.setChoices(choices, value, label, false),
).to.throw(TypeError, /input/i);
});
});
describe('passing invalid arguments', () => {
describe('passing no value', () => {
beforeEach(() => {
instance._isSelectElement = true;
});
it('throws', () => {
expect(() =>
instance.setChoices(choices, null, 'label', false),
).to.throw(TypeError, /value/i);
});
});
});
describe('passing valid arguments', () => {
beforeEach(() => {
instance._isSelectElement = true;
});
it('removes loading state', () => {
instance.setChoices(choices, value, label, false);
expect(containerOuterRemoveLoadingStateStub.called).to.equal(true);
});
describe('passing choices with children choices', () => {
it('adds groups', () => {
instance.setChoices(groups, value, label, false);
expect(addGroupStub.callCount).to.equal(1);
expect(addGroupStub.firstCall.args[0]).to.eql({
group: groups[0],
id: groups[0].id,
valueKey: value,
labelKey: label,
});
});
});
describe('passing choices without children choices', () => {
it('adds passed choices', () => {
instance.setChoices(choices, value, label, false);
expect(addChoiceStub.callCount).to.equal(2);
addChoiceStub.getCalls().forEach((call, index) => {
expect(call.args[0]).to.eql({
value: choices[index][value],
label: choices[index][label],
isSelected: !!choices[index].selected,
isDisabled: !!choices[index].disabled,
customProperties: choices[index].customProperties,
placeholder: !!choices[index].placeholder,
});
});
});
});
describe('passing an empty array with a true replaceChoices flag', () => {
it('choices are cleared', () => {
instance._isSelectElement = true;
instance.setChoices([], value, label, true);
expect(clearChoicesStub.called).to.equal(true);
});
});
describe('passing an empty array with a false replaceChoices flag', () => {
it('choices stay the same', () => {
instance._isSelectElement = true;
instance.setChoices([], value, label, false);
expect(clearChoicesStub.called).to.equal(false);
});
});
describe('passing true replaceChoices flag', () => {
it('choices are cleared', () => {
instance.setChoices(choices, value, label, true);
expect(clearChoicesStub.called).to.equal(true);
});
});
describe('passing false replaceChoices flag', () => {
it('choices are not cleared', () => {
instance.setChoices(choices, value, label, false);
expect(clearChoicesStub.called).to.equal(false);
});
});
});
});
});
describe('events', () => {
describe('search', () => {
const choices: Choice[] = [
{
id: 1,
value: '1',
label: 'Test 1',
selected: false,
disabled: false,
},
{
id: 2,
value: '2',
label: 'Test 2',
selected: false,
disabled: false,
},
];
beforeEach(() => {
document.body.innerHTML = `
<select data-choice multiple></select>
`;
instance = new Choices('[data-choice]', {
choices,
allowHTML: false,
searchEnabled: true,
});
});
it('details are passed', (done) => {
const query =
'This is a <search> query & a "test" with characters that should not be sanitised.';
instance.input.value = query;
instance.input.focus();
instance.passedElement.element.addEventListener(
'search',
(event) => {
expect(event.detail).to.eql({
value: query,
resultCount: 0,
});
done();
},
{ once: true },
);
instance._onKeyUp({ target: null, keyCode: null });
});
it('uses Fuse options', (done) => {
instance.input.value = 'test';
instance.input.focus();
instance.passedElement.element.addEventListener(
'search',
(event) => {
expect(event.detail.resultCount).to.eql(2);
instance.config.fuseOptions.isCaseSensitive = true;
instance.config.fuseOptions.minMatchCharLength = 4;
instance.passedElement.element.addEventListener(
'search',
(eventCaseSensitive) => {
expect(eventCaseSensitive.detail.resultCount).to.eql(0);
done();
},
{ once: true },
);
instance._onKeyUp({ target: null, keyCode: null });
},
{ once: true },
);
instance._onKeyUp({ target: null, keyCode: null });
});
it('is fired with a searchFloor of 0', (done) => {
instance.config.searchFloor = 0;
instance.input.value = '';
instance.input.focus();
instance.passedElement.element.addEventListener('search', (event) => {
expect(event.detail).to.eql({
value: instance.input.value,
resultCount: 0,
});
done();
});
instance._onKeyUp({ target: null, keyCode: null });
});
});
});
describe('private methods', () => {
describe('_createGroupsFragment', () => {
let _createChoicesFragmentStub;
const choices: Choice[] = [
{
id: 1,
selected: true,
groupId: 1,
value: 'Choice 1',
label: 'Choice 1',
},
{
id: 2,
selected: false,
groupId: 2,
value: 'Choice 2',
label: 'Choice 2',
},
{
id: 3,
selected: false,
groupId: 1,
value: 'Choice 3',
label: 'Choice 3',
},
];
const groups: Group[] = [
{
id: 2,
value: 'Group 2',
active: true,
disabled: false,
},
{
id: 1,
value: 'Group 1',
active: true,
disabled: false,
},
];
beforeEach(() => {
_createChoicesFragmentStub = stub();
instance._createChoicesFragment = _createChoicesFragmentStub;
});
afterEach(() => {
instance._createChoicesFragment.reset();
});
describe('returning a fragment of groups', () => {
describe('passing fragment argument', () => {
it('updates fragment with groups', () => {
const fragment = document.createDocumentFragment();
const childElement = document.createElement('div');
fragment.appendChild(childElement);
output = instance._createGroupsFragment(groups, choices, fragment);
const elementToWrapFragment = document.createElement('div');
elementToWrapFragment.appendChild(output);
expect(output).to.be.instanceOf(DocumentFragment);
expect(elementToWrapFragment.children[0]).to.eql(childElement);
expect(
elementToWrapFragment.querySelectorAll('[data-group]').length,
).to.equal(2);
});
});
describe('not passing fragment argument', () => {
it('returns new groups fragment', () => {
output = instance._createGroupsFragment(groups, choices);
const elementToWrapFragment = document.createElement('div');
elementToWrapFragment.appendChild(output);
expect(output).to.be.instanceOf(DocumentFragment);
expect(
elementToWrapFragment.querySelectorAll('[data-group]').length,
).to.equal(2);
});
});
describe('sorting groups', () => {
let sortFnStub;
beforeEach(() => {
sortFnStub = stub();
instance.config.sorter = sortFnStub;
instance.config.shouldSort = true;
});
afterEach(() => {
instance.config.sorter.reset();
});
it('sorts groups by config.sorter', () => {
expect(sortFnStub.called).to.equal(false);
instance._createGroupsFragment(groups, choices);
expect(sortFnStub.called).to.equal(true);
});
});
describe('not sorting groups', () => {
let sortFnStub;
beforeEach(() => {
sortFnStub = stub();
instance.config.sorter = sortFnStub;
instance.config.shouldSort = false;
});
afterEach(() => {
instance.config.sorter.reset();
});
it('does not sort groups', () => {
instance._createGroupsFragment(groups, choices);
expect(sortFnStub.called).to.equal(false);
});
});
describe('select-one element', () => {
beforeEach(() => {
instance._isSelectOneElement = true;
});
it('calls _createChoicesFragment with choices that belong to each group', () => {
expect(_createChoicesFragmentStub.called).to.equal(false);
instance._createGroupsFragment(groups, choices);
expect(_createChoicesFragmentStub.called).to.equal(true);
expect(_createChoicesFragmentStub.firstCall.args[0]).to.eql([
{
id: 1,
selected: true,
groupId: 1,
value: 'Choice 1',
label: 'Choice 1',
},
{
id: 3,
selected: false,
groupId: 1,
value: 'Choice 3',
label: 'Choice 3',
},
]);
expect(_createChoicesFragmentStub.secondCall.args[0]).to.eql([
{
id: 2,
selected: false,
groupId: 2,
value: 'Choice 2',
label: 'Choice 2',
},
]);
});
});
describe('text/select-multiple element', () => {
describe('renderSelectedChoices set to "always"', () => {
beforeEach(() => {
instance._isSelectOneElement = false;
instance.config.renderSelectedChoices = 'always';
});
it('calls _createChoicesFragment with choices that belong to each group', () => {
expect(_createChoicesFragmentStub.called).to.equal(false);
instance._createGroupsFragment(groups, choices);
expect(_createChoicesFragmentStub.called).to.equal(true);
expect(_createChoicesFragmentStub.firstCall.args[0]).to.eql([
{
id: 1,
selected: true,
groupId: 1,
value: 'Choice 1',
label: 'Choice 1',
},
{
id: 3,
selected: false,
groupId: 1,
value: 'Choice 3',
label: 'Choice 3',
},
]);
expect(_createChoicesFragmentStub.secondCall.args[0]).to.eql([
{
id: 2,
selected: false,
groupId: 2,
value: 'Choice 2',
label: 'Choice 2',
},
]);
});
});
describe('renderSelectedChoices not set to "always"', () => {
beforeEach(() => {
instance._isSelectOneElement = false;
instance.config.renderSelectedChoices = false;
});
it('calls _createChoicesFragment with choices that belong to each group that are not already selected', () => {
expect(_createChoicesFragmentStub.called).to.equal(false);
instance._createGroupsFragment(groups, choices);
expect(_createChoicesFragmentStub.called).to.equal(true);
expect(_createChoicesFragmentStub.firstCall.args[0]).to.eql([
{
id: 3,
selected: false,
groupId: 1,
value: 'Choice 3',
label: 'Choice 3',
},
]);
expect(_createChoicesFragmentStub.secondCall.args[0]).to.eql([
{
id: 2,
selected: false,
groupId: 2,
value: 'Choice 2',
label: 'Choice 2',
},
]);
});
});
});
});
});
describe('_generatePlaceholderValue', () => {
describe('select element', () => {
describe('when a placeholder option is defined', () => {
it('returns the text value of the placeholder option', () => {
const placeholderValue = 'I am a placeholder';
instance._isSelectElement = true;
instance.passedElement.placeholderOption = {
text: placeholderValue,
};
const value = instance._generatePlaceholderValue();
expect(value).to.equal(placeholderValue);
});
});
describe('when a placeholder option is not defined', () => {
it('returns null', () => {
instance._isSelectElement = true;
instance.passedElement.placeholderOption = undefined;
const value = instance._generatePlaceholderValue();
expect(value).to.equal(null);
});
});
});
describe('text input', () => {
describe('when the placeholder config option is set to true', () => {
describe('when the placeholderValue config option is defined', () => {
it('returns placeholderValue', () => {
const placeholderValue = 'I am a placeholder';
instance._isSelectElement = false;
instance.config.placeholder = true;
instance.config.placeholderValue = placeholderValue;
const value = instance._generatePlaceholderValue();
expect(value).to.equal(placeholderValue);
});
});
describe('when the placeholderValue config option is not defined', () => {
describe('when the placeholder attribute is defined on the passed element', () => {
it('returns the value of the placeholder attribute', () => {
const placeholderValue = 'I am a placeholder';
instance._isSelectElement = false;
instance.config.placeholder = true;
instance.config.placeholderValue = undefined;
instance.passedElement.element = {
dataset: {
placeholder: placeholderValue,
},
};
const value = instance._generatePlaceholderValue();
expect(value).to.equal(placeholderValue);
});
});
describe('when the placeholder attribute is not defined on the passed element', () => {
it('returns null', () => {
instance._isSelectElement = false;
instance.config.placeholder = true;
instance.config.placeholderValue = undefined;
instance.passedElement.element = {
dataset: {
placeholder: undefined,
},
};
const value = instance._generatePlaceholderValue();
expect(value).to.equal(null);
});
});
});
});
describe('when the placeholder config option is set to false', () => {
it('returns null', () => {
instance._isSelectElement = false;
instance.config.placeholder = false;
const value = instance._generatePlaceholderValue();
expect(value).to.equal(null);
});
});
});
});
describe('_getTemplate', () => {
describe('when passing a template key', () => {
it('returns the generated template for the given template key', () => {
const templateKey = 'test';
const element = document.createElement('div');
const customArg = { test: true };
instance._templates = {
[templateKey]: stub().returns(element),
};
output = instance._getTemplate(templateKey, customArg);
expect(output).to.deep.equal(element);
expect(instance._templates[templateKey]).to.have.been.calledOnceWith(
instance.config,
customArg,
);
});
});
});
describe('_onKeyDown', () => {
let activeItems;
let hasItems;
let hasActiveDropdown;
let hasFocussedInput;
beforeEach(() => {
instance.showDropdown = stub();
instance._onSelectKey = stub();
instance._onEnterKey = stub();
instance._onEscapeKey = stub();
instance._onDirectionKey = stub();
instance._onDeleteKey = stub();
({ activeItems } = instance._store);
hasItems = instance.itemList.hasChildren();
hasActiveDropdown = instance.dropdown.isActive;
hasFocussedInput = instance.input.isFocussed;
});
describe('direction key', () => {
const keyCodes = [
KEY_CODES.UP_KEY,
KEY_CODES.DOWN_KEY,
KEY_CODES.PAGE_UP_KEY,
KEY_CODES.PAGE_DOWN_KEY,
];
keyCodes.forEach((keyCode) => {
it(`calls _onDirectionKey with the expected arguments`, () => {
const event = {
keyCode,
};
instance._onKeyDown(event);
expect(instance._onDirectionKey).to.have.been.calledWith(
event,
hasActiveDropdown,
);
});
});
});
describe('select key', () => {
it(`calls _onSelectKey with the expected arguments`, () => {
const event = {
keyCode: KEY_CODES.A_KEY,
};
instance._onKeyDown(event);
expect(instance._onSelectKey).to.have.been.calledWith(
event,
hasItems,
);
});
});
describe('enter key', () => {
it(`calls _onEnterKey with the expected arguments`, () => {
const event = {
keyCode: KEY_CODES.ENTER_KEY,
};
instance._onKeyDown(event);
expect(instance._onEnterKey).to.have.been.calledWith(
event,
activeItems,
hasActiveDropdown,
);
});
});
describe('delete key', () => {
const keyCodes = [KEY_CODES.DELETE_KEY, KEY_CODES.BACK_KEY];
keyCodes.forEach((keyCode) => {
it(`calls _onDeleteKey with the expected arguments`, () => {
const event = {
keyCode,
};
instance._onKeyDown(event);
expect(instance._onDeleteKey).to.have.been.calledWith(
event,
activeItems,
hasFocussedInput,
);
});
});
});
});
describe('_removeItem', () => {
beforeEach(() => {
instance._store.dispatch = stub();
});
afterEach(() => {
instance._store.dispatch.reset();
});
describe('when given an item to remove', () => {
const item = {
id: 1111,
value: 'test value',
label: 'test label',
choiceId: 2222,
groupId: 3333,
customProperties: {},
};
it('dispatches a REMOVE_ITEM action to the store', () => {
instance._removeItem(item);
expect(instance._store.dispatch).to.have.been.calledWith(
removeItem(item.id, item.choiceId),
);
});
it('triggers a REMOVE_ITEM event on the passed element', (done) => {
passedElement.addEventListener(
'removeItem',
(event) => {
expect(event.detail).to.eql({
id: item.id,
value: item.value,
label: item.label,
customProperties: item.customProperties,
groupValue: null,
});
done();
},
false,
);
instance._removeItem(item);
});
describe('when the item belongs to a group', () => {
const group = {
id: 1,
value: 'testing',
};
const itemWithGroup = {
...item,
groupId: group.id,
};
beforeEach(() => {
instance._store.getGroupById = stub();
instance._store.getGroupById.returns(group);
});
afterEach(() => {
instance._store.getGroupById.reset();
});
it("includes the group's value in the triggered event", (done) => {
passedElement.addEventListener(
'removeItem',
(event) => {
expect(event.detail).to.eql({
id: itemWithGroup.id,
value: itemWithGroup.value,
label: itemWithGroup.label,
customProperties: itemWithGroup.customProperties,
groupValue: group.value,
});
done();
},
false,
);
instance._removeItem(itemWithGroup);
});
});
});
});
});
});
``` | /content/code_sandbox/src/scripts/choices.test.ts | xml | 2016-03-15T14:02:08 | 2024-08-15T07:08:50 | Choices | Choices-js/Choices | 6,092 | 14,251 |
```xml
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<dataset update-count="2">
<metadata data-nodes="write_ds_${0..9}.t_order_${0..9},read_ds_${0..9}.t_order_${0..9}">
<column name="order_id" type="numeric" />
<column name="user_id" type="numeric" />
<column name="status" type="varchar" />
<column name="merchant_id" type="numeric" />
<column name="remark" type="varchar" />
<column name="creation_date" type="datetime" />
</metadata>
<row data-node="write_ds_0.t_order_0" values="1000, 10, update, 1, test, 2017-08-08" />
<row data-node="write_ds_0.t_order_1" values="1001, 10, init, 2, test, 2017-08-08" />
<row data-node="write_ds_0.t_order_2" values="1002, 10, init, 3, test, 2017-08-08" />
<row data-node="write_ds_0.t_order_3" values="1003, 10, init, 4, test, 2017-08-08" />
<row data-node="write_ds_0.t_order_4" values="1004, 10, init, 5, test, 2017-08-08" />
<row data-node="write_ds_0.t_order_5" values="1005, 10, init, 6, test, 2017-08-08" />
<row data-node="write_ds_0.t_order_6" values="1006, 10, init, 7, test, 2017-08-08" />
<row data-node="write_ds_0.t_order_7" values="1007, 10, init, 8, test, 2017-08-08" />
<row data-node="write_ds_0.t_order_8" values="1008, 10, init, 9, test, 2017-08-08" />
<row data-node="write_ds_0.t_order_9" values="1009, 10, init, 10, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_0" values="1100, 11, init, 11, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_1" values="1101, 11, init, 12, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_2" values="1102, 11, init, 13, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_3" values="1103, 11, init, 14, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_4" values="1104, 11, init, 15, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_5" values="1105, 11, init, 16, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_6" values="1106, 11, init, 17, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_7" values="1107, 11, init, 18, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_8" values="1108, 11, init, 19, test, 2017-08-08" />
<row data-node="write_ds_1.t_order_9" values="1109, 11, init, 20, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_0" values="1200, 12, init, 1, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_1" values="1201, 12, init, 2, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_2" values="1202, 12, init, 3, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_3" values="1203, 12, init, 4, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_4" values="1204, 12, init, 5, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_5" values="1205, 12, init, 6, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_6" values="1206, 12, init, 7, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_7" values="1207, 12, init, 8, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_8" values="1208, 12, init, 9, test, 2017-08-08" />
<row data-node="write_ds_2.t_order_9" values="1209, 12, init, 10, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_0" values="1300, 13, init, 11, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_1" values="1301, 13, init, 12, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_2" values="1302, 13, init, 13, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_3" values="1303, 13, init, 14, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_4" values="1304, 13, init, 15, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_5" values="1305, 13, init, 16, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_6" values="1306, 13, init, 17, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_7" values="1307, 13, init, 18, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_8" values="1308, 13, init, 19, test, 2017-08-08" />
<row data-node="write_ds_3.t_order_9" values="1309, 13, init, 20, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_0" values="1400, 14, init, 1, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_1" values="1401, 14, init, 2, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_2" values="1402, 14, init, 3, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_3" values="1403, 14, init, 4, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_4" values="1404, 14, init, 5, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_5" values="1405, 14, init, 6, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_6" values="1406, 14, init, 7, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_7" values="1407, 14, init, 8, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_8" values="1408, 14, init, 9, test, 2017-08-08" />
<row data-node="write_ds_4.t_order_9" values="1409, 14, init, 10, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_0" values="1500, 15, init, 11, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_1" values="1501, 15, init, 12, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_2" values="1502, 15, init, 13, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_3" values="1503, 15, init, 14, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_4" values="1504, 15, init, 15, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_5" values="1505, 15, init, 16, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_6" values="1506, 15, init, 17, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_7" values="1507, 15, init, 18, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_8" values="1508, 15, init, 19, test, 2017-08-08" />
<row data-node="write_ds_5.t_order_9" values="1509, 15, init, 20, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_0" values="1600, 16, init, 1, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_1" values="1601, 16, init, 2, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_2" values="1602, 16, init, 3, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_3" values="1603, 16, init, 4, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_4" values="1604, 16, init, 5, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_5" values="1605, 16, init, 6, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_6" values="1606, 16, init, 7, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_7" values="1607, 16, init, 8, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_8" values="1608, 16, init, 9, test, 2017-08-08" />
<row data-node="write_ds_6.t_order_9" values="1609, 16, init, 10, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_0" values="1700, 17, init, 11, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_1" values="1701, 17, init, 12, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_2" values="1702, 17, init, 13, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_3" values="1703, 17, init, 14, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_4" values="1704, 17, init, 15, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_5" values="1705, 17, init, 16, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_6" values="1706, 17, init, 17, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_7" values="1707, 17, init, 18, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_8" values="1708, 17, init, 19, test, 2017-08-08" />
<row data-node="write_ds_7.t_order_9" values="1709, 17, init, 20, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_0" values="1800, 18, init, 1, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_1" values="1801, 18, init, 2, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_2" values="1802, 18, init, 3, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_3" values="1803, 18, init, 4, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_4" values="1804, 18, init, 5, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_5" values="1805, 18, init, 6, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_6" values="1806, 18, init, 7, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_7" values="1807, 18, init, 8, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_8" values="1808, 18, init, 9, test, 2017-08-08" />
<row data-node="write_ds_8.t_order_9" values="1809, 18, init, 10, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_0" values="1900, 19, init, 11, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_1" values="1901, 19, init, 12, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_2" values="1902, 19, init, 13, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_3" values="1903, 19, init, 14, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_4" values="1904, 19, init, 15, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_5" values="1905, 19, init, 16, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_6" values="1906, 19, init, 17, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_7" values="1907, 19, init, 18, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_8" values="1908, 19, init, 19, test, 2017-08-08" />
<row data-node="write_ds_9.t_order_9" values="1909, 19, init, 20, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_0" values="1000, 10, init_read, 1, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_1" values="1001, 10, init_read, 2, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_2" values="1002, 10, init_read, 3, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_3" values="1003, 10, init_read, 4, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_4" values="1004, 10, init_read, 5, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_5" values="1005, 10, init_read, 6, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_6" values="1006, 10, init_read, 7, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_7" values="1007, 10, init_read, 8, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_8" values="1008, 10, init_read, 9, test, 2017-08-08" />
<row data-node="read_ds_0.t_order_9" values="1009, 10, init_read, 10, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_0" values="1100, 11, init_read, 11, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_1" values="1101, 11, init_read, 12, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_2" values="1102, 11, init_read, 13, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_3" values="1103, 11, init_read, 14, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_4" values="1104, 11, init_read, 15, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_5" values="1105, 11, init_read, 16, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_6" values="1106, 11, init_read, 17, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_7" values="1107, 11, init_read, 18, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_8" values="1108, 11, init_read, 19, test, 2017-08-08" />
<row data-node="read_ds_1.t_order_9" values="1109, 11, init_read, 20, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_0" values="1200, 12, init_read, 1, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_1" values="1201, 12, init_read, 2, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_2" values="1202, 12, init_read, 3, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_3" values="1203, 12, init_read, 4, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_4" values="1204, 12, init_read, 5, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_5" values="1205, 12, init_read, 6, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_6" values="1206, 12, init_read, 7, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_7" values="1207, 12, init_read, 8, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_8" values="1208, 12, init_read, 9, test, 2017-08-08" />
<row data-node="read_ds_2.t_order_9" values="1209, 12, init_read, 10, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_0" values="1300, 13, init_read, 11, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_1" values="1301, 13, init_read, 12, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_2" values="1302, 13, init_read, 13, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_3" values="1303, 13, init_read, 14, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_4" values="1304, 13, init_read, 15, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_5" values="1305, 13, init_read, 16, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_6" values="1306, 13, init_read, 17, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_7" values="1307, 13, init_read, 18, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_8" values="1308, 13, init_read, 19, test, 2017-08-08" />
<row data-node="read_ds_3.t_order_9" values="1309, 13, init_read, 20, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_0" values="1400, 14, init_read, 1, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_1" values="1401, 14, init_read, 2, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_2" values="1402, 14, init_read, 3, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_3" values="1403, 14, init_read, 4, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_4" values="1404, 14, init_read, 5, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_5" values="1405, 14, init_read, 6, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_6" values="1406, 14, init_read, 7, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_7" values="1407, 14, init_read, 8, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_8" values="1408, 14, init_read, 9, test, 2017-08-08" />
<row data-node="read_ds_4.t_order_9" values="1409, 14, init_read, 10, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_0" values="1500, 15, init_read, 11, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_1" values="1501, 15, init_read, 12, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_2" values="1502, 15, init_read, 13, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_3" values="1503, 15, init_read, 14, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_4" values="1504, 15, init_read, 15, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_5" values="1505, 15, init_read, 16, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_6" values="1506, 15, init_read, 17, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_7" values="1507, 15, init_read, 18, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_8" values="1508, 15, init_read, 19, test, 2017-08-08" />
<row data-node="read_ds_5.t_order_9" values="1509, 15, init_read, 20, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_0" values="1600, 16, init_read, 1, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_1" values="1601, 16, init_read, 2, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_2" values="1602, 16, init_read, 3, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_3" values="1603, 16, init_read, 4, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_4" values="1604, 16, init_read, 5, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_5" values="1605, 16, init_read, 6, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_6" values="1606, 16, init_read, 7, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_7" values="1607, 16, init_read, 8, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_8" values="1608, 16, init_read, 9, test, 2017-08-08" />
<row data-node="read_ds_6.t_order_9" values="1609, 16, init_read, 10, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_0" values="1700, 17, init_read, 11, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_1" values="1701, 17, init_read, 12, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_2" values="1702, 17, init_read, 13, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_3" values="1703, 17, init_read, 14, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_4" values="1704, 17, init_read, 15, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_5" values="1705, 17, init_read, 16, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_6" values="1706, 17, init_read, 17, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_7" values="1707, 17, init_read, 18, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_8" values="1708, 17, init_read, 19, test, 2017-08-08" />
<row data-node="read_ds_7.t_order_9" values="1709, 17, init_read, 20, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_0" values="1800, 18, init_read, 1, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_1" values="1801, 18, init_read, 2, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_2" values="1802, 18, init_read, 3, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_3" values="1803, 18, init_read, 4, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_4" values="1804, 18, init_read, 5, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_5" values="1805, 18, init_read, 6, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_6" values="1806, 18, init_read, 7, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_7" values="1807, 18, init_read, 8, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_8" values="1808, 18, init_read, 9, test, 2017-08-08" />
<row data-node="read_ds_8.t_order_9" values="1809, 18, init_read, 10, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_0" values="1900, 19, init_read, 11, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_1" values="1901, 19, init_read, 12, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_2" values="1902, 19, init_read, 13, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_3" values="1903, 19, init_read, 14, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_4" values="1904, 19, init_read, 15, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_5" values="1905, 19, init_read, 16, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_6" values="1906, 19, init_read, 17, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_7" values="1907, 19, init_read, 18, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_8" values="1908, 19, init_read, 19, test, 2017-08-08" />
<row data-node="read_ds_9.t_order_9" values="1909, 19, init_read, 20, test, 2017-08-08" />
</dataset>
``` | /content/code_sandbox/test/e2e/sql/src/test/resources/cases/dml/dataset/dbtbl_with_readwrite_splitting/insert_on_duplicate_key_update.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 8,097 |
```xml
import { Observable, Subject, map } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { StateObservable } from '../src';
describe('StateObservable', () => {
it('should exist', () => {
expect.assertions(1);
expect(StateObservable.prototype).toBeInstanceOf(Observable);
});
it('should mirror the source subject', () => {
expect.assertions(3);
const input$ = new Subject();
const state$ = new StateObservable(input$, 'first');
let result = null;
state$.subscribe((state) => {
result = state;
});
expect(result).toEqual('first');
input$.next('second');
expect(result).toEqual('second');
input$.next('third');
expect(result).toEqual('third');
});
it('should cache last state on the `value` property', () => {
expect.assertions(2);
const input$ = new Subject();
const state$ = new StateObservable(input$, 'first');
expect(state$.value).toEqual('first');
input$.next('second');
expect(state$.value).toEqual('second');
});
it('should only update when the next value shallowly differs', () => {
expect.assertions(10);
const input$ = new Subject();
const first = { value: 'first' };
const state$ = new StateObservable(input$, first);
const next = vi.fn();
state$.subscribe(next);
expect(state$.value).toEqual(first);
expect(next).toHaveBeenCalledOnce();
expect(next).lastCalledWith(first);
input$.next(first);
expect(state$.value).toEqual(first);
expect(next).toHaveBeenCalledOnce();
first.value = 'something else';
input$.next(first);
expect(state$.value).toEqual(first);
expect(next).toHaveBeenCalledOnce();
const second = { value: 'second' };
input$.next(second);
expect(state$.value).toEqual(second);
expect(next).toHaveBeenCalledTimes(2);
expect(next).lastCalledWith(second);
});
it('works correctly (and does not lift) with operators applied', () => {
expect.assertions(6);
const first = { value: 'first' };
const input$ = new Subject<typeof first>();
const state$ = new StateObservable(input$, first).pipe(map((d) => d.value));
const next = vi.fn();
state$.subscribe(next);
// @ts-expect-error because we piped an operator over it state$ is no longer
// a StateObservable it's just a regular Observable and so it loses its `.value` prop
expect(state$.value).toEqual(undefined);
expect(next).toHaveBeenCalledOnce();
expect(next).lastCalledWith('first');
first.value = 'something else';
input$.next(first);
expect(next).toHaveBeenCalledOnce();
const second = { value: 'second' };
input$.next(second);
expect(next).toHaveBeenCalledTimes(2);
expect(next).lastCalledWith('second');
});
});
``` | /content/code_sandbox/test/StateObservable-spec.ts | xml | 2016-04-20T21:58:23 | 2024-08-12T22:17:00 | redux-observable | redux-observable/redux-observable | 7,852 | 647 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.