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
const checklistsChanged = `
subscription ticketsChecklistDetailChanged($contentType: String!, $contentTypeId: String!) {
ticketsChecklistDetailChanged(contentType: $contentType, contentTypeId: $contentTypeId) {
_id
}
}
`;
const checklistDetailChanged = `
subscription ticketsChecklistDetailChanged($_id: String!) {
ticketsChecklistDetailChanged(_id: $_id) {
_id
}
}
`;
export default {
checklistsChanged,
checklistDetailChanged
};
``` | /content/code_sandbox/packages/ui-tickets/src/checklists/graphql/subscriptions.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 110 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".ui.activity.ViewTransformActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="280dp"
android:layout_margin="10dp"
android:background="@color/cpb_blue"
android:gravity="center">
<home.smart.fly.animations.customview.TransformView
android:id="@+id/transformView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/fixed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:checked="true"
android:text="fixed" />
<CheckBox
android:id="@+id/negative"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:checked="false"
android:text="negative" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioGroup
android:id="@+id/FlipViewSel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/UDFlipView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="UDFlipView" />
<RadioButton
android:id="@+id/LRFlipView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:text="LRFlipView" />
<RadioButton
android:id="@+id/nullFlipView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:text="nullFlipView" />
</RadioGroup>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<home.smart.fly.animations.customview.EasySeekBar
android:id="@+id/rotateX"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
app:label="RotationX" />
<home.smart.fly.animations.customview.EasySeekBar
android:id="@+id/rotateY"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
app:label="RotationY" />
<home.smart.fly.animations.customview.EasySeekBar
android:id="@+id/rotateZ"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
app:label="RotationZ" />
<home.smart.fly.animations.customview.EasySeekBar
android:id="@+id/scaleX"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
app:label="scaleX" />
<home.smart.fly.animations.customview.EasySeekBar
android:id="@+id/scaleY"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
app:label="scaleY" />
</LinearLayout>
</ScrollView>
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/activity_view_transform.xml | xml | 2016-08-08T08:52:10 | 2024-08-12T19:24:13 | AndroidAnimationExercise | REBOOTERS/AndroidAnimationExercise | 1,868 | 925 |
```xml
/*
* This software is released under MIT license.
* The full license information can be found in LICENSE in the root directory of this project.
*/
export * from './textarea.element.js';
``` | /content/code_sandbox/packages/core/src/textarea/index.ts | xml | 2016-09-29T17:24:17 | 2024-08-11T17:06:15 | clarity | vmware-archive/clarity | 6,431 | 38 |
```xml
export default function page() {
return <>pages-icon-page</>
}
``` | /content/code_sandbox/test/e2e/app-dir/metadata/pages/blog/icon.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 16 |
```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.
-->
<accelerateDecelerateInterpolator xmlns:android="path_to_url" />
``` | /content/code_sandbox/libraries_res/chrome_res/src/main/res/interpolator/transform_curve_interpolator.xml | xml | 2016-07-04T07:28:36 | 2024-08-15T05:20:42 | AndroidChromium | JackyAndroid/AndroidChromium | 3,090 | 56 |
```xml
import { VERSION } from '@angular/core';
import { SemVerDSL as DSL, ISemVerDSL } from 'semver-dsl';
export const SemVerDSL: ISemVerDSL = DSL(VERSION.full);
``` | /content/code_sandbox/src/util/ngVersion.ts | xml | 2016-02-10T17:22:40 | 2024-08-14T16:41:28 | codelyzer | mgechev/codelyzer | 2,446 | 46 |
```xml
export interface SubscriptionCallback<T> {
(item: T): void;
}
// eslint-disable-next-line @typescript-eslint/ban-types
export interface Store<T extends object> {
subscribeToItem<K extends keyof T>(
key: K,
callback: SubscriptionCallback<T[K]>
): void;
unsubscribeFromItem<K extends keyof T>(
key: K,
callback: SubscriptionCallback<T[K]>
): void;
updateItem<K extends keyof T>(key: K, item: T[K]): void;
getItem<K extends keyof T>(key: K): T[K];
}
// eslint-disable-next-line @typescript-eslint/ban-types
export function createStore<T extends object>(
initialState: T = {} as T
): Store<T> {
let state: T = initialState;
const listeners: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[x in keyof T]: Array<(v: any) => void>;
} = {} as {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[x in keyof T]: Array<(v: any) => void>;
};
return {
subscribeToItem(key, callback) {
listeners[key] = listeners[key] || [];
listeners[key]!.push(callback);
},
unsubscribeFromItem(key, callback) {
const listener = listeners[key];
if (listener) {
listeners[key] = listener.filter(
(currentListener) => currentListener !== callback
);
}
},
updateItem(key, item) {
state = {
...state,
[key]: item,
};
const listener = listeners[key];
if (listener) {
listener.forEach((currentListener) => currentListener(state[key]));
}
},
getItem(key) {
return state[key];
},
};
}
``` | /content/code_sandbox/packages/utils/src/createStore.ts | xml | 2016-02-26T09:54:56 | 2024-08-16T18:16:31 | draft-js-plugins | draft-js-plugins/draft-js-plugins | 4,087 | 385 |
```xml
<clickhouse>
<profiles>
<default>
<allow_experimental_database_materialized_mysql>1</allow_experimental_database_materialized_mysql>
<external_storage_max_read_rows>0</external_storage_max_read_rows>
<external_storage_max_read_bytes>1</external_storage_max_read_bytes>
</default>
</profiles>
<users>
<default>
<password></password>
<networks incl="networks" replace="replace">
<ip>::/0</ip>
</networks>
<profile>default</profile>
</default>
</users>
</clickhouse>
``` | /content/code_sandbox/tests/integration/test_materialized_mysql_database/configs/users_disable_rows_settings.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 134 |
```xml
import { inject, injectable, } from 'inversify';
import { ServiceIdentifiers } from '../../container/ServiceIdentifiers';
import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory';
import { TStatement } from '../../types/node/TStatement';
import { TStringArrayIndexNodeFactory } from '../../types/container/custom-nodes/string-array-index-nodes/TStringArrayIndexNodeFactory';
import { IArrayUtils } from '../../interfaces/utils/IArrayUtils';
import { ICustomCodeHelperFormatter } from '../../interfaces/custom-code-helpers/ICustomCodeHelperFormatter';
import { IOptions } from '../../interfaces/options/IOptions';
import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
import { IStringArrayScopeCallsWrapperData } from '../../interfaces/node-transformers/string-array-transformers/IStringArrayScopeCallsWrapperData';
import { IStringArrayStorage } from '../../interfaces/storages/string-array-transformers/IStringArrayStorage';
import { initializable } from '../../decorators/Initializable';
import { AbstractStringArrayCallNode } from './AbstractStringArrayCallNode';
import { NodeFactory } from '../../node/NodeFactory';
import { NodeUtils } from '../../node/NodeUtils';
@injectable()
export class StringArrayScopeCallsWrapperVariableNode extends AbstractStringArrayCallNode {
/**
* @type {IStringArrayScopeCallsWrapperData}
*/
@initializable()
private stringArrayCallsWrapperData!: IStringArrayScopeCallsWrapperData;
/**
* @type {IStringArrayScopeCallsWrapperData}
*/
@initializable()
private stringArrayScopeCallsWrapperData!: IStringArrayScopeCallsWrapperData;
/**
* @param {TIdentifierNamesGeneratorFactory} identifierNamesGeneratorFactory
* @param {TStringArrayIndexNodeFactory} stringArrayIndexNodeFactory
* @param {ICustomCodeHelperFormatter} customCodeHelperFormatter
* @param {IStringArrayStorage} stringArrayStorage
* @param {IArrayUtils} arrayUtils
* @param {IRandomGenerator} randomGenerator
* @param {IOptions} options
*/
public constructor (
@inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator)
identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory,
@inject(ServiceIdentifiers.Factory__IStringArrayIndexNode)
stringArrayIndexNodeFactory: TStringArrayIndexNodeFactory,
@inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter,
@inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage,
@inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils,
@inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
@inject(ServiceIdentifiers.IOptions) options: IOptions,
) {
super(
identifierNamesGeneratorFactory,
stringArrayIndexNodeFactory,
customCodeHelperFormatter,
stringArrayStorage,
arrayUtils,
randomGenerator,
options
);
}
/**
* @param {IStringArrayScopeCallsWrapperData} stringArrayScopeCallsWrapperData
* @param {IStringArrayScopeCallsWrapperData} stringArrayCallsWrapperData
*/
public initialize (
stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData,
stringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData
): void {
this.stringArrayScopeCallsWrapperData = stringArrayScopeCallsWrapperData;
this.stringArrayCallsWrapperData = stringArrayCallsWrapperData;
}
/**
* @returns {TStatement[]}
*/
protected getNodeStructure (): TStatement[] {
const structure: TStatement = NodeFactory.variableDeclarationNode(
[
NodeFactory.variableDeclaratorNode(
NodeFactory.identifierNode(this.stringArrayScopeCallsWrapperData.name),
NodeFactory.identifierNode(this.stringArrayCallsWrapperData.name)
)
],
'const',
);
NodeUtils.parentizeAst(structure);
return [structure];
}
}
``` | /content/code_sandbox/src/custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperVariableNode.ts | xml | 2016-05-09T08:16:53 | 2024-08-16T19:43:07 | javascript-obfuscator | javascript-obfuscator/javascript-obfuscator | 13,358 | 859 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks Condition="'$(OS)' != 'Windows_NT'">net6.0;net5.0;netcoreapp3.1</TargetFrameworks>
<TargetFrameworks Condition="'$(OS)' == 'Windows_NT'">net6.0;net5.0;net471;netcoreapp3.1</TargetFrameworks>
<ApplicationIcon />
<StartupObject />
<TargetFrameworks>net6.0;net8.0;net471</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LiteNetLib\LiteNetLib.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="TestUtility\" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/LiteNetLib.Tests/LiteNetLib.Tests.csproj | xml | 2016-01-15T18:28:35 | 2024-08-16T03:25:43 | LiteNetLib | RevenantX/LiteNetLib | 3,025 | 290 |
```xml
import { Trace } from '@apollo/usage-reporting-protobuf';
import { TraceTreeBuilder } from '../traceTreeBuilder.js';
import type { SendErrorsOptions } from '../usageReporting/index.js';
import { internalPlugin } from '../../internalPlugin.js';
import { schemaIsSubgraph } from '../schemaIsSubgraph.js';
import type { ApolloServerPlugin } from '../../externalTypes/index.js';
export interface ApolloServerPluginInlineTraceOptions {
/**
* By default, if a trace contains errors, the errors are included in the
* trace with the message `<masked>`. The errors are associated with specific
* paths in the operation, but do not include the original error message or
* any extensions such as the error `code`, as those details may contain your
* users' private data. The extension `maskedBy:
* 'ApolloServerPluginInlineTrace'` is added.
*
* If you'd like details about the error included in traces, set this option.
* This option can take several forms:
*
* - { masked: true }: mask error messages and omit extensions (DEFAULT)
* - { unmodified: true }: include all error messages and extensions
* - { transform: ... }: a custom function for transforming errors. This
* function receives a `GraphQLError` and may return a `GraphQLError`
* (either a new error, or its potentially-modified argument) or `null`.
* This error is used in the trace; if `null`, the error is not included in
* traces or error statistics.
*/
includeErrors?: SendErrorsOptions;
/**
* This option is for internal use by `@apollo/server` only.
*
* By default we want to enable this plugin for subgraph schemas only, but we
* need to come up with our list of plugins before we have necessarily loaded
* the schema. So (unless the user installs this plugin or
* ApolloServerPluginInlineTraceDisabled themselves), `@apollo/server` always
* installs this plugin and uses this option to make sure traces are only
* included if the schema appears to be a subgraph.
*/
__onlyIfSchemaIsSubgraph?: boolean;
}
// This ftv1 plugin produces a base64'd Trace protobuf containing only the
// durationNs, startTime, endTime, and root fields. This output is placed
// on the `extensions`.`ftv1` property of the response. The Apollo Gateway
// utilizes this data to construct the full trace and submit it to Apollo's
// usage reporting ingress.
export function ApolloServerPluginInlineTrace(
options: ApolloServerPluginInlineTraceOptions = Object.create(null),
): ApolloServerPlugin {
let enabled: boolean | null = options.__onlyIfSchemaIsSubgraph ? null : true;
return internalPlugin({
__internal_plugin_id__: 'InlineTrace',
__is_disabled_plugin__: false,
async serverWillStart({ schema, logger }) {
// Handle the case that the plugin was implicitly installed. We only want it
// to actually be active if the schema appears to be federated. If you don't
// like the log line, just install `ApolloServerPluginInlineTrace()` in
// `plugins` yourself.
if (enabled === null) {
enabled = schemaIsSubgraph(schema);
if (enabled) {
logger.info(
'Enabling inline tracing for this subgraph. To disable, use ' +
'ApolloServerPluginInlineTraceDisabled.',
);
}
}
},
async requestDidStart({ request: { http }, metrics }) {
if (!enabled) {
return;
}
const treeBuilder = new TraceTreeBuilder({
maskedBy: 'ApolloServerPluginInlineTrace',
sendErrors: options.includeErrors,
});
// XXX Provide a mechanism to customize this logic.
if (http?.headers.get('apollo-federation-include-trace') !== 'ftv1') {
return;
}
// If some other (user-written?) plugin already decided that we are not
// capturing traces, then we should not capture traces.
if (metrics.captureTraces === false) {
return;
}
// Note that this will override any `fieldLevelInstrumentation` parameter
// to the usage reporting plugin for requests with the
// `apollo-federation-include-trace` header set.
metrics.captureTraces = true;
treeBuilder.startTiming();
return {
async executionDidStart() {
return {
willResolveField({ info }) {
return treeBuilder.willResolveField(info);
},
};
},
async didEncounterErrors({ errors }) {
treeBuilder.didEncounterErrors(errors);
},
async willSendResponse({ response }) {
// We record the end time at the latest possible time: right before serializing the trace.
// If we wait any longer, the time we record won't actually be sent anywhere!
treeBuilder.stopTiming();
// For now, we don't support inline traces on incremental delivery
// responses. (We could perhaps place the trace on the final chunk, or
// even deliver it bit by bit. For now, since Gateway does not support
// incremental delivery and Router does not pass through defers to
// subgraphs, this doesn't affect the "federated tracing" use case,
// though it does affect the ability to look at inline traces in other
// tools like Explorer.
if (response.body.kind === 'incremental') {
return;
}
// If we're in a gateway, include the query plan (and subgraph traces)
// in the inline trace. This is designed more for manually querying
// your graph while running locally to see what the query planner is
// doing rather than for running in production.
if (metrics.queryPlanTrace) {
treeBuilder.trace.queryPlan = metrics.queryPlanTrace;
}
const encodedUint8Array = Trace.encode(treeBuilder.trace).finish();
const encodedBuffer = Buffer.from(
encodedUint8Array,
encodedUint8Array.byteOffset,
encodedUint8Array.byteLength,
);
const extensions =
response.body.singleResult.extensions ||
(response.body.singleResult.extensions = Object.create(null));
// This should only happen if another plugin is using the same name-
// space within the `extensions` object and got to it before us.
if (typeof extensions.ftv1 !== 'undefined') {
throw new Error('The `ftv1` extension was already present.');
}
extensions.ftv1 = encodedBuffer.toString('base64');
},
};
},
});
}
``` | /content/code_sandbox/packages/server/src/plugin/inlineTrace/index.ts | xml | 2016-04-21T09:26:01 | 2024-08-16T19:32:15 | apollo-server | apollographql/apollo-server | 13,742 | 1,429 |
```xml
import fs from 'fs';
import path from 'path';
import { BabelFileResult, transformAsync } from '@babel/core';
import * as glob from 'glob';
import { logger } from 'just-scripts';
const EOL_REGEX = /\r?\n/g;
function addSourceMappingUrl(code: string, loc: string): string {
// Babel keeps stripping this comment, even when correct option is set. Adding manually.
return code + '\n//# sourceMappingURL=' + path.basename(loc);
}
export async function babel() {
const files = glob.sync('lib/**/*.styles.js');
for (const filename of files) {
const filePath = path.resolve(process.cwd(), filename);
const codeBuffer = await fs.promises.readFile(filePath);
const sourceCode = codeBuffer.toString().replace(EOL_REGEX, '\n');
const result = (await transformAsync(sourceCode, {
ast: false,
sourceMaps: true,
babelrc: true,
// to avoid leaking of global configs
babelrcRoots: [process.cwd()],
caller: { name: 'just-scripts' },
filename: filePath,
sourceFileName: path.basename(filename),
})) /* Bad `transformAsync` types. it can be null only if 2nd param is null(config)*/ as NonNullableRecord<BabelFileResult>;
const resultCode = addSourceMappingUrl(result.code, path.basename(filename) + '.map');
if (resultCode === sourceCode) {
logger.verbose(`babel: skipped ${filePath}`);
continue;
} else {
logger.verbose(`babel: transformed ${filePath}`);
}
const sourceMapFile = filePath + '.map';
await fs.promises.writeFile(filePath, resultCode);
await fs.promises.writeFile(sourceMapFile, JSON.stringify(result.map));
}
}
type NonNullableRecord<T> = {
[P in keyof T]-?: NonNullable<T[P]>;
};
``` | /content/code_sandbox/scripts/tasks/src/babel.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 398 |
```xml
export * from './RatingItem';
export * from './RatingItem.types';
export * from './renderRatingItem';
export * from './useRatingItem';
export * from './useRatingItemStyles.styles';
``` | /content/code_sandbox/packages/react-components/react-rating/library/src/components/RatingItem/index.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 42 |
```xml
import {
CreateDecryptedItemFromPayload,
DecryptedPayload,
DecryptedTransferPayload,
FillItemContentSpecialized,
KeySystemIdentifier,
KeySystemItemsKeyContentSpecialized,
KeySystemItemsKeyInterface,
PayloadTimestampDefaults,
ProtocolVersion,
} from '@standardnotes/models'
import { PureCryptoInterface } from '@standardnotes/sncrypto-common'
import { V004Algorithm } from '../../../../Algorithm'
import { ContentType } from '@standardnotes/domain-core'
export class CreateKeySystemItemsKeyUseCase {
constructor(private readonly crypto: PureCryptoInterface) {}
execute(dto: {
uuid: string
keySystemIdentifier: KeySystemIdentifier
sharedVaultUuid: string | undefined
rootKeyToken: string
}): KeySystemItemsKeyInterface {
const key = this.crypto.generateRandomKey(V004Algorithm.EncryptionKeyLength)
const content = FillItemContentSpecialized<KeySystemItemsKeyContentSpecialized>({
itemsKey: key,
creationTimestamp: new Date().getTime(),
version: ProtocolVersion.V004,
rootKeyToken: dto.rootKeyToken,
})
const transferPayload: DecryptedTransferPayload = {
uuid: dto.uuid,
content_type: ContentType.TYPES.KeySystemItemsKey,
key_system_identifier: dto.keySystemIdentifier,
shared_vault_uuid: dto.sharedVaultUuid,
content: content,
dirty: true,
...PayloadTimestampDefaults(),
}
const payload = new DecryptedPayload(transferPayload)
return CreateDecryptedItemFromPayload(payload)
}
}
``` | /content/code_sandbox/packages/encryption/src/Domain/Operator/004/UseCase/KeySystem/CreateKeySystemItemsKey.ts | xml | 2016-12-05T23:31:33 | 2024-08-16T06:51:19 | app | standardnotes/app | 5,180 | 328 |
```xml
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Location, LocationStrategy, HashLocationStrategy } from '@angular/common';
import * as shape from 'd3-shape';
import * as d3Array from 'd3-array';
import { Color, colorSets } from '@swimlane/ngx-charts/utils/color-sets';
import { formatLabel, escapeLabel } from '@swimlane/ngx-charts/common/label.helper';
import {
single,
multi,
boxData,
bubble,
sankeyData,
generateData,
generateGraph,
treemap,
timelineFilterBarData,
fiscalYearReport
} from './data';
import { bubbleDemoData } from './custom-charts/bubble-chart-interactive/data';
import { BubbleChartInteractiveServerDataModel } from './custom-charts/bubble-chart-interactive/models';
import { data as countries } from 'emoji-flags';
import chartGroups from './chartTypes';
import { barChart, lineChartSeries } from './combo-chart-data';
import pkg from '../../projects/swimlane/ngx-charts/package.json';
import { InputTypes } from '@swimlane/ngx-ui';
import { LegendPosition } from '@swimlane/ngx-charts/common/types/legend.model';
import { ScaleType } from '@swimlane/ngx-charts/common/types/scale-type.enum';
const monthName = new Intl.DateTimeFormat('en-us', { month: 'short' });
const weekdayName = new Intl.DateTimeFormat('en-us', { weekday: 'short' });
function multiFormat(value) {
if (value < 1000) return `${value.toFixed(2)}ms`;
value /= 1000;
if (value < 60) return `${value.toFixed(2)}s`;
value /= 60;
if (value < 60) return `${value.toFixed(2)}mins`;
value /= 60;
return `${value.toFixed(2)}hrs`;
}
const getRandomInt = (min: number, max: number) => {
return Math.floor(Math.random() * (max - min + 1) + min);
};
@Component({
selector: 'app-root',
providers: [Location, { provide: LocationStrategy, useClass: HashLocationStrategy }],
encapsulation: ViewEncapsulation.None,
styleUrls: ['../../node_modules/@swimlane/ngx-ui/index.css', './app.component.scss'],
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
APP_VERSION = pkg.version;
inputTypes = InputTypes;
theme = 'dark';
chartType: string;
chartGroups: any[];
chart: any;
realTimeData: boolean = false;
countries: any[];
single: any[];
multi: any[];
fiscalYearReport: any[];
dateData: any[];
dateDataWithRange: any[];
calendarData: any[];
statusData: any[];
sparklineData: any[];
timelineFilterBarData: any[];
graph: { links: any[]; nodes: any[] };
bubble: any;
linearScale: boolean = false;
range: boolean = false;
view: [number, number];
width: number = 700;
height: number = 300;
fitContainer: boolean = false;
// options
showXAxis = true;
showYAxis = true;
gradient = false;
showLegend = true;
legendTitle = 'Legend';
legendPosition = LegendPosition.Right;
showXAxisLabel = true;
tooltipDisabled = false;
showText = true;
xAxisLabel = 'Country';
showYAxisLabel = true;
yAxisLabel = 'GDP Per Capita';
showGridLines = true;
innerPadding = '10%';
barPadding = 8;
groupPadding = 16;
roundDomains = false;
maxRadius = 10;
minRadius = 3;
showSeriesOnHover = true;
roundEdges: boolean = true;
animations: boolean = true;
xScaleMin: any;
xScaleMax: any;
yScaleMin: number;
yScaleMax: number;
showDataLabel: boolean = false;
noBarWhenZero: boolean = true;
trimXAxisTicks: boolean = true;
trimYAxisTicks: boolean = true;
rotateXAxisTicks: boolean = true;
maxXAxisTickLength: number = 16;
maxYAxisTickLength: number = 16;
strokeColor: string = '#FFFFFF';
strokeWidth: number = 2;
wrapTicks = false;
curves = {
Basis: shape.curveBasis,
'Basis Closed': shape.curveBasisClosed,
Bundle: shape.curveBundle.beta(1),
Cardinal: shape.curveCardinal,
'Cardinal Closed': shape.curveCardinalClosed,
'Catmull Rom': shape.curveCatmullRom,
'Catmull Rom Closed': shape.curveCatmullRomClosed,
Linear: shape.curveLinear,
'Linear Closed': shape.curveLinearClosed,
'Monotone X': shape.curveMonotoneX,
'Monotone Y': shape.curveMonotoneY,
Natural: shape.curveNatural,
Step: shape.curveStep,
'Step After': shape.curveStepAfter,
'Step Before': shape.curveStepBefore,
default: shape.curveLinear
};
// line interpolation
curveType: string = 'Linear';
curve: any = this.curves[this.curveType];
interpolationTypes = [
'Basis',
'Bundle',
'Cardinal',
'Catmull Rom',
'Linear',
'Monotone X',
'Monotone Y',
'Natural',
'Step',
'Step After',
'Step Before'
];
closedCurveType: string = 'Linear Closed';
closedCurve: any = this.curves[this.closedCurveType];
closedInterpolationTypes = ['Basis Closed', 'Cardinal Closed', 'Catmull Rom Closed', 'Linear Closed'];
colorSets: any;
colorScheme: any;
schemeType = ScaleType.Ordinal;
selectedColorScheme: string;
rangeFillOpacity: number = 0.15;
// Override colors for certain values
customColors: any[] = [
{
name: 'Germany',
value: '#a8385d'
}
];
// pie
showLabels = true;
explodeSlices = false;
doughnut = false;
arcWidth = 0.25;
// line, area
autoScale = true;
timeline = false;
// margin
margin: boolean = false;
marginTop: number = 40;
marginRight: number = 40;
marginBottom: number = 40;
marginLeft: number = 40;
// box
boxData = boxData;
// sankey
sankeyData = sankeyData;
// gauge
gaugeMin: number = 0;
gaugeMax: number = 100;
gaugeLargeSegments: number = 10;
gaugeSmallSegments: number = 5;
gaugeTextValue: string = '';
gaugeUnits: string = 'alerts';
gaugeAngleSpan: number = 240;
gaugeStartAngle: number = -120;
gaugeShowAxis: boolean = true;
gaugeValue: number = 50; // linear gauge value
gaugePreviousValue: number = 70;
// heatmap
heatmapMin: number = 0;
heatmapMax: number = 50000;
// Combo Chart
barChart: any[] = barChart;
lineChartSeries: any[] = lineChartSeries;
lineChartScheme: Color = {
name: 'coolthree',
selectable: true,
group: ScaleType.Ordinal,
domain: ['#01579b', '#7aa3e5', '#a8385d', '#00bfa5']
};
comboBarScheme: Color = {
name: 'singleLightBlue',
selectable: true,
group: ScaleType.Ordinal,
domain: ['#01579b']
};
showRightYAxisLabel: boolean = true;
yAxisLabelRight: string = 'Utilization';
// demos
totalSales = 0;
salePrice = 100;
personnelCost = 100;
mathText = '3 - 1.5*sin(x) + cos(2*x) - 1.5*abs(cos(x))';
mathFunction: (o: any) => any;
treemap: any[];
treemapPath: any[] = [];
sumBy: string = 'Size';
// bubble chart interactive demo
bubbleDemoTempData: any[] = [];
bubbleDemoChart: BubbleChartInteractiveServerDataModel;
// Reference lines
showRefLines: boolean = true;
showRefLabels: boolean = true;
// Supports any number of reference lines.
refLines = [
{ value: 42500, name: 'Maximum' },
{ value: 37750, name: 'Average' },
{ value: 33000, name: 'Minimum' }
];
// data
plotData: any;
// Sidebar Controls:
colorVisible: boolean = true;
dataVisible: boolean = true;
dimVisible: boolean = true;
optsVisible: boolean = true;
constructor(public location: Location) {
this.mathFunction = this.getFunction();
Object.assign(this, {
single,
multi,
countries,
chartGroups,
colorSets,
graph: generateGraph(50),
boxData,
bubble,
plotData: this.generatePlotData(),
treemap,
bubbleDemoData,
fiscalYearReport
});
// interactive drill down demos
this.treemapProcess();
this.bubbleDemoChart = new BubbleChartInteractiveServerDataModel();
this.bubbleDemoProcess(bubbleDemoData[0]);
this.dateData = generateData(5, false);
this.dateDataWithRange = generateData(2, true);
this.setColorScheme('cool');
this.calendarData = this.getCalendarData();
this.statusData = this.getStatusData();
this.sparklineData = generateData(1, false, 30);
this.timelineFilterBarData = timelineFilterBarData();
}
get dateDataWithOrWithoutRange() {
if (this.range) {
return this.dateDataWithRange;
} else {
return this.dateData;
}
}
ngOnInit() {
const state = this.location.path(true);
this.selectChart(state.length ? state : 'bar-vertical');
setInterval(this.updateData.bind(this), 1000);
if (!this.fitContainer) {
this.applyDimensions();
}
}
updateData() {
if (!this.realTimeData) {
return;
}
this.gaugeValue = this.gaugeMin + Math.floor(Math.random() * (this.gaugeMax - this.gaugeMin));
const country = this.countries[Math.floor(Math.random() * this.countries.length)];
const add = Math.random() < 0.7;
const remove = Math.random() < 0.5;
if (remove) {
if (this.single.length > 1) {
const index = Math.floor(Math.random() * this.single.length);
this.single.splice(index, 1);
this.single = [...this.single];
}
if (this.multi.length > 1) {
const index = Math.floor(Math.random() * this.multi.length);
this.multi.splice(index, 1);
this.multi = [...this.multi];
}
if (this.bubble.length > 1) {
const index = Math.floor(Math.random() * this.bubble.length);
this.bubble.splice(index, 1);
this.bubble = [...this.bubble];
}
if (this.graph.nodes.length > 1) {
const index = Math.floor(Math.random() * this.graph.nodes.length);
const value = this.graph.nodes[index].value;
this.graph.nodes.splice(index, 1);
const nodes = [...this.graph.nodes];
const links = this.graph.links.filter(link => {
return (
link.source !== value && link.source.value !== value && link.target !== value && link.target.value !== value
);
});
this.graph = { links, nodes };
}
if (this.boxData.length > 1) {
const index = Math.floor(Math.random() * this.boxData.length);
this.boxData.splice(index, 1);
this.boxData = [...this.boxData];
}
}
if (add) {
// single
const entry = {
name: country.name,
value: Math.floor(10000 + Math.random() * 50000)
};
this.single = [...this.single, entry];
// multi
const multiEntry = {
name: country.name,
series: [
{
name: '1990',
value: Math.floor(10000 + Math.random() * 50000)
},
{
name: '2000',
value: Math.floor(10000 + Math.random() * 50000)
},
{
name: '2010',
value: Math.floor(10000 + Math.random() * 50000)
}
]
};
this.multi = [...this.multi, multiEntry];
// graph
const node = { value: country.name };
const nodes = [...this.graph.nodes, node];
const link = {
source: country.name,
target: nodes[Math.floor(Math.random() * (nodes.length - 1))].value
};
const links = [...this.graph.links, link];
this.graph = { links, nodes };
// bubble
const bubbleYear = Math.floor((2010 - 1990) * Math.random() + 1990);
const bubbleEntry = {
name: country.name,
series: [
{
name: '' + bubbleYear,
x: new Date(bubbleYear, 0, 1),
y: Math.floor(30 + Math.random() * 70),
r: Math.floor(30 + Math.random() * 20)
}
]
};
this.bubble = [...this.bubble, bubbleEntry];
// box
const boxEntry = {
name: country.name,
series: [
{
name: '1990',
value: getRandomInt(10, 5)
},
{
name: '2000',
value: getRandomInt(15, 5)
},
{
name: '2010',
value: getRandomInt(20, 10)
},
{
name: '2020',
value: getRandomInt(30, 10)
},
{
name: '2030',
value: getRandomInt(50, 20)
}
]
};
const index = this.boxData.findIndex(box => box.name === country.name);
if (index > -1) {
this.boxData[index] = boxEntry;
} else {
this.boxData = [...this.boxData, boxEntry];
}
// bubble interactive demo
this.bubbleDemoProcess(bubbleDemoData[getRandomInt(0, bubbleDemoData.length - 1)]);
this.statusData = this.getStatusData();
this.timelineFilterBarData = timelineFilterBarData();
}
const date = new Date(Math.floor(1473700105009 + Math.random() * 1000000000));
for (const series of this.dateData) {
series.series.push({
name: date,
value: Math.floor(2000 + Math.random() * 5000)
});
}
this.dateData = [...this.dateData];
this.dateDataWithRange = generateData(2, true);
if (this.chart.inputFormat === 'calendarData') this.calendarData = this.getCalendarData();
}
applyDimensions() {
this.view = [this.width, this.height];
}
toggleFitContainer() {
if (this.fitContainer) {
this.view = undefined;
} else {
this.applyDimensions();
}
}
selectChart(chartSelector) {
this.chartType = chartSelector = chartSelector.replace('/', '');
this.location.replaceState(this.chartType);
for (const group of this.chartGroups) {
this.chart = group.charts.find(x => x.selector === chartSelector);
if (this.chart) break;
}
this.linearScale = false;
this.yAxisLabel = 'GDP Per Capita';
this.xAxisLabel = 'Country';
this.width = 700;
this.height = 300;
Object.assign(this, this.chart.defaults);
if (!this.fitContainer) {
this.applyDimensions();
}
}
changeTheme(theme: string) {
this.theme = theme;
if (theme === 'light') {
this.strokeColor = '#000000';
} else {
this.strokeColor = '#FFFFFF';
}
}
select(data) {
console.log('Item clicked', JSON.parse(JSON.stringify(data)));
}
activate(data) {
console.log('Activate', JSON.parse(JSON.stringify(data)));
}
deactivate(data) {
console.log('Deactivate', JSON.parse(JSON.stringify(data)));
}
getInterpolationType(curveType) {
return this.curves[curveType] || this.curves['default'];
}
setColorScheme(name) {
this.selectedColorScheme = name;
this.colorScheme = this.colorSets.find(s => s.name === name);
}
onLegendLabelClick(entry) {
console.log('Legend clicked', entry);
}
getCalendarData(): any[] {
// today
const now = new Date();
const todaysDay = now.getDate();
const thisDay = new Date(now.getFullYear(), now.getMonth(), todaysDay);
// Monday
const thisMonday = new Date(thisDay.getFullYear(), thisDay.getMonth(), todaysDay - thisDay.getDay() + 1);
const thisMondayDay = thisMonday.getDate();
const thisMondayYear = thisMonday.getFullYear();
const thisMondayMonth = thisMonday.getMonth();
// 52 weeks before monday
const calendarData = [];
const getDate = d => new Date(thisMondayYear, thisMondayMonth, d);
for (let week = -52; week <= 0; week++) {
const mondayDay = thisMondayDay + week * 7;
const monday = getDate(mondayDay);
// one week
const series = [];
for (let dayOfWeek = 7; dayOfWeek > 0; dayOfWeek--) {
const date = getDate(mondayDay - 1 + dayOfWeek);
// skip future dates
if (date > now) {
continue;
}
// value
const value = dayOfWeek < 6 ? date.getMonth() + 1 : 0;
series.push({
date,
name: weekdayName.format(date),
value
});
}
calendarData.push({
name: monday.toString(),
series
});
}
return calendarData;
}
calendarAxisTickFormatting(mondayString: string) {
const monday = new Date(mondayString);
const month = monday.getMonth();
const day = monday.getDate();
const year = monday.getFullYear();
const lastSunday = new Date(year, month, day - 1);
const nextSunday = new Date(year, month, day + 6);
return lastSunday.getMonth() !== nextSunday.getMonth() ? monthName.format(nextSunday) : '';
}
calendarTooltipText(c): string {
return `
<span class="tooltip-label">${c.label} ${c.cell.date.toLocaleDateString()}</span>
<span class="tooltip-val">${c.data.toLocaleString()}</span>
`;
}
pieTooltipText({ data }) {
const label = formatLabel(data.name);
const val = formatLabel(data.value);
return `
<span class="tooltip-label">${escapeLabel(label)}</span>
<span class="tooltip-val">$${val}</span>
`;
}
dollarValueFormat(c): string {
return `$${c.value.toLocaleString()}`;
}
getStatusData() {
const sales = Math.round(1e4 * Math.random());
const dur = 36e5 * Math.random();
return this.calcStatusData(sales, dur);
}
calcStatusData(sales = this.statusData[0].value, dur = this.statusData[2].value) {
const ret = sales * this.salePrice;
const cost = ((sales * dur) / 60 / 60 / 1000) * this.personnelCost;
const ROI = (ret - cost) / cost;
return [
{
name: 'Sales',
value: sales
},
{
name: 'Gross',
value: ret,
extra: { format: 'currency' }
},
{
name: 'Avg. Time',
value: dur,
extra: { format: 'time' }
},
{
name: 'Cost',
value: cost,
extra: { format: 'currency' }
},
{
name: 'ROI',
value: ROI,
extra: { format: 'percent' }
}
];
}
statusValueFormat(c): string {
switch (c.data.extra ? c.data.extra.format : '') {
case 'currency':
return `$${Math.round(c.value).toLocaleString()}`;
case 'time':
return multiFormat(c.value);
case 'percent':
return `${Math.round(c.value * 100)}%`;
default:
return c.value.toLocaleString();
}
}
valueFormatting(value: number): string {
return `${Math.round(value).toLocaleString()} `;
}
currencyFormatting(value: number) {
return `$${Math.round(value).toLocaleString()}`;
}
gdpLabelFormatting(c) {
return `${escapeLabel(c.label)}<br/><small class="number-card-label">GDP Per Capita</small>`;
}
statusLabelFormat(c): string {
return `${c.label}<br/><small class="number-card-label">This week</small>`;
}
generatePlotData() {
if (!this.mathFunction) {
return [];
}
const twoPi = 2 * Math.PI;
const length = 25;
const series = Array({ length }).map((d, i) => {
const x = i / (length - 1);
const t = x * twoPi;
return {
name: ~~(x * 360),
value: this.mathFunction(t)
};
});
return [
{
name: this.mathText,
series
}
];
}
getFunction(text = this.mathText) {
try {
text = `with (Math) { return ${this.mathText} }`;
// tslint:disable-next-line: function-constructor
const fn = new Function('x', text).bind(Math); // tslint:disable-line: tsr-detect-eval-with-expression
return typeof fn(1) === 'number' ? fn : null;
} catch (err) {
return null;
}
}
treemapProcess(sumBy = this.sumBy) {
this.sumBy = sumBy;
const children = treemap[0];
const value = sumBy === 'Size' ? sumChildren(children) : countChildren(children);
this.treemap = [children];
this.treemapPath = [{ name: 'Top', children: [children], value }];
function sumChildren(node) {
return (node.value = node.size || d3Array.sum(node.children, sumChildren));
}
function countChildren(node) {
return (node.value = node.children ? d3Array.sum(node.children, countChildren) : 1);
}
}
treemapSelect(item) {
if (item.children) {
const idx = this.treemapPath.indexOf(item);
this.treemapPath.splice(idx + 1);
this.treemap = this.treemapPath[idx].children;
return;
}
const node = this.treemap.find(d => d.name === item.name);
if (node.children) {
this.treemapPath.push(node);
this.treemap = node.children;
}
}
getFlag(country) {
return this.countries.find(c => c.name === country).emoji;
}
onFilter(event) {
console.log('timeline filter', event);
}
/*
**
Combo Chart
**
[yLeftAxisScaleFactor]="yLeftAxisScale" and [yRightAxisScaleFactor]="yRightAxisScale"
exposes the left and right min and max axis values for custom scaling, it is probably best to
scale one axis in relation to the other axis but for flexibility to scale either the left or
right axis both were exposed.
**
*/
yLeftAxisScale(min, max) {
return { min: `${min}`, max: `${max}` };
}
yRightAxisScale(min, max) {
return { min: `${min}`, max: `${max}` };
}
yLeftTickFormat(data) {
return `${data.toLocaleString()}`;
}
yRightTickFormat(data) {
return `${data}%`;
}
/*
**
End of Combo Chart
**
*/
onSelect(event) {
console.log(event);
}
dblclick(event) {
console.log('Double click', event);
}
/*
**
Bubble Chart Interactive Demo
**
*/
bubbleDemoProcess(dataFromServer) {
this.bubbleDemoChart.setDataFromServer(dataFromServer);
this.bubbleDemoTempData = this.bubbleDemoChart.toChart();
}
getBubbleInteractiveTitle() {
return this.bubbleDemoChart.getChartTitle();
}
bubbleShowDrillDownResetLink() {
return this.bubbleDemoChart.getDrilldownDepth() > 0;
}
onClickResetBubbleInteractiveDrill() {
this.bubbleDemoChart.resetDrilldown();
this.bubbleDemoTempData = this.bubbleDemoChart.toChart();
}
onSelectBubbleInteractivePoint(event) {
this.bubbleDemoChart.drilldown(event);
this.bubbleDemoTempData = this.bubbleDemoChart.toChart();
}
}
``` | /content/code_sandbox/src/app/app.component.ts | xml | 2016-07-22T15:58:41 | 2024-08-02T15:56:24 | ngx-charts | swimlane/ngx-charts | 4,284 | 5,681 |
```xml
import { observer } from 'mobx-react-lite'
import { FunctionComponent, useRef } from 'react'
import { UpgradePrompt } from '../PremiumFeaturesModal/Subviews/UpgradePrompt'
import { useApplication } from '../ApplicationProvider'
export const PreferencesPremiumOverlay: FunctionComponent = () => {
const ctaButtonRef = useRef<HTMLButtonElement>(null)
const application = useApplication()
const hasSubscription = application.hasValidFirstPartySubscription()
const onClick = () => {
application.preferencesController.closePreferences()
}
return (
<div className="absolute bottom-0 left-0 right-0 top-0 flex flex-col items-center justify-center">
<div className="absolute h-full w-full bg-default opacity-[86%]"></div>
<div className="border-1 z-10 rounded border border-border bg-default p-5">
<UpgradePrompt
featureName={'Plugin Gallery'}
ctaRef={ctaButtonRef}
application={application}
hasSubscription={hasSubscription}
inline={true}
onClick={onClick}
/>
</div>
</div>
)
}
export default observer(PreferencesPremiumOverlay)
``` | /content/code_sandbox/packages/web/src/javascripts/Components/Preferences/PremiumOverlay.tsx | xml | 2016-12-05T23:31:33 | 2024-08-16T06:51:19 | app | standardnotes/app | 5,180 | 243 |
```xml
import * as React from 'react';
import { StyleSheet } from 'react-native';
import type { StackNavigationProp } from '@react-navigation/stack';
import { List, PaperProvider, Banner } from 'react-native-paper';
import ScreenWrapper from '../ScreenWrapper';
type Props = {
navigation: StackNavigationProp<{ [key: string]: undefined }>;
};
const ThemeExample = ({ navigation }: Props) => {
return (
<PaperProvider>
<ScreenWrapper contentContainerStyle={styles.container}>
<Banner visible>
React Native Paper automatically adapts theme based on system
preferences. Please change system theme to dark/light to see the
effect
</Banner>
<List.Section title={`Theme based on the source color`}>
<List.Item
title="Themed Sport App"
description="Go to the example"
onPress={() => navigation.navigate('teamsList')}
right={(props) => <List.Icon {...props} icon="arrow-right" />}
/>
</List.Section>
</ScreenWrapper>
</PaperProvider>
);
};
ThemeExample.title = 'Theme';
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default ThemeExample;
``` | /content/code_sandbox/example/src/Examples/ThemeExample.tsx | xml | 2016-10-19T05:56:53 | 2024-08-16T08:48:04 | react-native-paper | callstack/react-native-paper | 12,646 | 257 |
```xml
export class ListItem {
public Title: string;
public Description:string;
public ImageUrl: string;
}
``` | /content/code_sandbox/samples/react-slide-swiper/src/webparts/reactSlideSwiper/services/ListItem.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 24 |
```xml
import ParserHtml from '../../../../src/parser/model/ParserHtml';
import ParserCss from '../../../../src/parser/model/ParserCss';
import DomComponents from '../../../../src/dom_components';
import Editor from '../../../../src/editor/model/Editor';
import { CSS_BG_OBJ, CSS_BG_STR } from './ParserCss';
describe('ParserHtml', () => {
let obj: ReturnType<typeof ParserHtml>;
beforeEach(() => {
const em = new Editor({});
const dom = new DomComponents(em);
obj = ParserHtml(em, {
textTags: ['br', 'b', 'i', 'u'],
textTypes: ['text', 'textnode', 'comment'],
returnArray: true,
});
obj.compTypes = dom.componentTypes;
});
test('Simple div node', () => {
const str = '<div></div>';
const result = [{ tagName: 'div' }];
expect(obj.parse(str).html).toEqual(result);
});
test('Simple article node', () => {
const str = '<article></article>';
const result = [{ tagName: 'article' }];
expect(obj.parse(str).html).toEqual(result);
});
test('Node with attributes', () => {
const str = '<div id="test1" class="test2 test3" data-one="test4" strange="test5"></div>';
const result = [
{
tagName: 'div',
classes: ['test2', 'test3'],
attributes: {
'data-one': 'test4',
id: 'test1',
strange: 'test5',
},
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse style string to object', () => {
const str = 'color:black; width:100px; test:value;';
const result = {
color: 'black',
width: '100px',
test: 'value',
};
expect(obj.parseStyle(str)).toEqual(result);
});
test('Parse style string with values containing colon to object', () => {
const str = 'background-image:url("path_to_url"); test:value;';
const result = {
'background-image': 'url("path_to_url")',
test: 'value',
};
expect(obj.parseStyle(str)).toEqual(result);
});
test('Parse style with multiple values of the same key', () => {
expect(obj.parseStyle(CSS_BG_STR)).toEqual(CSS_BG_OBJ);
});
test('Parse style with comments', () => {
expect(obj.parseStyle('/* color #ffffff; */ width: 100px;')).toEqual({
width: '100px',
});
});
test('Parse class string to array', () => {
const str = 'test1 test2 test3 test-4';
const result = ['test1', 'test2', 'test3', 'test-4'];
expect(obj.parseClass(str)).toEqual(result);
});
test('Parse class string to array with special classes', () => {
const str = 'test1 test2 test3 test-4 gjs-test';
const result = ['test1', 'test2', 'test3', 'test-4', 'gjs-test'];
expect(obj.parseClass(str)).toEqual(result);
});
test('Style attribute is isolated', () => {
const str = '<div id="test1" style="color:black; width:100px; test:value;"></div>';
const result = [
{
tagName: 'div',
attributes: { id: 'test1' },
style: {
color: 'black',
width: '100px',
test: 'value',
},
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Class attribute is isolated', () => {
const str = '<div id="test1" class="test2 test3 test4"></div>';
const result = [
{
tagName: 'div',
attributes: { id: 'test1' },
classes: ['test2', 'test3', 'test4'],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse images nodes', () => {
const str = '<img id="test1" src="./index.html"/>';
const result = [
{
tagName: 'img',
type: 'image',
attributes: {
id: 'test1',
src: './index.html',
},
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse text nodes', () => {
const str = '<div id="test1">test2 </div>';
const result = [
{
tagName: 'div',
attributes: { id: 'test1' },
type: 'text',
components: { type: 'textnode', content: 'test2 ' },
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse text with few text tags', () => {
const str = '<div id="test1"><br/> test2 <br/> a b <b>b</b> <i>i</i> <u>u</u> test </div>';
const result = [
{
tagName: 'div',
attributes: { id: 'test1' },
type: 'text',
components: [
{ tagName: 'br' },
{
content: ' test2 ',
type: 'textnode',
tagName: '',
},
{ tagName: 'br' },
{
content: ' a b ',
type: 'textnode',
tagName: '',
},
{
components: { type: 'textnode', content: 'b' },
type: 'text',
tagName: 'b',
},
{
content: ' ',
type: 'textnode',
tagName: '',
},
{
components: { type: 'textnode', content: 'i' },
tagName: 'i',
type: 'text',
},
{
content: ' ',
type: 'textnode',
tagName: '',
},
{
components: { type: 'textnode', content: 'u' },
tagName: 'u',
type: 'text',
},
{
content: ' test ',
type: 'textnode',
tagName: '',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse text with few text tags and nested node', () => {
const str = '<div id="test1">a b <b>b</b> <i>i</i>c <div>ABC</div> <i>i</i> <u>u</u> test </div>';
const result = [
{
tagName: 'div',
attributes: { id: 'test1' },
type: 'text',
components: [
{
content: 'a b ',
type: 'textnode',
tagName: '',
},
{
components: { type: 'textnode', content: 'b' },
tagName: 'b',
type: 'text',
},
{
content: ' ',
type: 'textnode',
tagName: '',
},
{
components: { type: 'textnode', content: 'i' },
tagName: 'i',
type: 'text',
},
{
content: 'c ',
type: 'textnode',
tagName: '',
},
{
tagName: 'div',
type: 'text',
components: { type: 'textnode', content: 'ABC' },
},
{
content: ' ',
type: 'textnode',
tagName: '',
},
{
components: { type: 'textnode', content: 'i' },
tagName: 'i',
type: 'text',
},
{
content: ' ',
type: 'textnode',
tagName: '',
},
{
components: { type: 'textnode', content: 'u' },
tagName: 'u',
type: 'text',
},
{
content: ' test ',
type: 'textnode',
tagName: '',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse text with few text tags and comment', () => {
const str = '<div id="test1">Some text <br/><!-- comment --><b>Bold</b></div>';
const result = [
{
tagName: 'div',
attributes: { id: 'test1' },
type: 'text',
components: [
{
content: 'Some text ',
type: 'textnode',
tagName: '',
},
{ tagName: 'br' },
{
content: ' comment ',
type: 'comment',
tagName: '',
},
{
components: { type: 'textnode', content: 'Bold' },
type: 'text',
tagName: 'b',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse nested nodes', () => {
const str =
'<article id="test1"> <div></div> <footer id="test2"></footer> Text mid <div id="last"></div></article>';
const result = [
{
tagName: 'article',
attributes: { id: 'test1' },
components: [
{
tagName: 'div',
},
{
content: ' ',
type: 'textnode',
tagName: '',
},
{
tagName: 'footer',
attributes: { id: 'test2' },
},
{
tagName: '',
type: 'textnode',
content: ' Text mid ',
},
{
tagName: 'div',
attributes: { id: 'last' },
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse nested text nodes', () => {
const str = '<div>content1 <div>nested</div> content2</div>';
const result = [
{
tagName: 'div',
type: 'text',
components: [
{
tagName: '',
type: 'textnode',
content: 'content1 ',
},
{
tagName: 'div',
type: 'text',
components: { type: 'textnode', content: 'nested' },
},
{
tagName: '',
type: 'textnode',
content: ' content2',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse nested span text nodes', () => {
const str = '<div>content1 <div><span>nested</span></div> content2</div>';
const result = [
{
tagName: 'div',
components: [
{
tagName: '',
type: 'textnode',
content: 'content1 ',
},
{
tagName: 'div',
components: [
{
tagName: 'span',
type: 'text',
components: { type: 'textnode', content: 'nested' },
},
],
},
{
tagName: '',
type: 'textnode',
content: ' content2',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse multiple nodes', () => {
const str = '<div></div><div></div>';
const result = [{ tagName: 'div' }, { tagName: 'div' }];
expect(obj.parse(str).html).toEqual(result);
});
test('Remove script tags', () => {
const str = '<div><script>const test;</script></div><div></div><script>const test2;</script>';
const result = [{ tagName: 'div' }, { tagName: 'div' }];
expect(obj.parse(str).html).toEqual(result);
});
test('Isolate styles', () => {
const str = '<div><style>.a{color: red}</style></div><div></div><style>.b{color: blue}</style>';
const resHtml = [{ tagName: 'div' }, { tagName: 'div' }];
const resCss = [
{
selectors: ['a'],
style: { color: 'red' },
},
{
selectors: ['b'],
style: { color: 'blue' },
},
];
const res = obj.parse(str, ParserCss());
expect(res.html).toEqual(resHtml);
expect(res.css).toEqual(resCss);
});
test('Respect multiple font-faces contained in styles in html', () => {
const str = `
<style>
@font-face {
font-family: "Open Sans";
src:url(path_to_url
}
@font-face {
font-family: 'Glyphicons Halflings';
src:url(path_to_url
}
</style>
<div>a div</div>
`;
const expected = [
{
selectors: [],
selectorsAdd: '',
style: {
'font-family': '"Open Sans"',
src: 'url(path_to_url
},
singleAtRule: true,
atRuleType: 'font-face',
},
{
selectors: [],
selectorsAdd: '',
style: {
'font-family': "'Glyphicons Halflings'",
src: 'url(path_to_url
},
singleAtRule: true,
atRuleType: 'font-face',
},
];
const res = obj.parse(str, ParserCss());
expect(res.css).toEqual(expected);
});
test('Parse nested div with text and spaces', () => {
const str = '<div> <p>TestText</p> </div>';
const result = [
{
tagName: 'div',
type: 'text',
components: [
{
tagName: '',
type: 'textnode',
content: ' ',
},
{
tagName: 'p',
components: { type: 'textnode', content: 'TestText' },
type: 'text',
},
{
tagName: '',
type: 'textnode',
content: ' ',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Cleanup useless empty whitespaces', () => {
const str = `<div>
<p>TestText</p>
</div>`;
const result = [
{
tagName: 'div',
components: [
{
tagName: 'p',
components: { type: 'textnode', content: 'TestText' },
type: 'text',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Keep meaningful whitespaces', () => {
const str = `<div>
<p>A</p> <p>B</p> <p>C</p> <p>D</p>
</div>`;
const result = [
{
tagName: 'div',
type: 'text',
components: [
{
tagName: 'p',
components: { type: 'textnode', content: 'A' },
type: 'text',
},
{ type: 'textnode', content: ' ', tagName: '' },
{
tagName: 'p',
components: { type: 'textnode', content: 'B' },
type: 'text',
},
{ type: 'textnode', content: ' ', tagName: '' },
{
tagName: 'p',
components: { type: 'textnode', content: 'C' },
type: 'text',
},
{ type: 'textnode', content: '', tagName: '' },
{
tagName: 'p',
components: { type: 'textnode', content: 'D' },
type: 'text',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse node with model attributes to fetch', () => {
const str =
'<div id="test1" data-test="test-value" data-gjs-draggable=".myselector" data-gjs-stuff="test">test2 </div>';
const result = [
{
tagName: 'div',
draggable: '.myselector',
stuff: 'test',
attributes: {
id: 'test1',
'data-test': 'test-value',
},
type: 'text',
components: { type: 'textnode', content: 'test2 ' },
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse model attributes with true and false', () => {
const str = '<div id="test1" data-test="test-value" data-gjs-draggable="true" data-gjs-stuff="false">test2 </div>';
const result = [
{
tagName: 'div',
draggable: true,
stuff: false,
attributes: {
id: 'test1',
'data-test': 'test-value',
},
type: 'text',
components: { type: 'textnode', content: 'test2 ' },
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse attributes with object inside', () => {
const str = '<div data-gjs-test=\'{ "prop1": "value1", "prop2": 10, "prop3": true}\'>test2 </div>';
const result = [
{
tagName: 'div',
type: 'text',
test: {
prop1: 'value1',
prop2: 10,
prop3: true,
},
components: { type: 'textnode', content: 'test2 ' },
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('Parse attributes with arrays inside', () => {
const str = '<div data-gjs-test=\'["value1", "value2"]\'>test2 </div>';
const result = [
{
tagName: 'div',
type: 'text',
test: ['value1', 'value2'],
components: { type: 'textnode', content: 'test2 ' },
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('SVG is properly parsed', () => {
const str = `<div>
<svg xmlns="path_to_url" viewBox="0 0 24 24">
<linearGradient x1="0%" y1="0%"/>
<path d="M13 12h7v1.5h-7m0-4h7V11h-7m0 3.5h7V16h-7m8-12H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2m0 15h-9V6h9"></path>
</svg>
</div>`;
const result = [
{
tagName: 'div',
components: [
{
type: 'svg',
tagName: 'svg',
attributes: {
xmlns: 'path_to_url
viewBox: '0 0 24 24',
},
components: [
{
tagName: 'linearGradient',
attributes: { x1: '0%', y1: '0%' },
type: 'svg-in',
},
{
tagName: 'path',
attributes: {
d: 'M13 12h7v1.5h-7m0-4h7V11h-7m0 3.5h7V16h-7m8-12H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2m0 15h-9V6h9',
},
type: 'svg-in',
},
],
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
test('<template> with content is properly parsed', () => {
const str = `<template class="test">
<tr>
<td>Cell</td>
</tr>
</template>`;
const result = [
{
tagName: 'template',
classes: ['test'],
components: [
{
type: 'row',
tagName: 'tr',
components: [
{
type: 'cell',
tagName: 'td',
components: { type: 'textnode', content: 'Cell' },
},
],
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});
describe('Options', () => {
test('Remove unsafe attributes', () => {
const str = '<img src="path/img" data-test="1" class="test" onload="unsafe"/>';
const result = {
type: 'image',
tagName: 'img',
classes: ['test'],
attributes: {
src: 'path/img',
'data-test': '1',
},
};
expect(obj.parse(str).html).toEqual([result]);
expect(obj.parse(str, null, { allowUnsafeAttr: true }).html).toEqual([
{
...result,
attributes: {
...result.attributes,
onload: 'unsafe',
},
},
]);
});
test('Remove unsafe attribute values', () => {
const str = '<iframe src="javascript:alert(1)"></iframe>';
const result = {
type: 'iframe',
tagName: 'iframe',
};
expect(obj.parse(str).html).toEqual([result]);
expect(obj.parse(str, null, { allowUnsafeAttrValue: true }).html).toEqual([
{
...result,
attributes: {
src: 'javascript:alert(1)',
},
},
]);
});
test('Custom preParser option', () => {
const str = '<iframe src="javascript:alert(1)"></iframe>';
const result = {
type: 'iframe',
tagName: 'iframe',
attributes: {
src: 'test:alert(1)',
},
};
const preParser = (str: string) => str.replace('javascript:', 'test:');
expect(obj.parse(str, null, { preParser }).html).toEqual([result]);
});
test('parsing as document', () => {
const str = `
<!DOCTYPE html>
<html class="cls-html" lang="en" data-gjs-htmlp="true">
<head class="cls-head" data-gjs-headp="true">
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="/noop.css">
<!-- comment -->
<script src="/noop.js"></script>
<style>.test { color: red }</style>
</head>
<body class="cls-body" data-gjs-bodyp="true">
<h1>H1</h1>
</body>
</html>
`;
expect(obj.parse(str, null, { asDocument: true })).toEqual({
doctype: '<!DOCTYPE html>',
root: { classes: ['cls-html'], attributes: { lang: 'en' }, htmlp: true },
head: {
type: 'head',
tagName: 'head',
headp: true,
classes: ['cls-head'],
components: [
{ tagName: 'meta', attributes: { charset: 'utf-8' } },
{
tagName: 'title',
type: 'text',
components: { type: 'textnode', content: 'Test' },
},
{
tagName: 'link',
attributes: { rel: 'stylesheet', href: '/noop.css' },
},
{
type: 'comment',
tagName: '',
content: ' comment ',
},
{
tagName: 'style',
type: 'text',
components: { type: 'textnode', content: '.test { color: red }' },
},
],
},
html: {
tagName: 'body',
bodyp: true,
classes: ['cls-body'],
components: [
{
tagName: 'h1',
type: 'text',
components: { type: 'textnode', content: 'H1' },
},
],
},
});
});
});
});
``` | /content/code_sandbox/test/specs/parser/model/ParserHtml.ts | xml | 2016-01-22T00:23:19 | 2024-08-16T11:20:59 | grapesjs | GrapesJS/grapesjs | 21,687 | 5,385 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list android:id="@+id/selected"
android:oneshot="false"
xmlns:android="path_to_url">
<item android:drawable="@drawable/ic_location_navigation_no_location_24dp" android:duration="750" />
<item android:drawable="@drawable/ic_location_navigation_24dp" android:duration="750" />
</animation-list>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_location_navigation_searching_24dp.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 93 |
```xml
<!DOCTYPE icuInfo SYSTEM "path_to_url">
<!--
* 2017 and later: Unicode, Inc. and others.
-->
<icuInfo>
<icuProducts>
<icuProduct type="icu4c">
<releases>
<release version="4.2">
<capabilities>
<feature type="unicode" version="5.1"/>
<feature type="uca" version="5.1"/>
<feature type="tz" version="2009g"/>
<feature type="cldr" version="1.7"/>
<feature type="formatting" total="292" version="???">
af <!-- open:ok syms:40/42#189:ok fmt:ok -->
af_NA <!-- open:ok syms:40/42#189:ok fmt:ok -->
af_ZA <!-- open:ok syms:40/42#189:ok fmt:ok -->
am <!-- open:ok syms:40/42#131:ok fmt:ok -->
am_ET <!-- open:ok syms:40/42#131:ok fmt:ok -->
ar <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_AE <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_BH <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_DZ <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_EG <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_IQ <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_JO <!-- open:ok syms:40/42#254:ok fmt:ok -->
ar_KW <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_LB <!-- open:ok syms:40/42#254:ok fmt:ok -->
ar_LY <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_MA <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_OM <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_QA <!-- open:ok syms:40/42#220:ok fmt:ok -->
ar_SA <!-- open:ok syms:40/42#220:ok fmt:ok -->
ar_SD <!-- open:ok syms:40/42#206:ok fmt:ok -->
ar_SY <!-- open:ok syms:40/42#254:ok fmt:ok -->
ar_TN <!-- open:ok syms:40/42#220:ok fmt:ok -->
ar_YE <!-- open:ok syms:40/42#220:ok fmt:ok -->
as <!-- open:ok syms:40/42#214:ok fmt:ok -->
as_IN <!-- open:ok syms:40/42#214:ok fmt:ok -->
az <!-- open:ok syms:40/42#188:ok fmt:ok -->
az_Cyrl <!-- open:ok syms:40/42#188:ok fmt:ok -->
az_Cyrl_AZ <!-- open:ok syms:40/42#188:ok fmt:ok -->
az_Latn <!-- open:ok syms:40/42#188:ok fmt:ok -->
az_Latn_AZ <!-- open:ok syms:40/42#188:ok fmt:ok -->
be <!-- open:ok syms:40/42#193:ok fmt:ok -->
be_BY <!-- open:ok syms:40/42#193:ok fmt:ok -->
bg <!-- open:ok syms:40/42#196:ok fmt:ok -->
bg_BG <!-- open:ok syms:40/42#196:ok fmt:ok -->
bn <!-- open:ok syms:40/42#256:ok fmt:ok -->
bn_BD <!-- open:ok syms:40/42#256:ok fmt:ok -->
bn_IN <!-- open:ok syms:40/42#256:ok fmt:ok -->
bo <!-- open:ok syms:40/42#330:ok fmt:ok -->
bo_CN <!-- open:ok syms:40/42#330:ok fmt:ok -->
bo_IN <!-- open:ok syms:40/42#330:ok fmt:ok -->
ca <!-- open:ok syms:40/42#196:ok fmt:ok -->
ca_ES <!-- open:ok syms:40/42#196:ok fmt:ok -->
cs <!-- open:ok syms:40/42#212:ok fmt:ok -->
cs_CZ <!-- open:ok syms:40/42#212:ok fmt:ok -->
cy <!-- open:ok syms:40/42#221:ok fmt:ok -->
cy_GB <!-- open:ok syms:40/42#221:ok fmt:ok -->
da <!-- open:ok syms:40/42#194:ok fmt:ok -->
da_DK <!-- open:ok syms:40/42#194:ok fmt:ok -->
de <!-- open:ok syms:40/42#195:ok fmt:ok -->
de_AT <!-- open:ok syms:40/42#195:ok fmt:ok -->
de_BE <!-- open:ok syms:40/42#195:ok fmt:ok -->
de_CH <!-- open:ok syms:40/42#195:ok fmt:ok -->
de_DE <!-- open:ok syms:40/42#195:ok fmt:ok -->
de_LI <!-- open:ok syms:40/42#195:ok fmt:ok -->
de_LU <!-- open:ok syms:40/42#195:ok fmt:ok -->
el <!-- open:ok syms:40/42#218:ok fmt:ok -->
el_CY <!-- open:ok syms:40/42#218:ok fmt:ok -->
el_GR <!-- open:ok syms:40/42#218:ok fmt:ok -->
en <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_AU <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_BE <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_BW <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_BZ <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_CA <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_GB <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_HK <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_IE <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_IN <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_JM <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_MH <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_MT <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_NA <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_NZ <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_PH <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_PK <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_SG <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_TT <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_US <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_US_POSIX <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_VI <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_ZA <!-- open:ok syms:40/42#185:ok fmt:ok -->
en_ZW <!-- open:ok syms:40/42#185:ok fmt:ok -->
eo <!-- open:ok syms:40/42#177:ok fmt:ok -->
es <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_AR <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_BO <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_CL <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_CO <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_CR <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_DO <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_EC <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_ES <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_GT <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_HN <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_MX <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_NI <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_PA <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_PE <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_PR <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_PY <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_SV <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_US <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_UY <!-- open:ok syms:40/42#188:ok fmt:ok -->
es_VE <!-- open:ok syms:40/42#188:ok fmt:ok -->
et <!-- open:ok syms:40/42#201:ok fmt:ok -->
et_EE <!-- open:ok syms:40/42#201:ok fmt:ok -->
eu <!-- open:ok syms:40/42#197:ok fmt:ok -->
eu_ES <!-- open:ok syms:40/42#197:ok fmt:ok -->
fa <!-- open:ok syms:40/42#214:ok fmt:ok -->
fa_AF <!-- open:ok syms:40/42#197:ok fmt:ok -->
fa_IR <!-- open:ok syms:40/42#214:ok fmt:ok -->
fi <!-- open:ok syms:40/42#330:ok fmt:ok -->
fi_FI <!-- open:ok syms:40/42#330:ok fmt:ok -->
fo <!-- open:ok syms:40/42#200:ok fmt:ok -->
fo_FO <!-- open:ok syms:40/42#200:ok fmt:ok -->
fr <!-- open:ok syms:40/42#215:ok fmt:ok -->
fr_BE <!-- open:ok syms:40/42#215:ok fmt:ok -->
fr_CA <!-- open:ok syms:40/42#215:ok fmt:ok -->
fr_CH <!-- open:ok syms:40/42#215:ok fmt:ok -->
fr_FR <!-- open:ok syms:40/42#215:ok fmt:ok -->
fr_LU <!-- open:ok syms:40/42#215:ok fmt:ok -->
fr_MC <!-- open:ok syms:40/42#215:ok fmt:ok -->
fr_SN <!-- open:ok syms:40/42#215:ok fmt:ok -->
ga <!-- open:ok syms:40/42#247:ok fmt:ok -->
ga_IE <!-- open:ok syms:40/42#247:ok fmt:ok -->
gl <!-- open:ok syms:40/42#182:ok fmt:ok -->
gl_ES <!-- open:ok syms:40/42#182:ok fmt:ok -->
gsw <!-- open:ok syms:40/42#201:ok fmt:ok -->
gsw_CH <!-- open:ok syms:40/42#201:ok fmt:ok -->
gu <!-- open:ok syms:40/42#206:ok fmt:ok -->
gu_IN <!-- open:ok syms:40/42#206:ok fmt:ok -->
gv <!-- open:ok syms:40/42#295:ok fmt:ok -->
gv_GB <!-- open:ok syms:40/42#295:ok fmt:ok -->
ha <!-- open:ok syms:40/42#178:ok fmt:ok -->
ha_Latn <!-- open:ok syms:40/42#178:ok fmt:ok -->
ha_Latn_GH <!-- open:ok syms:40/42#178:ok fmt:ok -->
ha_Latn_NE <!-- open:ok syms:40/42#178:ok fmt:ok -->
ha_Latn_NG <!-- open:ok syms:40/42#178:ok fmt:ok -->
haw <!-- open:ok syms:40/42#199:ok fmt:ok -->
haw_US <!-- open:ok syms:40/42#199:ok fmt:ok -->
he <!-- open:ok syms:40/42#204:ok fmt:ok -->
he_IL <!-- open:ok syms:40/42#204:ok fmt:ok -->
hi <!-- open:ok syms:40/42#207:ok fmt:ok -->
hi_IN <!-- open:ok syms:40/42#207:ok fmt:ok -->
hr <!-- open:ok syms:40/42#203:ok fmt:ok -->
hr_HR <!-- open:ok syms:40/42#203:ok fmt:ok -->
hu <!-- open:ok syms:40/42#206:ok fmt:ok -->
hu_HU <!-- open:ok syms:40/42#206:ok fmt:ok -->
hy <!-- open:ok syms:40/42#204:ok fmt:ok -->
hy_AM <!-- open:ok syms:40/42#204:ok fmt:ok -->
hy_AM_REVISED <!-- open:ok syms:40/42#204:ok fmt:ok -->
id <!-- open:ok syms:40/42#173:ok fmt:ok -->
id_ID <!-- open:ok syms:40/42#173:ok fmt:ok -->
ii <!-- open:ok syms:40/42#93:ok fmt:ok -->
ii_CN <!-- open:ok syms:40/42#93:ok fmt:ok -->
is <!-- open:ok syms:40/42#223:ok fmt:ok -->
is_IS <!-- open:ok syms:40/42#223:ok fmt:ok -->
it <!-- open:ok syms:40/42#193:ok fmt:ok -->
it_CH <!-- open:ok syms:40/42#193:ok fmt:ok -->
it_IT <!-- open:ok syms:40/42#193:ok fmt:ok -->
ja <!-- open:ok syms:40/42#87:ok fmt:ok -->
ja_JP <!-- open:ok syms:40/42#87:ok fmt:ok -->
ka <!-- open:ok syms:40/42#49:ok fmt:ok -->
ka_GE <!-- open:ok syms:40/42#49:ok fmt:ok -->
kk <!-- open:ok syms:40/42#193:ok fmt:ok -->
kk_Cyrl <!-- open:ok syms:40/42#193:ok fmt:ok -->
kk_Cyrl_KZ <!-- open:ok syms:40/42#193:ok fmt:ok -->
kl <!-- open:ok syms:40/42#237:ok fmt:ok -->
kl_GL <!-- open:ok syms:40/42#237:ok fmt:ok -->
km <!-- open:ok syms:40/42#105:ok fmt:ok -->
km_KH <!-- open:ok syms:40/42#105:ok fmt:ok -->
kn <!-- open:ok syms:40/42#220:ok fmt:ok -->
kn_IN <!-- open:ok syms:40/42#220:ok fmt:ok -->
ko <!-- open:ok syms:40/42#87:ok fmt:ok -->
ko_KR <!-- open:ok syms:40/42#87:ok fmt:ok -->
kok <!-- open:ok syms:40/42#243:ok fmt:ok -->
kok_IN <!-- open:ok syms:40/42#243:ok fmt:ok -->
kw <!-- open:ok syms:40/42#224:ok fmt:ok -->
kw_GB <!-- open:ok syms:40/42#224:ok fmt:ok -->
lt <!-- open:ok syms:40/42#231:ok fmt:ok -->
lt_LT <!-- open:ok syms:40/42#231:ok fmt:ok -->
lv <!-- open:ok syms:40/42#231:ok fmt:ok -->
lv_LV <!-- open:ok syms:40/42#231:ok fmt:ok -->
mk <!-- open:ok syms:40/42#208:ok fmt:ok -->
mk_MK <!-- open:ok syms:40/42#208:ok fmt:ok -->
ml <!-- open:ok syms:40/42#262:ok fmt:ok -->
ml_IN <!-- open:ok syms:40/42#262:ok fmt:ok -->
mr <!-- open:ok syms:40/42#230:ok fmt:ok -->
mr_IN <!-- open:ok syms:40/42#230:ok fmt:ok -->
ms <!-- open:ok syms:40/42#169:ok fmt:ok -->
ms_BN <!-- open:ok syms:40/42#169:ok fmt:ok -->
ms_MY <!-- open:ok syms:40/42#169:ok fmt:ok -->
mt <!-- open:ok syms:40/42#191:ok fmt:ok -->
mt_MT <!-- open:ok syms:40/42#191:ok fmt:ok -->
nb <!-- open:ok syms:40/42#200:ok fmt:ok -->
nb_NO <!-- open:ok syms:40/42#200:ok fmt:ok -->
ne <!-- open:ok syms:40/42#55:ok fmt:ok -->
ne_IN <!-- open:ok syms:40/42#55:ok fmt:ok -->
ne_NP <!-- open:ok syms:40/42#55:ok fmt:ok -->
nl <!-- open:ok syms:40/42#203:ok fmt:ok -->
nl_BE <!-- open:ok syms:40/42#203:ok fmt:ok -->
nl_NL <!-- open:ok syms:40/42#203:ok fmt:ok -->
nn <!-- open:ok syms:40/42#182:ok fmt:ok -->
nn_NO <!-- open:ok syms:40/42#182:ok fmt:ok -->
om <!-- open:ok syms:40/42#208:ok fmt:ok -->
om_ET <!-- open:ok syms:40/42#208:ok fmt:ok -->
om_KE <!-- open:ok syms:40/42#208:ok fmt:ok -->
or <!-- open:ok syms:40/42#232:ok fmt:ok -->
or_IN <!-- open:ok syms:40/42#232:ok fmt:ok -->
pa <!-- open:ok syms:40/42#196:ok fmt:ok -->
pa_Arab <!-- open:ok syms:40/42#176:ok fmt:ok -->
pa_Arab_PK <!-- open:ok syms:40/42#176:ok fmt:ok -->
pa_Guru <!-- open:ok syms:40/42#196:ok fmt:ok -->
pa_Guru_IN <!-- open:ok syms:40/42#196:ok fmt:ok -->
pl <!-- open:ok syms:40/42#212:ok fmt:ok -->
pl_PL <!-- open:ok syms:40/42#212:ok fmt:ok -->
ps <!-- open:ok syms:40/42#202:ok fmt:ok -->
ps_AF <!-- open:ok syms:40/42#202:ok fmt:ok -->
pt <!-- open:ok syms:40/42#214:ok fmt:ok -->
pt_BR <!-- open:ok syms:40/42#214:ok fmt:ok -->
pt_PT <!-- open:ok syms:40/42#214:ok fmt:ok -->
ro <!-- open:ok syms:40/42#199:ok fmt:ok -->
ro_MD <!-- open:ok syms:40/42#199:ok fmt:ok -->
ro_RO <!-- open:ok syms:40/42#199:ok fmt:ok -->
ru <!-- open:ok syms:40/42#201:ok fmt:ok -->
ru_RU <!-- open:ok syms:40/42#201:ok fmt:ok -->
ru_UA <!-- open:ok syms:40/42#201:ok fmt:ok -->
si <!-- open:ok syms:40/42#217:ok fmt:ok -->
si_LK <!-- open:ok syms:40/42#217:ok fmt:ok -->
sk <!-- open:ok syms:40/42#185:ok fmt:ok -->
sk_SK <!-- open:ok syms:40/42#185:ok fmt:ok -->
sl <!-- open:ok syms:40/42#192:ok fmt:ok -->
sl_SI <!-- open:ok syms:40/42#192:ok fmt:ok -->
so <!-- open:ok syms:40/42#298:ok fmt:ok -->
so_DJ <!-- open:ok syms:40/42#298:ok fmt:ok -->
so_ET <!-- open:ok syms:40/42#298:ok fmt:ok -->
so_KE <!-- open:ok syms:40/42#298:ok fmt:ok -->
so_SO <!-- open:ok syms:40/42#298:ok fmt:ok -->
sq <!-- open:ok syms:40/42#186:ok fmt:ok -->
sq_AL <!-- open:ok syms:40/42#186:ok fmt:ok -->
sr <!-- open:ok syms:40/42#183:ok fmt:ok -->
sr_Cyrl <!-- open:ok syms:40/42#183:ok fmt:ok -->
sr_Cyrl_BA <!-- open:ok syms:40/42#187:ok fmt:ok -->
sr_Cyrl_ME <!-- open:ok syms:40/42#183:ok fmt:ok -->
sr_Cyrl_RS <!-- open:ok syms:40/42#183:ok fmt:ok -->
sr_Latn <!-- open:ok syms:40/42#185:ok fmt:ok -->
sr_Latn_BA <!-- open:ok syms:40/42#185:ok fmt:ok -->
sr_Latn_ME <!-- open:ok syms:40/42#185:ok fmt:ok -->
sr_Latn_RS <!-- open:ok syms:40/42#185:ok fmt:ok -->
sv <!-- open:ok syms:40/42#185:ok fmt:ok -->
sv_FI <!-- open:ok syms:40/42#185:ok fmt:ok -->
sv_SE <!-- open:ok syms:40/42#185:ok fmt:ok -->
sw <!-- open:ok syms:40/42#186:ok fmt:ok -->
sw_KE <!-- open:ok syms:40/42#186:ok fmt:ok -->
sw_TZ <!-- open:ok syms:40/42#186:ok fmt:ok -->
ta <!-- open:ok syms:40/42#183:ok fmt:ok -->
ta_IN <!-- open:ok syms:40/42#183:ok fmt:ok -->
te <!-- open:ok syms:40/42#231:ok fmt:ok -->
te_IN <!-- open:ok syms:40/42#231:ok fmt:ok -->
th <!-- open:ok syms:39/41#218:ok fmt:ok -->
th_TH <!-- open:ok syms:39/41#218:ok fmt:ok -->
ti <!-- open:ok syms:40/42#133:ok fmt:ok -->
ti_ER <!-- open:ok syms:40/42#125:ok fmt:ok -->
ti_ET <!-- open:ok syms:40/42#133:ok fmt:ok -->
tr <!-- open:ok syms:40/42#171:ok fmt:ok -->
tr_TR <!-- open:ok syms:40/42#171:ok fmt:ok -->
uk <!-- open:ok syms:40/42#204:ok fmt:ok -->
uk_UA <!-- open:ok syms:40/42#204:ok fmt:ok -->
ur <!-- open:ok syms:40/42#179:ok fmt:ok -->
ur_IN <!-- open:ok syms:40/42#179:ok fmt:ok -->
ur_PK <!-- open:ok syms:40/42#179:ok fmt:ok -->
uz <!-- open:ok syms:40/42#49:ok fmt:ok -->
uz_Arab <!-- open:ok syms:40/42#49:ok fmt:ok -->
uz_Arab_AF <!-- open:ok syms:40/42#49:ok fmt:ok -->
uz_Cyrl <!-- open:ok syms:40/42#49:ok fmt:ok -->
uz_Cyrl_UZ <!-- open:ok syms:40/42#49:ok fmt:ok -->
uz_Latn <!-- open:ok syms:40/42#141:ok fmt:ok -->
uz_Latn_UZ <!-- open:ok syms:40/42#141:ok fmt:ok -->
vi <!-- open:ok syms:40/42#267:ok fmt:ok -->
vi_VN <!-- open:ok syms:40/42#267:ok fmt:ok -->
zh <!-- open:ok syms:40/42#94:ok fmt:ok -->
zh_Hans <!-- open:ok syms:40/42#94:ok fmt:ok -->
zh_Hans_CN <!-- open:ok syms:40/42#94:ok fmt:ok -->
zh_Hans_HK <!-- open:ok syms:40/42#94:ok fmt:ok -->
zh_Hans_MO <!-- open:ok syms:40/42#94:ok fmt:ok -->
zh_Hans_SG <!-- open:ok syms:40/42#94:ok fmt:ok -->
zh_Hant <!-- open:ok syms:40/42#94:ok fmt:ok -->
zh_Hant_HK <!-- open:ok syms:40/42#94:ok fmt:ok -->
zh_Hant_MO <!-- open:ok syms:40/42#94:ok fmt:ok -->
zh_Hant_TW <!-- open:ok syms:40/42#94:ok fmt:ok -->
zu <!-- open:ok syms:40/42#201:ok fmt:ok -->
zu_ZA <!-- open:ok syms:40/42#201:ok fmt:ok -->
</feature>
<feature type="collation" total="219" version="???">
af
af_NA
af_ZA
ar
ar_AE
ar_BH
ar_DZ
ar_EG
ar_IQ
ar_JO
ar_KW
ar_LB
ar_LY
ar_MA
ar_OM
ar_QA
ar_SA
ar_SD
ar_SY
ar_TN
ar_YE
as
as_IN
az
az_Latn
az_Latn_AZ
be
be_BY
bg
bg_BG
bn
bn_IN
ca
ca_ES
cs
cs_CZ
cy
da
da_DK
de
de_AT
de_BE
de_CH
de_DE
de_LU
el
el_GR
en
en_AU
en_BE
en_BW
en_CA
en_GB
en_HK
en_IE
en_IN
en_MT
en_NZ
en_PH
en_SG
en_US
en_US_POSIX
en_VI
en_ZA
en_ZW
eo
es
es_AR
es_BO
es_CL
es_CO
es_CR
es_DO
es_EC
es_ES
es_GT
es_HN
es_MX
es_NI
es_PA
es_PE
es_PR
es_PY
es_SV
es_US
es_UY
es_VE
et
et_EE
fa
fa_AF
fa_IR
fi
fi_FI
fo
fo_FO
fr
fr_BE
fr_CA
fr_CH
fr_FR
fr_LU
ga
ga_IE
gu
gu_IN
haw
he
he_IL
hi
hi_IN
hr
hr_HR
hu
hu_HU
id
id_ID
is
is_IS
it
it_CH
it_IT
ja
ja_JP
kk
kk_KZ
kl
kl_GL
km
kn
kn_IN
ko
ko_KR
kok
lt
lt_LT
lv
lv_LV
mk
mk_MK
ml
mr
mr_IN
ms
ms_BN
ms_MY
mt
mt_MT
nb
nb_NO
nl
nl_BE
nl_NL
nn
nn_NO
om
om_ET
om_KE
or
pa
pa_Arab
pa_Arab_PK
pa_Guru
pa_Guru_IN
pl
pl_PL
ps
ps_AF
pt
pt_BR
pt_PT
ro
ro_RO
ru
ru_RU
ru_UA
si
si_LK
sk
sk_SK
sl
sl_SI
sq
sq_AL
sr
sr_Cyrl
sr_Cyrl_BA
sr_Cyrl_ME
sr_Cyrl_RS
sr_Latn
sr_Latn_BA
sr_Latn_ME
sr_Latn_RS
sv
sv_FI
sv_SE
ta
ta_IN
te
te_IN
th
th_TH
tr
tr_TR
uk
uk_UA
ur
ur_IN
ur_PK
vi
vi_VN
zh
zh_Hans
zh_Hans_CN
zh_Hans_SG
zh_Hant
zh_Hant_HK
zh_Hant_MO
zh_Hant_TW
</feature>
</capabilities>
</release>
</releases>
</icuProduct>
</icuProducts>
</icuInfo>
``` | /content/code_sandbox/tools/multi/proj/icu4cscan/xml/4_2.xml | xml | 2016-01-08T02:42:32 | 2024-08-16T18:14:55 | icu | unicode-org/icu | 2,693 | 7,893 |
```xml
import {Component, EventEmitter, NgZone, OnDestroy, OnInit, Output} from "@angular/core";
import {RxDocument} from "../../../../../../";
import {DatabaseService} from "../../services/database.service";
@Component({
selector: 'heroes-list',
templateUrl: 'heroes-list.component.html'
})
export class HeroesListComponent implements OnInit, OnDestroy {
heroes: RxDocument[];
sub;
@Output('edit') editChange: EventEmitter<RxDocument> = new EventEmitter();
set edit(hero) {
console.log('editHero: ' + hero.name);
this.editChange.emit(hero);
}
editHero(hero) {
this.edit = hero;
}
deleteHero(hero) {
hero.remove();
}
constructor(private databaseService: DatabaseService,
private zone: NgZone) {
}
ngAfterContentInit() {
}
private async _show() {
const db = await this.databaseService.get();
const heroes$ = db['hero']
.find()
.sort({name: 1})
.$;
this.sub = heroes$.subscribe(heroes => {
this.heroes = heroes;
this.zone.run(() => {
});
});
}
ngOnInit() {
this._show();
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
``` | /content/code_sandbox/examples/ionic2/src/app/components/heroes-list/heroes-list.component.ts | xml | 2016-12-02T19:34:42 | 2024-08-16T15:47:20 | rxdb | pubkey/rxdb | 21,054 | 273 |
```xml
import { ExpoUpdatesManifest } from 'expo-manifests';
import { NativeModules } from 'react-native';
import './setUpErrorHandler.fx';
/**
* @hidden Dev launcher manifests are only ones served by servers (not embedded bare manifests)
*/
export type Manifest = ExpoUpdatesManifest;
export { disableErrorHandling } from './DevLauncherErrorManager';
/**
* @hidden
*/
export function registerErrorHandlers() {
console.warn(
'DevLauncher.registerErrorHandlers has been deprecated. To enable error handlers you need to import "expo-dev-launcher" at the top of your index.js.'
);
}
/**
* A method that returns a boolean to indicate if the current application is a development build.
*/
export function isDevelopmentBuild(): boolean {
return !!NativeModules.EXDevLauncher;
}
/**
* @hidden
*/
export type DevLauncherExtension = {
navigateToLauncherAsync: () => Promise<void>;
};
``` | /content/code_sandbox/packages/expo-dev-launcher/src/DevLauncher.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 187 |
```xml
import { getUnixTime } from 'date-fns';
import { c } from 'ttag';
import { AppLink, SettingsLink } from '@proton/components';
import { CALENDAR_SETTINGS_SECTION_ID, ICAL_ATTENDEE_STATUS, ICAL_METHOD } from '@proton/shared/lib/calendar/constants';
import { getInteroperabilityOperationsPath } from '@proton/shared/lib/calendar/settingsRoutes';
import { propertyToUTCDate } from '@proton/shared/lib/calendar/vcalConverter';
import { APPS, CALENDAR_APP_NAME } from '@proton/shared/lib/constants';
import type { RequireSome } from '@proton/shared/lib/interfaces';
import OpenInCalendarButton from '../../components/message/extras/calendar/OpenInCalendarButton';
import type { InvitationModel } from './invite';
export const getCalendarEventLink = (model: RequireSome<InvitationModel, 'invitationIcs'>) => {
const {
isOrganizerMode,
isImport,
hasMultipleVevents,
hideLink,
isPartyCrasher,
isOutdated,
isAddressActive,
calendarData,
invitationIcs: { method, attendee: attendeeIcs, vevent: veventIcs },
invitationApi,
hasNoCalendars,
canCreateCalendar,
hasDecryptionError,
} = model;
if (hideLink) {
return null;
}
const hasAlsoReplied =
attendeeIcs?.partstat &&
[ICAL_ATTENDEE_STATUS.ACCEPTED, ICAL_ATTENDEE_STATUS.TENTATIVE, ICAL_ATTENDEE_STATUS.DECLINED].includes(
attendeeIcs?.partstat
);
const canBeAdded = isImport;
const canBeAnswered =
!isOrganizerMode && method === ICAL_METHOD.REQUEST && !isOutdated && isAddressActive && !isImport;
const canBeManaged =
isOrganizerMode &&
(method === ICAL_METHOD.REPLY || (method === ICAL_METHOD.COUNTER && hasAlsoReplied)) &&
!isImport &&
!veventIcs['recurrence-id'];
const canBeSeenUpdated =
[ICAL_METHOD.CANCEL, ICAL_METHOD.COUNTER, ICAL_METHOD.REFRESH].includes(method) ||
(!isOrganizerMode && method === ICAL_METHOD.REQUEST && isOutdated);
const safeCalendarNeedsUserAction = calendarData?.calendarNeedsUserAction && !(isPartyCrasher && !isOrganizerMode);
// the calendar needs a user action to be active
if (safeCalendarNeedsUserAction) {
if (isImport) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>{c('Link')
.t`You need to activate your calendar keys to add this event`}</AppLink>
);
}
if (canBeManaged) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>{c('Link')
.t`You need to activate your calendar keys to manage this invitation`}</AppLink>
);
}
if (canBeAnswered) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>{c('Link')
.t`You need to activate your calendar keys to answer this invitation`}</AppLink>
);
}
if (canBeSeenUpdated && invitationApi) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>
{isOrganizerMode
? c('Link').t`You need to activate your calendar keys to see the updated event`
: c('Link').t`You need to activate your calendar keys to see the updated invitation`}
</AppLink>
);
}
return null;
}
if (isImport && hasMultipleVevents) {
return (
<SettingsLink
path={getInteroperabilityOperationsPath({ sectionId: CALENDAR_SETTINGS_SECTION_ID.IMPORT })}
app={APPS.PROTONCALENDAR}
>
{c('Link')
.t`This ICS file contains more than one event. Please download it and import the events in ${CALENDAR_APP_NAME}`}
</SettingsLink>
);
}
// the invitation is unanswered
if (!invitationApi) {
if (hasDecryptionError) {
// the event exists in the db but couldn't be decrypted
if (canBeManaged) {
return (
<SettingsLink path="/encryption-keys#addresses" app={APPS.PROTONMAIL}>
{c('Link').t`You need to reactivate your keys to manage this invitation`}
</SettingsLink>
);
}
if (canBeSeenUpdated) {
return (
<SettingsLink path="/encryption-keys#addresses" app={APPS.PROTONMAIL}>
{isOrganizerMode
? c('Link').t`You need to reactivate your keys to see the updated event`
: c('Link').t`You need to reactivate your keys to see the updated invitation`}
</SettingsLink>
);
}
}
if (hasNoCalendars && canCreateCalendar && !isPartyCrasher) {
if (canBeAdded) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>
{c('Link').t`Create a new calendar to add this event`}
</AppLink>
);
}
if (canBeAnswered) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>
{c('Link').t`Create a new calendar to answer this invitation`}
</AppLink>
);
}
if (canBeManaged) {
return (
<AppLink to="/" toApp={APPS.PROTONCALENDAR}>
{c('Link').t`Create a new calendar to manage your invitations`}
</AppLink>
);
}
}
return null;
}
// the invitation has been answered
const calendarID = calendarData?.calendar.ID || '';
const eventID = invitationApi?.calendarEvent.ID;
const recurrenceIDProperty = invitationApi?.vevent['recurrence-id'];
const recurrenceID = recurrenceIDProperty ? getUnixTime(propertyToUTCDate(recurrenceIDProperty)) : undefined;
const linkString = isOutdated
? c('Link').t`Open updated event in ${CALENDAR_APP_NAME}`
: c('Link').t`Open in ${CALENDAR_APP_NAME}`;
return (
<OpenInCalendarButton
linkString={linkString}
calendarID={calendarID}
eventID={eventID}
recurrenceID={recurrenceID}
/>
);
};
``` | /content/code_sandbox/applications/mail/src/app/helpers/calendar/inviteLink.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,438 |
```xml
export { default as Prompt } from './Prompt';
export * from './Prompt';
``` | /content/code_sandbox/packages/components/components/prompt/index.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 17 |
```xml
import * as React from 'react';
import { AreaChart, IChartProps } from '@fluentui/react-charting';
import * as d3 from 'd3-format';
import { ILineChartProps } from '@fluentui/react-charting';
import { DefaultButton } from '@fluentui/react/lib/Button';
interface IAreaChartBasicState {
width: number;
height: number;
dynamicData: IChartProps;
}
export class AreaChartDataChangeExample extends React.Component<{}, IAreaChartBasicState> {
constructor(props: ILineChartProps) {
super(props);
this.state = {
width: 700,
height: 300,
dynamicData: {
chartTitle: 'Area chart with dynamic data',
lineChartData: [
{
legend: 'Chart 1',
data: [
{ x: 20, y: 10 },
{ x: 30, y: 20 },
{ x: 40, y: 40 },
],
},
{
legend: 'Chart 2',
data: [
{ x: 20, y: 20 },
{ x: 30, y: 30 },
{ x: 40, y: 50 },
],
},
{
legend: 'Chart 3',
data: [
{ x: 20, y: 25 },
{ x: 30, y: 35 },
{ x: 40, y: 55 },
],
},
],
},
};
this._changeData = this._changeData.bind(this);
this._changeXData = this._changeXData.bind(this);
}
public render(): JSX.Element {
return <div className="containerDiv">{this._basicExample()}</div>;
}
private _onWidthChange = (e: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ width: parseInt(e.target.value, 10) });
};
private _onHeightChange = (e: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ height: parseInt(e.target.value, 10) });
};
private _basicExample(): JSX.Element {
const rootStyle = { width: `${this.state.width}px`, height: `${this.state.height}px` };
return (
<>
<label htmlFor="changeWidth_Multiple">Change Width:</label>
<input
type="range"
value={this.state.width}
min={200}
max={1000}
id="changeWidth_Multiple"
onChange={this._onWidthChange}
aria-valuetext={`ChangeWidthslider${this.state.width}`}
/>
<label htmlFor="changeHeight_Multiple">Change Height:</label>
<input
type="range"
value={this.state.height}
min={200}
max={1000}
id="changeHeight_Multiple"
onChange={this._onHeightChange}
aria-valuetext={`ChangeHeightslider${this.state.height}`}
/>
<div style={rootStyle}>
<AreaChart
height={this.state.height}
width={this.state.width}
data={this.state.dynamicData}
legendsOverflowText={'Overflow Items'}
yAxisTickFormat={d3.format('$,')}
enablePerfOptimization={true}
legendProps={{
allowFocusOnLegends: true,
}}
enableReflow={true}
/>
<div style={{ marginBottom: '13px' }}>
Note: Y values in callout display individual values. Y value plotted on chart are cumulative for the
datapoint.
</div>
<DefaultButton text="Change Ydata" onClick={this._changeData} />
<DefaultButton text="Change Xdata" onClick={this._changeXData} />
</div>
</>
);
}
private _changeData(): void {
this.setState({
dynamicData: {
chartTitle: 'Area chart with dynamic data',
lineChartData: [
{
legend: 'Chart 1',
data: [
{ x: 20, y: this._randomY() },
{ x: 30, y: this._randomY() },
{ x: 40, y: this._randomY() },
],
},
{
legend: 'Chart 2',
data: [
{ x: 20, y: this._randomY() },
{ x: 30, y: this._randomY() },
{ x: 40, y: this._randomY() },
],
},
{
legend: 'Chart 3',
data: [
{ x: 20, y: this._randomY() },
{ x: 30, y: this._randomY() },
{ x: 40, y: this._randomY() },
],
},
],
},
});
}
private _changeXData(): void {
const xChangedValue1 = this._randomX();
const xChangedValue2 = xChangedValue1 + 2;
const xChangedValue3 = xChangedValue2 + 3;
this.setState({
dynamicData: {
chartTitle: 'Area chart with dynamic data',
lineChartData: [
{
legend: 'Chart 1',
data: [
{ x: xChangedValue1, y: 10 },
{ x: xChangedValue2, y: 20 },
{ x: xChangedValue3, y: 40 },
],
},
{
legend: 'Chart 2',
data: [
{ x: xChangedValue1, y: 20 },
{ x: xChangedValue2, y: 30 },
{ x: xChangedValue3, y: 50 },
],
},
{
legend: 'Chart 3',
data: [
{ x: xChangedValue1, y: 25 },
{ x: xChangedValue2, y: 35 },
{ x: xChangedValue3, y: 55 },
],
},
],
},
});
}
private _randomY(): number {
return Math.random() * 60 + 5;
}
private _randomX(): number {
const randomNumber = Math.random() * 50 + 5;
const roundedNumber = Math.round(randomNumber);
return roundedNumber;
}
}
``` | /content/code_sandbox/packages/react-examples/src/react-charting/AreaChart/AreaChart.DataChange.Example.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 1,375 |
```xml
// Used by GestureDetector (unsupported on web at the moment) to check whether the
// attached view may get flattened on Fabric. Original implementation causes errors
// on web due to the static resolution of `require` statements by webpack breaking
// the conditional importing.
export function getShadowNodeFromRef(_ref: any) {
return null;
}
``` | /content/code_sandbox/src/getShadowNodeFromRef.web.ts | xml | 2016-10-27T08:31:38 | 2024-08-16T12:03:40 | react-native-gesture-handler | software-mansion/react-native-gesture-handler | 5,989 | 72 |
```xml
export * from "./Contract";
export * from "./FavoriteManagerModule";
``` | /content/code_sandbox/src/main/Core/FavoriteManager/index.ts | xml | 2016-10-11T04:59:52 | 2024-08-16T11:53:31 | ueli | oliverschwendener/ueli | 3,543 | 15 |
```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="ru" original="../LocalizableStrings.resx">
<body>
<trans-unit id="BlobStoreSourceFileProvider_Exception_FailedToUpdateCache">
<source>Failed to update search cache.</source>
<target state="translated"> .</target>
<note />
</trans-unit>
<trans-unit id="BlobStoreSourceFileProvider_Exception_LocalCacheDoesNotExist">
<source>Local search cache '{0}' does not exist.</source>
<target state="translated"> \"{0}\" .</target>
<note>{0} - file path to search cache</note>
</trans-unit>
<trans-unit id="BlobStoreSourceFileProvider_Warning_LocalCacheWillBeUsed">
<source>Failed to update search cache. Local search cache will be used instead.</source>
<target state="translated"> . .</target>
<note />
</trans-unit>
<trans-unit id="TemplateSearchCache_Exception_NotSupported">
<source>The template search cache data is not supported.</source>
<target state="translated"> .</target>
<note />
</trans-unit>
<trans-unit id="TemplateSearchCache_Exception_NotValid">
<source>The template search cache data is not valid.</source>
<target state="translated"> .</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/Microsoft.TemplateSearch.Common/xlf/LocalizableStrings.ru.xlf | xml | 2016-06-28T20:54:16 | 2024-08-16T14:39:38 | templating | dotnet/templating | 1,598 | 401 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="path_to_url"
android:exitFadeDuration="@android:integer/config_shortAnimTime" >
<item android:state_pressed="true"
android:drawable="@color/branch_name_bg_pressed" />
<item android:drawable="@color/branch_name_bg" />
</selector>
``` | /content/code_sandbox/app/src/main/res/drawable/bt_branch_name_bg.xml | xml | 2016-10-14T02:54:01 | 2024-08-16T16:01:33 | MGit | maks/MGit | 1,193 | 82 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="path_to_url">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{1b31e8a3-343c-4e8a-a018-3ca937a37bf6}</UniqueIdentifier>
<Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{b400bdd5-2584-4d1c-b905-d44112576dd8}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{022e436a-5341-4184-8a8f-04d3dd644e8d}</UniqueIdentifier>
<Extensions>ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\python\_pjsua.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="..\src\python\_pjsua.def">
<Filter>Source Files</Filter>
</None>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\src\python\_pjsua.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>
``` | /content/code_sandbox/pjsip-apps/build/python_pjsua.vcxproj.filters | xml | 2016-01-24T05:00:33 | 2024-08-16T03:31:21 | pjproject | pjsip/pjproject | 1,960 | 368 |
```xml
import { TypeORMError } from "./TypeORMError"
import { EntityMetadata } from "../metadata/EntityMetadata"
/**
* Thrown when specified entity property was not found.
*/
export class EntityPropertyNotFoundError extends TypeORMError {
constructor(propertyPath: string, metadata: EntityMetadata) {
super(propertyPath)
Object.setPrototypeOf(this, EntityPropertyNotFoundError.prototype)
this.message = `Property "${propertyPath}" was not found in "${metadata.targetName}". Make sure your query is correct.`
}
}
``` | /content/code_sandbox/src/error/EntityPropertyNotFoundError.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 106 |
```xml
/*
* Wire
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see path_to_url
*
*/
import {useContext, useEffect, useRef} from 'react';
import {container} from 'tsyringe';
import {Button, ButtonVariant, IconButton, IconButtonVariant, useMatchMedia} from '@wireapp/react-ui-kit';
import {Avatar, AVATAR_SIZE} from 'Components/Avatar';
import {UserClassifiedBar} from 'Components/input/ClassifiedBar';
import {UnverifiedUserWarning} from 'Components/Modals/UserModal';
import {UserName} from 'Components/UserName';
import {SidebarTabs, useSidebarStore} from 'src/script/page/LeftSidebar/panels/Conversations/useSidebarStore';
import {useAppMainState, ViewType} from 'src/script/page/state';
import {useKoSubscribableChildren} from 'Util/ComponentUtil';
import {t} from 'Util/LocalizerUtil';
import {User} from '../../entity/User';
import {RootContext} from '../../page/RootProvider';
import {TeamState} from '../../team/TeamState';
import {UserState} from '../../user/UserState';
interface ConnectRequestsProps {
readonly userState: UserState;
readonly teamState: TeamState;
}
export const ConnectRequests = ({
userState = container.resolve(UserState),
teamState = container.resolve(TeamState),
}: ConnectRequestsProps) => {
const connectRequestsRefEnd = useRef<HTMLDivElement | null>(null);
const temporaryConnectRequestsCount = useRef<number>(0);
const mainViewModel = useContext(RootContext);
const {classifiedDomains} = useKoSubscribableChildren(teamState, ['classifiedDomains']);
const {connectRequests: unsortedConnectionRequests} = useKoSubscribableChildren(userState, ['connectRequests']);
const connectionRequests = unsortedConnectionRequests.sort((user1, user2) => {
const user1Connection = user1.connection();
const user2Connection = user2.connection();
if (!user1Connection || !user2Connection) {
return 0;
}
return new Date(user1Connection.lastUpdate).getTime() - new Date(user2Connection.lastUpdate).getTime();
});
// To be changed when design chooses a breakpoint, the conditional can be integrated to the ui-kit directly
const smBreakpoint = useMatchMedia('max-width: 640px');
const {setCurrentView} = useAppMainState(state => state.responsiveView);
const {setCurrentTab: setCurrentSidebarTab} = useSidebarStore();
const scrollToBottom = (behavior: ScrollBehavior = 'auto') => {
if (connectRequestsRefEnd.current) {
connectRequestsRefEnd.current.scrollIntoView({behavior});
}
};
useEffect(() => {
if (temporaryConnectRequestsCount.current + 1 === connectionRequests.length) {
scrollToBottom('smooth');
}
temporaryConnectRequestsCount.current = connectionRequests.length;
}, [connectionRequests]);
useEffect(() => {
scrollToBottom();
}, []);
if (!mainViewModel) {
return null;
}
const actionsViewModel = mainViewModel.actions;
const onIgnoreClick = (userEntity: User): void => {
actionsViewModel.ignoreConnectionRequest(userEntity);
};
const onAcceptClick = async (userEntity: User) => {
await actionsViewModel.acceptConnectionRequest(userEntity);
const conversationEntity = await actionsViewModel.getOrCreate1to1Conversation(userEntity);
if (connectionRequests.length === 1) {
/**
* In the connect request view modal, we show an overview of all incoming connection requests. When there are multiple open connection requests, we want that the user sees them all and can accept them one-by-one. When the last open connection request gets accepted, we want the user to switch to this conversation.
*/
setCurrentSidebarTab(SidebarTabs.RECENT);
return actionsViewModel.open1to1Conversation(conversationEntity);
}
};
return (
<div className="connect-request-wrapper">
<div id="connect-requests" className="connect-requests" style={{overflowY: 'scroll'}}>
<div className="connect-requests-inner" style={{overflowY: 'hidden'}}>
{smBreakpoint && (
<div css={{width: '100%'}}>
<IconButton
variant={IconButtonVariant.SECONDARY}
className="connect-requests-icon-back icon-back"
css={{marginBottom: 0}}
onClick={() => setCurrentView(ViewType.MOBILE_LEFT_SIDEBAR)}
/>
</div>
)}
{connectionRequests.map(connectRequest => (
<div
key={connectRequest.id}
className="connect-request"
data-uie-uid={connectRequest.id}
data-uie-name="connect-request"
>
<div className="connect-request-name ellipsis">
<UserName user={connectRequest} />
</div>
<div className="connect-request-username label-username">{connectRequest.handle}</div>
{classifiedDomains && (
<UserClassifiedBar users={[connectRequest]} classifiedDomains={classifiedDomains} />
)}
<Avatar
className="connect-request-avatar avatar-no-filter cursor-default"
participant={connectRequest}
avatarSize={AVATAR_SIZE.X_LARGE}
noBadge
noFilter
hideAvailabilityStatus
/>
<UnverifiedUserWarning />
<div className="connect-request-button-group">
<Button
variant={ButtonVariant.SECONDARY}
data-uie-name="do-ignore"
aria-label={t('connectionRequestIgnore')}
onClick={() => onIgnoreClick(connectRequest)}
>
{t('connectionRequestIgnore')}
</Button>
<Button
onClick={() => onAcceptClick(connectRequest)}
data-uie-name="do-accept"
aria-label={t('connectionRequestConnect')}
>
{t('connectionRequestConnect')}
</Button>
</div>
</div>
))}
</div>
<div className="connect-request-list-end" ref={connectRequestsRefEnd} />
</div>
</div>
);
};
``` | /content/code_sandbox/src/script/components/ConnectRequests/ConnectionRequests.tsx | xml | 2016-07-21T15:34:05 | 2024-08-16T11:40:13 | wire-webapp | wireapp/wire-webapp | 1,125 | 1,352 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<resources>
<dimen name="quoted_tweet_height">140dp</dimen>
<dimen name="action_bar_default_height">48dp</dimen>
<dimen name="neg_action_bar_default_height">-48dp</dimen>
<dimen name="contact_picture_border">5dp</dimen>
<dimen name="tweet_viewer_name_margin_left">35dp</dimen>
<dimen name="snack_bar_size">200dp</dimen>
<dimen name="pager_tab_strip_text">14sp</dimen>
<dimen name="pro_pic_size">40dp</dimen>
<dimen name="tweet_activ_margin">6dp</dimen>
<dimen name="drawer_size_port">250dp</dimen>
<dimen name="drawer_size_land">210dp</dimen>
<dimen name="tutorial_text_size">14sp</dimen>
<dimen name="tutorial_bubble_1_size">100dp</dimen>
<dimen name="tutorial_bubble_2_size">120dp</dimen>
<dimen name="tutorial_bubble_3_size">100dp</dimen>
<dimen name="tutorial_bubble_4_size">120dp</dimen>
<dimen name="tutorial_bubble_5_size">80dp</dimen>
<dimen name="tutorial_bubble_padding">35dp</dimen>
<dimen name="header_condensed_height">230dp</dimen>
<dimen name="header_expanded_height">300dp</dimen>
<dimen name="header_holder_padding">2dp</dimen>
<dimen name="header_side_padding">5dp</dimen>
<dimen name="header_top_padding">10dp</dimen>
<dimen name="expansion_size">150dp</dimen>
<dimen name="settings_text_padding">16dp</dimen>
<dimen name="user_profile_card_padding">16dp</dimen>
<dimen name="user_profile_header_padding">16dp</dimen>
</resources>
``` | /content/code_sandbox/app/src/main/res/values/dimens.xml | xml | 2016-07-08T03:18:40 | 2024-08-14T02:54:51 | talon-for-twitter-android | klinker24/talon-for-twitter-android | 1,189 | 519 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
export {default as DatePicker} from './DatePicker';
``` | /content/code_sandbox/optimize/client/src/modules/components/DatePicker/index.tsx | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 38 |
```xml
import React from 'react';
import { utils } from '../../utils';
import LinkExternal from '../LinkExternal';
const UpLinkLink: React.FC<{ packageName: string; uplinkName: string }> = ({
packageName,
uplinkName,
}) => {
const link = utils.getUplink(uplinkName, packageName);
return link ? (
<LinkExternal to={link} variant="outline">
{uplinkName}
</LinkExternal>
) : (
<>{uplinkName}</>
);
};
export default UpLinkLink;
``` | /content/code_sandbox/packages/ui-components/src/components/UpLinks/UplinkLink.tsx | xml | 2016-04-15T16:21:12 | 2024-08-16T09:38:01 | verdaccio | verdaccio/verdaccio | 16,189 | 118 |
```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. -->
<!--
Overlays a Button on top of an ImageView. Via a RemoteViews the only way to set an image, apply
a color filter, and have API level 16+ compatibility, is to use an ImageView. There are some
similar methods for Button but they are either hidden, require too high an API level, or both.
The Button must be on top of the ImageView so that it can be tapped, and so that its text will
be read out by TalkBack.
-->
<FrameLayout
xmlns:android="path_to_url"
xmlns:tools="path_to_url"
tools:ignore="MergeRootFrame"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_weight="1">
<ImageView
android:id="@+id/button_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_gravity="start|center_vertical"
android:adjustViewBounds="true"
android:maxHeight="32dp"
android:maxWidth="32dp"
android:contentDescription="@null"
android:scaleType="centerInside"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="end"
android:gravity="start|center_vertical"
android:paddingStart="8dp"
android:singleLine="true"
android:textSize="13sp"
style="@style/WebNotificationButton"/>
</FrameLayout>
``` | /content/code_sandbox/libraries_res/chrome_res/src/main/res/layout/web_notification_button.xml | xml | 2016-07-04T07:28:36 | 2024-08-15T05:20:42 | AndroidChromium | JackyAndroid/AndroidChromium | 3,090 | 382 |
```xml
import { jsx } from '../../../src';
import { Canvas, Chart } from '../../../src';
import { Interval, Legend, Axis } from '../../../src/components';
import { createContext, delay, gestureSimulator } from '../../util';
const data = [
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: -110 },
];
describe('Interval', () => {
it('legend ', async () => {
const context = createContext();
const { type, props } = (
<Canvas context={context} pixelRatio={1}>
<Chart data={data}>
<Legend />
<Axis field="genre" />
<Axis field="sold" />
<Interval x="genre" y="sold" color="genre" />
</Chart>
</Canvas>
);
const canvas = new Canvas(props);
await canvas.render();
await delay(800);
expect(context).toMatchImageSnapshot();
await gestureSimulator(context.canvas, 'click', { x: 165, y: 26 });
await delay(500);
expect(context).toMatchImageSnapshot();
await gestureSimulator(context.canvas, 'click', { x: 109, y: 24 });
await delay(500);
expect(context).toMatchImageSnapshot();
await gestureSimulator(context.canvas, 'click', { x: 165, y: 26 });
await delay(800);
expect(context).toMatchImageSnapshot();
});
});
``` | /content/code_sandbox/packages/f2/test/components/legend/interval.test.tsx | xml | 2016-08-29T06:26:23 | 2024-08-16T15:50:14 | F2 | antvis/F2 | 7,877 | 346 |
```xml
import { outputFile, pathExists, readFile } from 'fs-extra';
import type { TestCase } from 'junit-xml';
import { getJunitXml } from 'junit-xml';
import { join, resolve } from 'path';
import { prompt } from 'prompts';
import invariant from 'tiny-invariant';
import { dedent } from 'ts-dedent';
import {
allTemplates as TEMPLATES,
type Template,
type TemplateKey,
} from '../code/lib/cli-storybook/src/sandbox-templates';
import { version } from '../code/package.json';
import { bench } from './tasks/bench';
import { build } from './tasks/build';
import { check } from './tasks/check';
import { chromatic } from './tasks/chromatic';
import { compile } from './tasks/compile';
import { dev } from './tasks/dev';
import { e2eTestsBuild } from './tasks/e2e-tests-build';
import { e2eTestsDev } from './tasks/e2e-tests-dev';
import { generate } from './tasks/generate';
import { install } from './tasks/install';
import { publish } from './tasks/publish';
import { runRegistryTask } from './tasks/run-registry';
import { sandbox } from './tasks/sandbox';
import { serve } from './tasks/serve';
import { smokeTest } from './tasks/smoke-test';
import { syncDocs } from './tasks/sync-docs';
import { testRunnerBuild } from './tasks/test-runner-build';
import { testRunnerDev } from './tasks/test-runner-dev';
import { vitestTests } from './tasks/vitest-test';
import { CODE_DIRECTORY, JUNIT_DIRECTORY, SANDBOX_DIRECTORY } from './utils/constants';
import type { OptionValues } from './utils/options';
import { createOptions, getCommand, getOptionsOrPrompt } from './utils/options';
const sandboxDir = process.env.SANDBOX_ROOT || SANDBOX_DIRECTORY;
export const extraAddons = ['a11y', 'storysource'];
export type Path = string;
export type TemplateDetails = {
key: TemplateKey;
selectedTask: TaskKey;
template: Template;
codeDir: Path;
sandboxDir: Path;
builtSandboxDir: Path;
junitFilename: Path;
};
type MaybePromise<T> = T | Promise<T>;
export type Task = {
/** A description of the task for a prompt */
description: string;
/**
* Does this task represent a service for another task?
*
* Unlink other tasks, if a service is not ready, it doesn't mean the subsequent tasks must be out
* of date. As such, services will never be reset back to, although they will be started if
* dependent tasks are.
*/
service?: boolean;
/** Which tasks must be ready before this task can run */
dependsOn?: TaskKey[] | ((details: TemplateDetails, options: PassedOptionValues) => TaskKey[]);
/** Is this task already "ready", and potentially not required? */
ready: (details: TemplateDetails, options?: PassedOptionValues) => MaybePromise<boolean>;
/** Run the task */
run: (
details: TemplateDetails,
options: PassedOptionValues
) => MaybePromise<void | AbortController>;
/** Does this task handle its own junit results? */
junit?: boolean;
};
export const tasks = {
// These tasks pertain to the whole monorepo, rather than an
// individual template/sandbox
install,
compile,
check,
publish,
'sync-docs': syncDocs,
'run-registry': runRegistryTask,
// These tasks pertain to a single sandbox in the ../sandboxes dir
generate,
sandbox,
dev,
'smoke-test': smokeTest,
build,
serve,
'test-runner': testRunnerBuild,
'test-runner-dev': testRunnerDev,
chromatic,
'e2e-tests': e2eTestsBuild,
'e2e-tests-dev': e2eTestsDev,
bench,
'vitest-integration': vitestTests,
};
type TaskKey = keyof typeof tasks;
function isSandboxTask(taskKey: TaskKey) {
return !['install', 'compile', 'publish', 'run-registry', 'check', 'sync-docs'].includes(taskKey);
}
export const options = createOptions({
task: {
type: 'string',
description: 'Which task would you like to run?',
values: Object.keys(tasks) as TaskKey[],
valueDescriptions: Object.values(tasks).map((t) => `${t.description} (${getTaskKey(t)})`),
required: true,
},
startFrom: {
type: 'string',
description: 'Which task should we start execution from?',
values: [...(Object.keys(tasks) as TaskKey[]), 'never', 'auto'] as const,
// This is prompted later based on information about what's ready
promptType: false,
},
template: {
type: 'string',
description: 'What template would you like to make a sandbox for?',
values: Object.keys(TEMPLATES) as TemplateKey[],
required: ({ task }) => !task || isSandboxTask(task),
promptType: (_, { task }) => isSandboxTask(task),
},
// // TODO -- feature flags
// sandboxDir: {
// type: 'string',
// description: 'What is the name of the directory the sandbox runs in?',
// promptType: false,
// },
addon: {
type: 'string[]',
description: 'Which extra addons (beyond the CLI defaults) would you like installed?',
values: extraAddons,
promptType: (_, { task }) => isSandboxTask(task),
},
link: {
type: 'boolean',
description: 'Build code and link for local development?',
inverse: true,
promptType: false,
},
prod: {
type: 'boolean',
description: 'Build code for production',
promptType: false,
},
dryRun: {
type: 'boolean',
description: "Don't execute commands, just list them (dry run)?",
promptType: false,
},
debug: {
type: 'boolean',
description: 'Print all the logs to the console',
promptType: false,
},
junit: {
type: 'boolean',
description: 'Store results in junit format?',
promptType: false,
},
skipTemplateStories: {
type: 'boolean',
description: 'Do not include template stories and their addons',
promptType: false,
},
disableDocs: {
type: 'boolean',
description: 'Disable addon-docs from essentials',
promptType: false,
},
});
export type PassedOptionValues = Omit<OptionValues<typeof options>, 'task' | 'startFrom' | 'junit'>;
const logger = console;
function getJunitFilename(taskKey: TaskKey) {
return join(JUNIT_DIRECTORY, `${taskKey}.xml`);
}
async function writeJunitXml(
taskKey: TaskKey,
templateKey: TemplateKey,
startTime: Date,
err?: Error,
systemError?: boolean
) {
let errorData = {};
if (err) {
// we want to distinguish whether the error comes from the tests we are running or from arbitrary code
errorData = systemError ? { errors: [{ message: err.stack }] } : { errors: [err] };
}
const name = `${taskKey} - ${templateKey}`;
const time = (Date.now() - +startTime) / 1000;
const testCase = { name, assertions: 1, time, ...errorData };
// We store the metadata as a system-err.
// Which is a bit unfortunate but it seems that one can't store extra data when the task is successful.
// system-err won't turn the whole test suite as failing, which makes it a reasonable candidate
const metadata: TestCase = {
name: `${name} - metadata`,
systemErr: [JSON.stringify({ ...TEMPLATES[templateKey], id: templateKey, version })],
};
const suite = { name, timestamp: startTime, time, testCases: [testCase, metadata] };
const junitXml = getJunitXml({ time, name, suites: [suite] });
const path = getJunitFilename(taskKey);
await outputFile(path, junitXml);
logger.log(`Test results written to ${resolve(path)}`);
}
function getTaskKey(task: Task): TaskKey {
return (Object.entries(tasks) as [TaskKey, Task][]).find(([_, t]) => t === task)[0];
}
/** Get a list of tasks that need to be (possibly) run, in order, to be able to run `finalTask`. */
function getTaskList(finalTask: Task, details: TemplateDetails, optionValues: PassedOptionValues) {
const taskDeps = new Map<Task, Task[]>();
// Which tasks depend on a given task
const tasksThatDepend = new Map<Task, Task[]>();
const addTask = (task: Task, dependent?: Task) => {
if (tasksThatDepend.has(task)) {
if (!dependent) {
throw new Error('Unexpected task without dependent seen a second time');
}
tasksThatDepend.set(task, tasksThatDepend.get(task).concat(dependent));
return;
}
// This is the first time we've seen this task
tasksThatDepend.set(task, dependent ? [dependent] : []);
const dependedTaskNames =
typeof task.dependsOn === 'function'
? task.dependsOn(details, optionValues)
: task.dependsOn || [];
const dependedTasks = dependedTaskNames.map((n) => tasks[n]);
taskDeps.set(task, dependedTasks);
dependedTasks.forEach((t) => addTask(t, task));
};
addTask(finalTask);
// We need to sort the tasks topologically so we run each task before the tasks that
// depend on it. This is Kahn's algorithm :shrug:
const sortedTasks = [] as Task[];
const tasksWithoutDependencies = [finalTask];
while (taskDeps.size !== sortedTasks.length) {
const task = tasksWithoutDependencies.pop();
if (!task) {
throw new Error('Topological sort failed, is there a cyclic task dependency?');
}
sortedTasks.unshift(task);
taskDeps.get(task).forEach((depTask) => {
const remainingTasksThatDepend = tasksThatDepend
.get(depTask)
.filter((t) => !sortedTasks.includes(t));
if (remainingTasksThatDepend.length === 0) {
tasksWithoutDependencies.push(depTask);
}
});
}
return { sortedTasks, tasksThatDepend };
}
type TaskStatus =
| 'ready'
| 'unready'
| 'running'
| 'complete'
| 'failed'
| 'serving'
| 'notserving';
const statusToEmoji: Record<TaskStatus, string> = {
ready: '',
unready: '',
running: '',
complete: '',
failed: '',
serving: '',
notserving: '',
};
function writeTaskList(statusMap: Map<Task, TaskStatus>) {
logger.info(
[...statusMap.entries()]
.map(([task, status]) => `${statusToEmoji[status]} ${getTaskKey(task)}`)
.join(' > ')
);
logger.info();
}
async function runTask(task: Task, details: TemplateDetails, optionValues: PassedOptionValues) {
const { junitFilename } = details;
const startTime = new Date();
try {
let updatedOptions = optionValues;
if (details.template?.modifications?.skipTemplateStories) {
updatedOptions = { ...updatedOptions, skipTemplateStories: true };
}
if (details.template?.modifications?.disableDocs) {
updatedOptions = { ...updatedOptions, disableDocs: true };
}
const controller = await task.run(details, updatedOptions);
if (junitFilename && !task.junit) {
await writeJunitXml(getTaskKey(task), details.key, startTime);
}
return controller;
} catch (err) {
invariant(err instanceof Error);
const hasJunitFile = await pathExists(junitFilename);
// If there's a non-test related error (junit report has not been reported already), we report the general failure in a junit report
if (junitFilename && !hasJunitFile) {
await writeJunitXml(getTaskKey(task), details.key, startTime, err, true);
}
throw err;
} finally {
if (await pathExists(junitFilename)) {
const junitXml = await (await readFile(junitFilename)).toString();
const prefixedXml = junitXml.replace(/classname="(.*)"/g, `classname="${details.key} $1"`);
await outputFile(junitFilename, prefixedXml);
}
}
}
const controllers: AbortController[] = [];
async function run() {
// useful for other scripts to know whether they're running in the creation of a sandbox in the monorepo
process.env.IN_STORYBOOK_SANDBOX = 'true';
const allOptionValues = await getOptionsOrPrompt('yarn task', options);
const { task: taskKey, startFrom, junit, ...optionValues } = allOptionValues;
const finalTask = tasks[taskKey];
const { template: templateKey } = optionValues;
const template = TEMPLATES[templateKey];
const templateSandboxDir = templateKey && join(sandboxDir, templateKey.replace('/', '-'));
const details: TemplateDetails = {
key: templateKey,
template,
codeDir: CODE_DIRECTORY,
selectedTask: taskKey,
sandboxDir: templateSandboxDir,
builtSandboxDir: templateKey && join(templateSandboxDir, 'storybook-static'),
junitFilename: junit && getJunitFilename(taskKey),
};
const { sortedTasks, tasksThatDepend } = getTaskList(finalTask, details, optionValues);
const sortedTasksReady = await Promise.all(
sortedTasks.map((t) => t.ready(details, optionValues))
);
if (templateKey) {
logger.info(` Selected sandbox: ${templateKey}`);
logger.info();
}
logger.info(`Task readiness up to ${taskKey}`);
const initialTaskStatus = (task: Task, ready: boolean) => {
if (task.service) {
return ready ? 'serving' : 'notserving';
}
return ready ? 'ready' : 'unready';
};
const statuses = new Map<Task, TaskStatus>(
sortedTasks.map((task, index) => [task, initialTaskStatus(task, sortedTasksReady[index])])
);
writeTaskList(statuses);
function setUnready(task: Task) {
// If the task is a service we don't need to set it unready but we still need to do so for
// it's dependencies
// If the task is a service we don't need to set it unready but we still need to do so for
// it's dependencies
if (!task.service) {
statuses.set(task, 'unready');
}
tasksThatDepend
.get(task)
.filter((t) => !t.service)
.forEach(setUnready);
}
// NOTE: we don't include services in the first unready task. We only need to rewind back to a
// service if the user explicitly asks. It's expected that a service is no longer running.
const firstUnready = sortedTasks.find((task) => statuses.get(task) === 'unready');
if (startFrom === 'auto') {
// Don't reset anything!
} else if (startFrom === 'never') {
if (!firstUnready) {
throw new Error(`Task ${taskKey} is ready`);
}
if (firstUnready !== finalTask) {
throw new Error(`Task ${getTaskKey(firstUnready)} was not ready`);
}
} else if (startFrom) {
// set to reset back to a specific task
if (firstUnready && sortedTasks.indexOf(tasks[startFrom]) > sortedTasks.indexOf(firstUnready)) {
throw new Error(
`Task ${getTaskKey(firstUnready)} was not ready, earlier than your request ${startFrom}.`
);
}
setUnready(tasks[startFrom]);
} else if (firstUnready === sortedTasks[0]) {
// We need to do everything, no need to change anything
} else if (sortedTasks.length === 1) {
setUnready(sortedTasks[0]);
} else {
// We don't know what to do! Let's ask
const { startFromTask } = await prompt(
{
type: 'select',
message: firstUnready
? `We need to run all tasks from ${getTaskKey(
firstUnready
)} onwards, would you like to start from an earlier task?`
: `Which task would you like to start from?`,
name: 'startFromTask',
choices: sortedTasks
.slice(0, firstUnready && sortedTasks.indexOf(firstUnready) + 1)
.reverse()
.map((t) => ({
title: `${t.description} (${getTaskKey(t)})`,
value: t,
})),
},
{
onCancel: () => {
logger.log('Command cancelled by the user. Exiting...');
process.exit(1);
},
}
);
setUnready(startFromTask);
}
for (let i = 0; i < sortedTasks.length; i += 1) {
const task = sortedTasks[i];
const status = statuses.get(task);
let shouldRun = status === 'unready';
if (status === 'notserving') {
shouldRun =
finalTask === task ||
!!tasksThatDepend.get(task).find((t) => statuses.get(t) === 'unready');
}
if (shouldRun) {
statuses.set(task, 'running');
writeTaskList(statuses);
try {
const controller = await runTask(task, details, {
...optionValues,
// Always debug the final task so we can see it's output fully
debug: task === finalTask ? true : optionValues.debug,
});
if (controller) {
controllers.push(controller);
}
} catch (err) {
invariant(err instanceof Error);
logger.error(`Error running task ${getTaskKey(task)}:`);
logger.error(JSON.stringify(err, null, 2));
if (process.env.CI) {
logger.error(
dedent`
To reproduce this error locally, run:
${getCommand('yarn task', options, {
...allOptionValues,
link: true,
startFrom: 'auto',
})}
Note this uses locally linking which in rare cases behaves differently to CI. For a closer match, run:
${getCommand('yarn task', options, {
...allOptionValues,
startFrom: 'auto',
})}`
);
}
controllers.forEach((controller) => {
controller.abort();
});
throw err;
}
statuses.set(task, task.service ? 'serving' : 'complete');
// If the task is a service, we want to stay open until we are ctrl-ced
if (sortedTasks[i] === finalTask && finalTask.service) {
await new Promise(() => {});
}
}
}
return 0;
}
process.on('exit', () => {
// Make sure to kill any running tasks
controllers.forEach((controller) => {
controller.abort();
});
});
run()
.then((status) => process.exit(status))
.catch((err) => {
logger.error();
logger.error(err);
process.exit(1);
});
``` | /content/code_sandbox/scripts/task.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 4,327 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="path_to_url"
xmlns:xsi="path_to_url"
xmlns:dubbo="path_to_url"
xsi:schemaLocation="path_to_url
path_to_url
path_to_url
path_to_url">
<!-- -->
<dubbo:application name="goshop-service-goods" />
<!-- redis-->
<dubbo:registry address="${dubbo.address}" check="false" />
<!-- multicast
<dubbo:registry address="multicast://224.5.6.7:1234?unicast=false" check="false"/>-->
<!-- zookeeper
<dubbo:registry protocol="zookeeper" address="127.0.0.1:2181" check="false" />-->
<!-- protocol="registry"
<dubbo:monitor protocol="registry"/>-->
<!-- ProtocolConfigServiceConfig, -->
<dubbo:provider timeout="10000" threadpool="fixed" threads="100" accepts="1000" />
<!---->
<dubbo:protocol name="dubbo" dispatcher="all" threadpool="fixed" threads="20" port="28883" />
<!-- -->
<dubbo:service retries="0" interface="org.goshop.goods.i.GoodsClassService" ref="goodsClassService" />
<dubbo:service retries="0" interface="org.goshop.goods.i.GoodsTypeService" ref="goodsTypeService" />
</beans>
``` | /content/code_sandbox/goshop-service-goods/src/main/resources/spring/applicationContext-dubbo-provider.xml | xml | 2016-06-18T10:16:23 | 2024-08-01T09:11:36 | goshop2 | pzhgugu/goshop2 | 1,106 | 339 |
```xml
import visit from 'unist-util-visit'
import { Node } from 'unist'
import { mermaidAPI } from 'mermaid'
import rehypeParse from 'rehype-parse'
import unified from 'unified'
import { randomBytes } from 'crypto'
const SUPPORTED = ['flowchart', 'mermaid', 'sequence', 'chart', 'chart(yaml)']
export function remarkCharts() {
return (tree: Node) => {
visit(tree, 'code', (node) => {
if (typeof node.lang !== 'string' || !SUPPORTED.includes(node.lang)) {
return
}
node.type = node.lang
node.data = {
hName: node.lang,
hChildren: [{ type: 'text', value: node.value }],
hProperties: {
className: [node.lang],
},
}
})
}
}
export function rehypeMermaid() {
return async (tree: Node) => {
const mermaidNodes: Node[] = []
visit(tree, { tagName: 'mermaid' }, (node: any) => {
mermaidNodes.push(node)
})
const parser = unified().use(rehypeParse, { fragment: true })
await Promise.all(
mermaidNodes.map(async (node: any) => {
node.tagName = 'div'
const value = node.children[0].value
try {
const svg: string = await new Promise((res) => {
mermaidAPI.render(
`mermaid-${randomBytes(8).toString('hex')}`,
value,
res
)
})
node.children = parser.parse(svg).children
} catch (err) {
node.children = [{ type: 'text', value: err.message }]
}
})
)
}
}
``` | /content/code_sandbox/src/cloud/lib/charts/remarkCharts.ts | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 383 |
```xml
import {IListItem} from "./IListItem";
export interface INewsListItem extends IListItem {
newsheader: string;
newsbody: string;
expiryDate: Date;
}
``` | /content/code_sandbox/samples/react-designpatterns-typescript/FactoryMethod/src/webparts/factoryMethod/components/models/INewsListItem.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 40 |
```xml
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { ConfirmPopupDocModule } from '@doc/confirmpopup/confirmpopupdoc.module';
import { ConfirmPopupDemo } from './confirmpopupdemo';
import { ConfirmPopupDemoRoutingModule } from './confirmpopupdemo-routing.module';
@NgModule({
imports: [CommonModule, ConfirmPopupDemoRoutingModule, ConfirmPopupDocModule],
declarations: [ConfirmPopupDemo]
})
export class ConfirmPopupDemoModule {}
``` | /content/code_sandbox/src/app/showcase/pages/confirmpopup/confirmpopupdemo.module.ts | xml | 2016-01-16T09:23:28 | 2024-08-16T19:58:20 | primeng | primefaces/primeng | 9,969 | 106 |
```xml
import { fetchPolaris } from '../utils';
export const getDepositStatement = async (subdomain, params) => {
const balance = await fetchPolaris({
op: '13610302',
data: [
{
acntCode: params.number,
startDate: params.startDate,
endDate: params.endDate,
orderBy: 'desc',
seeNotFinancial: 0,
seeCorr: 0,
seeReverse: 0,
startPosition: 0,
count: 100,
},
],
subdomain,
}).then((res) => JSON.parse(res));
return balance;
};
``` | /content/code_sandbox/packages/plugin-syncpolaris-api/src/utils/deposit/getDepositStatement.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 136 |
```xml
import { Entity } from "../../../../src/decorator/entity/Entity"
import { Column } from "../../../../src/decorator/columns/Column"
import { PrimaryGeneratedColumn } from "../../../../src/decorator/columns/PrimaryGeneratedColumn"
import { OneToMany } from "../../../../src/decorator/relations/OneToMany"
import { Category } from "./Category"
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@OneToMany((type) => Category, (category) => category.post)
categories: Promise<Category[]>
}
``` | /content/code_sandbox/test/github-issues/996/entity/Post.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 122 |
```xml
/*your_sha256_hash-----------------------------
*your_sha256_hash----------------------------*/
import * as assert from 'assert';
import StatusView from '../../src/views/statusView';
import * as LocalizedConstants from '../../src/constants/localizedConstants';
suite('Status View Tests', () => {
test('updateStatusMessage should not immediately update status message for definition request', (done) => {
return new Promise((resolve, reject) => {
let statusView = new StatusView();
let newStatus = LocalizedConstants.definitionRequestedStatus;
let currentStatus = '';
let getCurrentStatus = () => {
return currentStatus;
};
let actualStatusMessage = '';
let expectedStatusMessage = LocalizedConstants.gettingDefinitionMessage;
let updateMessage = (message) => {
actualStatusMessage = message;
};
statusView.updateStatusMessage(newStatus, getCurrentStatus, updateMessage);
assert.equal(actualStatusMessage, '');
setTimeout(() => {
assert.equal(actualStatusMessage, expectedStatusMessage);
}, 600);
statusView.dispose();
done();
});
});
test('updateStatusMessage should not update status message for definition request if already completed', (done) => {
return new Promise((resolve, reject) => {
let statusView = new StatusView();
let newStatus = LocalizedConstants.definitionRequestedStatus;
let currentStatus = LocalizedConstants.definitionRequestCompletedStatus;
let getCurrentStatus = () => {
return currentStatus;
};
let actualStatusMessage = '';
let expectedStatusMessage = '';
let updateMessage = (message) => {
actualStatusMessage = message;
};
statusView.updateStatusMessage(newStatus, getCurrentStatus, updateMessage);
assert.equal(actualStatusMessage, '');
setTimeout(() => {
assert.equal(actualStatusMessage, expectedStatusMessage);
}, 600);
statusView.dispose();
done();
});
});
test('updateStatusMessage should update status message for definition request completed', (done) => {
return new Promise((resolve, reject) => {
let statusView = new StatusView();
let newStatus = LocalizedConstants.definitionRequestCompletedStatus;
let currentStatus = LocalizedConstants.definitionRequestCompletedStatus;
let getCurrentStatus = () => {
return currentStatus;
};
let actualStatusMessage = '';
let expectedStatusMessage = '';
let updateMessage = (message) => {
actualStatusMessage = message;
};
statusView.updateStatusMessage(newStatus, getCurrentStatus, updateMessage);
assert.equal(actualStatusMessage, expectedStatusMessage);
statusView.dispose();
done();
});
});
test('updateStatusMessage should update status message for updating intelliSense', (done) => {
return new Promise((resolve, reject) => {
let statusView = new StatusView();
let newStatus = LocalizedConstants.updatingIntelliSenseStatus;
let currentStatus = '';
let getCurrentStatus = () => {
return currentStatus;
};
let actualStatusMessage = '';
let expectedStatusMessage = LocalizedConstants.updatingIntelliSenseLabel;
let updateMessage = (message) => {
actualStatusMessage = message;
};
statusView.updateStatusMessage(newStatus, getCurrentStatus, updateMessage);
assert.equal(actualStatusMessage, expectedStatusMessage);
statusView.dispose();
done();
});
});
test('updateStatusMessage should update status message for intelliSense updated status', (done) => {
return new Promise((resolve, reject) => {
let statusView = new StatusView();
let newStatus = LocalizedConstants.intelliSenseUpdatedStatus;
let currentStatus = '';
let getCurrentStatus = () => {
return currentStatus;
};
let actualStatusMessage = '';
let expectedStatusMessage = '';
let updateMessage = (message) => {
actualStatusMessage = message;
};
statusView.updateStatusMessage(newStatus, getCurrentStatus, updateMessage);
assert.equal(actualStatusMessage, expectedStatusMessage);
statusView.dispose();
done();
});
});
});
``` | /content/code_sandbox/test/unit/statusView.test.ts | xml | 2016-06-26T04:38:04 | 2024-08-16T20:04:12 | vscode-mssql | microsoft/vscode-mssql | 1,523 | 868 |
```xml
import Link from "next/link";
export default function Header() {
return (
<div>
<Link href="/" style={{ marginRight: 10 }}>
Home
</Link>
<Link href="/about" style={{ marginRight: 10 }}>
About
</Link>
</div>
);
}
``` | /content/code_sandbox/examples/with-dynamic-import/components/Header.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 68 |
```xml
import type { Logger } from '@apollo/utils.logger';
import type { ReferencedFieldsByType } from '@apollo/utils.usagereporting';
import LRUCache from 'lru-cache';
export interface OperationDerivedData {
signature: string;
referencedFieldsByType: ReferencedFieldsByType;
}
export function createOperationDerivedDataCache({
logger,
}: {
logger: Logger;
}): LRUCache<string, OperationDerivedData> {
let lastWarn: Date;
let lastDisposals = 0;
return new LRUCache<string, OperationDerivedData>({
// Calculate the length of cache objects by the JSON.stringify byteLength.
sizeCalculation(obj) {
return Buffer.byteLength(JSON.stringify(obj), 'utf8');
},
// 10MiB limit, very much approximately since we can't be sure how V8 might
// be storing this data internally. Though this should be enough to store a
// fair amount of operation data, depending on their overall complexity. A
// future version of this might expose some configuration option to grow the
// cache, but ideally, we could do that dynamically based on the resources
// available to the server, and not add more configuration surface area.
// Hopefully the warning message will allow us to evaluate the need with
// more validated input from those that receive it.
maxSize: Math.pow(2, 20) * 10,
dispose() {
// Count the number of disposals between warning messages.
lastDisposals++;
// Only show a message warning about the high turnover every 60 seconds.
if (!lastWarn || new Date().getTime() - lastWarn.getTime() > 60000) {
// Log the time that we last displayed the message.
lastWarn = new Date();
logger.warn(
[
'This server is processing a high number of unique operations. ',
`A total of ${lastDisposals} records have been `,
'ejected from the ApolloServerPluginUsageReporting signature cache in the past ',
'interval. If you see this warning frequently, please open an ',
'issue on the Apollo Server repository.',
].join(''),
);
// Reset the disposal counter for the next message interval.
lastDisposals = 0;
}
},
});
}
export function operationDerivedDataCacheKey(
queryHash: string,
operationName: string,
) {
return `${queryHash}${operationName && ':' + operationName}`;
}
``` | /content/code_sandbox/packages/server/src/plugin/usageReporting/operationDerivedDataCache.ts | xml | 2016-04-21T09:26:01 | 2024-08-16T19:32:15 | apollo-server | apollographql/apollo-server | 13,742 | 532 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.cyl.musiclake.ui.widget.LyricView
android:id="@+id/lyricShow"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="@dimen/dp_20"
android:clickable="true"
android:focusable="true"
app:highlightColor="@color/amber"
app:textAlign="center"
app:textColor="@color/white" />
</FrameLayout>
``` | /content/code_sandbox/app/src/main/res/layout/frag_player_lrcview.xml | xml | 2016-04-09T15:47:45 | 2024-08-14T04:30:04 | MusicLake | caiyonglong/MusicLake | 2,654 | 155 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<RootNamespace>ConsoleAppCosmosDb</RootNamespace>
<AssemblyName>ConsoleAppCosmosDb</AssemblyName>
<StartupObject>ConsoleAppCosmosDb.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\ConsoleApp_net452_CosmosDb\Entities\Entity.cs" Link="Entities\Entity.cs" />
<Compile Include="..\ConsoleApp_net452_CosmosDb\Entities\EntityData.cs" Link="Entities\EntityData.cs" />
<Compile Include="..\ConsoleApp_net452_CosmosDb\Entities\EntityReading.cs" Link="Entities\EntityReading.cs" />
<Compile Include="..\ConsoleApp_net452_CosmosDb\Entities\EntityReadingValue.cs" Link="Entities\EntityReadingValue.cs" />
<Compile Include="..\ConsoleApp_net452_CosmosDb\Program.cs" Link="Program.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.DocumentDB.Core" Version="2.5.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.Linq.Dynamic.Core\System.Linq.Dynamic.Core.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Entities\" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/src-console/ConsoleApp_netcore2.1_CosmosDb/ConsoleApp_netcore2.1_CosmosDb.csproj | xml | 2016-04-08T16:41:51 | 2024-08-16T05:55:59 | System.Linq.Dynamic.Core | zzzprojects/System.Linq.Dynamic.Core | 1,537 | 317 |
```xml
export class OrganizationSubscriptionUpdateRequest {
/**
* The number of seats to add or remove from the subscription.
* Applies to both PM and SM request types.
*/
seatAdjustment: number;
/**
* The maximum number of seats that can be auto-scaled for the subscription.
* Applies to both PM and SM request types.
*/
maxAutoscaleSeats?: number;
/**
* Build a subscription update request for the Password Manager product type.
* @param seatAdjustment - The number of seats to add or remove from the subscription.
* @param maxAutoscaleSeats - The maximum number of seats that can be auto-scaled for the subscription.
*/
constructor(seatAdjustment: number, maxAutoscaleSeats?: number) {
this.seatAdjustment = seatAdjustment;
this.maxAutoscaleSeats = maxAutoscaleSeats;
}
}
``` | /content/code_sandbox/libs/common/src/billing/models/request/organization-subscription-update.request.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 194 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE library PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN"
"path_to_url">
(See accompanying file LICENSE_1_0.txt or path_to_url
-->
<section id="string_algo.concept" last-revision="$Date$">
<title>Concepts</title>
<using-namespace name="boost"/>
<using-namespace name="boost::algorithm"/>
<section>
<title>Definitions</title>
<table>
<title>Notation</title>
<tgroup cols="2" align="left">
<tbody>
<row>
<entry><code>F</code></entry>
<entry>A type that is a model of Finder</entry>
</row>
<row>
<entry><code>Fmt</code></entry>
<entry>A type that is a model of Formatter</entry>
</row>
<row>
<entry><code>Iter</code></entry>
<entry>
Iterator Type
</entry>
</row>
<row>
<entry><code>f</code></entry>
<entry>Object of type <code>F</code></entry>
</row>
<row>
<entry><code>fmt</code></entry>
<entry>Object of type <code>Fmt</code></entry>
</row>
<row>
<entry><code>i,j</code></entry>
<entry>Objects of type <code>Iter</code></entry>
</row>
</tbody>
</tgroup>
</table>
</section>
<section id="string_algo.finder_concept">
<title>Finder Concept</title>
<para>
Finder is a functor which searches for an arbitrary part of a container.
The result of the search is given as an <classname>iterator_range</classname>
delimiting the selected part.
</para>
<table>
<title>Valid Expressions</title>
<tgroup cols="3" align="left">
<thead>
<row>
<entry>Expression</entry>
<entry>Return Type</entry>
<entry>Effects</entry>
</row>
</thead>
<tbody>
<row>
<entry><code>f(i,j)</code></entry>
<entry>Convertible to <code>iterator_range<Iter></code></entry>
<entry>Perform the search on the interval [i,j) and returns the result of the search</entry>
</row>
</tbody>
</tgroup>
</table>
<para>
Various algorithms need to perform a search in a container and a Finder is a generalization of such
search operations that allows algorithms to abstract from searching. For instance, generic replace
algorithms can replace any part of the input, and the Finder is used to select the desired one.
</para>
<para>
Note, that it is only required that the finder works with a particular iterator type. However,
a Finder operation can be defined as a template, allowing the Finder to work with any iterator.
</para>
<para>
<emphasis role="bold">Examples</emphasis>
</para>
<para>
<itemizedlist>
<listitem>
Finder implemented as a class. This Finder always returns the whole input as a match. <code>operator()</code>
is templated, so that the finder can be used on any iterator type.
<programlisting>
struct simple_finder
{
template<typename ForwardIteratorT>
boost::iterator_range<ForwardIteratorT> operator()(
ForwardIteratorT Begin,
ForwardIteratorT End )
{
return boost::make_range( Begin, End );
}
};
</programlisting>
</listitem>
<listitem>
Function Finder. Finder can be any function object. That is, any ordinary function with the
required signature can be used as well. However, such a function can be used only for
a specific iterator type.
<programlisting>
boost::iterator_range<std::string> simple_finder(
std::string::const_iterator Begin,
std::string::const_iterator End )
{
return boost::make_range( Begin, End );
}
</programlisting>
</listitem>
</itemizedlist>
</para>
</section>
<section id="string_algo.formatter_concept">
<title>Formatter concept</title>
<para>
Formatters are used by <link linkend="string_algo.replace">replace algorithms</link>.
They are used in close combination with finders.
A formatter is a functor, which takes a result from a Finder operation and transforms it in a specific way.
The operation of the formatter can use additional information provided by a specific finder,
for example <functionname>regex_formatter()</functionname> uses the match information from
<functionname>regex_finder()</functionname> to format the result of formatter operation.
</para>
<table>
<title>Valid Expressions</title>
<tgroup cols="3" align="left">
<thead>
<row>
<entry>Expression</entry>
<entry>Return Type</entry>
<entry>Effects</entry>
</row>
</thead>
<tbody>
<row>
<entry><code>fmt(f(i,j))</code></entry>
<entry>A container type, accessible using container traits</entry>
<entry>Formats the result of the finder operation</entry>
</row>
</tbody>
</tgroup>
</table>
<para>
Similarly to finders, formatters generalize format operations. When a finder is used to
select a part of the input, formatter takes this selection and performs some formatting
on it. Algorithms can abstract from formatting using a formatter.
</para>
<para>
<emphasis role="bold">Examples</emphasis>
</para>
<para>
<itemizedlist>
<listitem>
Formatter implemented as a class. This Formatter does not perform any formatting and
returns the match, repackaged. <code>operator()</code>
is templated, so that the Formatter can be used on any Finder type.
<programlisting>
struct simple_formatter
{
template<typename FindResultT>
std::string operator()( const FindResultT& Match )
{
std::string Temp( Match.begin(), Match.end() );
return Temp;
}
};
</programlisting>
</listitem>
<listitem>
Function Formatter. Similarly to Finder, Formatter can be any function object.
However, as a function, it can be used only with a specific Finder type.
<programlisting>
std::string simple_formatter( boost::iterator_range<std::string::const_iterator>& Match )
{
std::string Temp( Match.begin(), Match.end() );
return Temp;
}
</programlisting>
</listitem>
</itemizedlist>
</para>
</section>
</section>
``` | /content/code_sandbox/deps/boost_1_66_0/libs/algorithm/string/doc/concept.xml | xml | 2016-09-05T10:18:44 | 2024-08-11T13:21:40 | LiquidCore | LiquidPlayer/LiquidCore | 1,010 | 1,582 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="path_to_url">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{798E3AE4-A984-43FF-8928-EACFF43F56AE}</ProjectGuid>
<RootNamespace>cletest</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir).\x64\Debug\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">.\x64\Debug\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir).\x64\Release\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">.\x64\Release\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\..\include\layout;..\..\..\include;..\..\common;..\..\tools\ctestfw;..\..\tools\toolutil;..\..\layout;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<LanguageStandard>stdcpp17</LanguageStandard>
<LanguageStandard_C>stdc11</LanguageStandard_C>
</ClCompile>
<Link>
<AdditionalDependencies>..\..\..\lib\icuucd.lib;..\..\..\lib\icuind.lib;..\..\..\lib\icutestd.lib;..\..\..\lib\icutud.lib;..\..\..\lib\iculed.lib;..\..\..\lib\iculxd.lib;%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<TargetMachine>NotSet</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>..\..\..\include\layout;..\..\..\include;..\..\common;..\..\tools\ctestfw;..\..\tools\toolutil;..\..\layout;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalDependencies>..\..\..\lib\icuuc.lib;..\..\..\lib\icuin.lib;..\..\..\lib\icutest.lib;..\..\..\lib\icutu.lib;..\..\..\lib\icule.lib;..\..\..\lib\iculx.lib;%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>NotSet</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\..\include\layout;..\..\..\include;..\..\common;..\..\tools\ctestfw;..\..\tools\toolutil;..\..\layout;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN64;WIN32;_DEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalDependencies>..\..\..\lib64\icuucd.lib;..\..\..\lib64\icuind.lib;..\..\..\lib64\icutestd.lib;..\..\..\lib64\icutud.lib;..\..\..\lib64\iculed.lib;..\..\..\lib64\iculxd.lib;%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<AdditionalIncludeDirectories>..\..\..\include\layout;..\..\..\include;..\..\common;..\..\tools\ctestfw;..\..\tools\toolutil;..\..\layout;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN64;WIN32;NDEBUG;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalDependencies>..\..\..\lib64\icuuc.lib;..\..\..\lib64\icuin.lib;..\..\..\lib64\icutest.lib;..\..\..\lib64\icutu.lib;..\..\..\lib64\icule.lib;..\..\..\lib64\iculx.lib;%(AdditionalDependencies)</AdditionalDependencies>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="cfonts.cpp" />
<ClCompile Include="cletest.c" />
<ClCompile Include="cmaps.cpp" />
<ClCompile Include="FontObject.cpp" />
<ClCompile Include="FontTableCache.cpp" />
<ClCompile Include="letest.cpp" />
<ClCompile Include="letsutil.cpp" />
<ClCompile Include="PortableFontInstance.cpp" />
<ClCompile Include="SimpleFontInstance.cpp" />
<ClCompile Include="xmlreader.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="cfonts.h" />
<ClInclude Include="cmaps.h" />
<ClInclude Include="FontObject.h" />
<ClInclude Include="FontTableCache.h" />
<ClInclude Include="letest.h" />
<ClInclude Include="letsutil.h" />
<ClInclude Include="PortableFontInstance.h" />
<ClInclude Include="sfnt.h" />
<ClInclude Include="SimpleFontInstance.h" />
<ClInclude Include="xmlreader.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
``` | /content/code_sandbox/icu4c/source/test/letest/cletest.vcxproj | xml | 2016-01-08T02:42:32 | 2024-08-16T18:14:55 | icu | unicode-org/icu | 2,693 | 2,790 |
```xml
import { makeStyles } from '@griffel/react';
import { SlotClassNames } from '@fluentui/react-utilities';
import type { TextSlots } from '../../Text/Text.types';
import { typographyStyles } from '@fluentui/react-theme';
export const body2ClassNames: SlotClassNames<TextSlots> = {
root: 'fui-Body2',
};
/**
* Styles for the root slot
*/
export const useBody2Styles = makeStyles({
root: typographyStyles.body2,
});
``` | /content/code_sandbox/packages/react-components/react-text/library/src/components/presets/Body2/useBody2Styles.styles.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 106 |
```xml
/** @jsxRuntime automatic */
/** @jsxImportSource @fluentui/react-jsx-runtime */
import { assertSlots } from '@fluentui/react-utilities';
import type { TableBodyState, TableBodySlots } from './TableBody.types';
/**
* Render the final JSX of TableBody
*/
export const renderTableBody_unstable = (state: TableBodyState) => {
assertSlots<TableBodySlots>(state);
return <state.root />;
};
``` | /content/code_sandbox/packages/react-components/react-table/library/src/components/TableBody/renderTableBody.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 97 |
```xml
import * as React from 'react';
import {
I18nContextProvider,
RecordContextProvider,
ResourceContext,
} from 'ra-core';
import { TextField } from './field';
import { Labeled } from './Labeled';
import { Box, Stack } from '@mui/material';
export default { title: 'ra-ui-materialui/detail/Labeled' };
const record = {
id: 1,
title: 'War and Peace',
author: 'Leo Tolstoy',
summary:
"War and Peace broadly focuses on Napoleon's invasion of Russia, and the impact it had on Tsarist society. The book explores themes such as revolution, revolution and empire, the growth and decline of various states and the impact it had on their economies, culture, and society.",
year: 1869,
};
export const Basic = () => (
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Labeled>
<TextField source="title" />
</Labeled>
</RecordContextProvider>
</ResourceContext.Provider>
);
export const LabelIntrospection = () => (
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Labeled>
<TextField label="My custom Title" source="title" />
</Labeled>
</RecordContextProvider>
</ResourceContext.Provider>
);
export const Label = () => (
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Labeled label="My custom Title">
<TextField source="title" />
</Labeled>
</RecordContextProvider>
</ResourceContext.Provider>
);
export const NoLabel = () => (
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Labeled>
<TextField label={false} source="title" />
</Labeled>
</RecordContextProvider>
</ResourceContext.Provider>
);
export const Color = () => (
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Stack gap={1} sx={{ m: 1 }}>
<Labeled>
<TextField source="title" />
</Labeled>
<Labeled color="success.main">
<TextField source="title" />
</Labeled>
<Labeled color="#abcdef">
<TextField source="title" />
</Labeled>
</Stack>
</RecordContextProvider>
</ResourceContext.Provider>
);
export const IsRequired = () => (
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Labeled isRequired>
<TextField source="title" />
</Labeled>
</RecordContextProvider>
</ResourceContext.Provider>
);
export const NonField = () => (
<Labeled>
<span>War and Peace</span>
</Labeled>
);
export const NoDoubleLabel = () => (
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Labeled>
<Labeled label="My custom Title">
<TextField source="title" />
</Labeled>
</Labeled>
</RecordContextProvider>
</ResourceContext.Provider>
);
export const FullWidth = () => (
<Stack alignItems="flex-start">
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Labeled label="title" fullWidth>
<Box border="1px solid">
<TextField source="title" />
</Box>
</Labeled>
</RecordContextProvider>
</ResourceContext.Provider>
</Stack>
);
export const FullWidthNoLabel = () => (
<Stack alignItems="flex-start">
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Labeled label={false} fullWidth>
<Box border="1px solid">
<TextField source="title" />
</Box>
</Labeled>
</RecordContextProvider>
</ResourceContext.Provider>
</Stack>
);
export const I18nKey = () => (
<I18nContextProvider
value={{
getLocale: () => 'en',
translate: m => m,
changeLocale: async () => {},
}}
>
<ResourceContext.Provider value="books">
<RecordContextProvider value={record}>
<Labeled>
<TextField source="title" />
</Labeled>
</RecordContextProvider>
</ResourceContext.Provider>
</I18nContextProvider>
);
``` | /content/code_sandbox/packages/ra-ui-materialui/src/Labeled.stories.tsx | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 976 |
```xml
export interface ISettings {
id: number;
}
export interface ICutoff {
id: number;
name: string;
}
export interface IItem {
allowed: boolean;
quality: IQuality;
}
export interface IQuality {
id: number;
name: string;
}
export interface ICheckbox {
value: string;
enabled: boolean;
}
export interface IUsersModel {
id: string;
username: string;
}
export interface INavBar {
id: string;
icon: string;
name: string;
link: string;
requiresAdmin: boolean;
enabled: boolean;
toolTip?: boolean;
toolTipMessage?: string;
style?: string;
externalLink?: boolean;
}
``` | /content/code_sandbox/src/Ombi/ClientApp/src/app/interfaces/ICommon.ts | xml | 2016-02-25T12:14:54 | 2024-08-14T22:56:44 | Ombi | Ombi-app/Ombi | 3,674 | 156 |
```xml
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<response>
<result code="1001">
<msg>Command completed successfully; action pending</msg>
</result>
<resData>
<domain:trnData
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>example.tld</domain:name>
<domain:trStatus>pending</domain:trStatus>
<domain:reID>NewRegistrar</domain:reID>
<domain:reDate>2000-06-09T22:00:00.0Z</domain:reDate>
<domain:acID>TheRegistrar</domain:acID>
<domain:acDate>2000-06-14T22:00:00.0Z</domain:acDate>
<domain:exDate>2002-09-08T22:00:00.0Z</domain:exDate>
</domain:trnData>
</resData>
<extension>
<fee:trnData xmlns:fee="urn:ietf:params:xml:ns:fee-%FEE_VERSION%">
<fee:currency>USD</fee:currency>
<fee:fee description="renew">11.00</fee:fee>
</fee:trnData>
</extension>
<trID>
<clTRID>ABC-12345</clTRID>
<svTRID>server-trid</svTRID>
</trID>
</response>
</epp>
``` | /content/code_sandbox/core/src/test/resources/google/registry/flows/domain/domain_transfer_request_response_fee.xml | xml | 2016-02-29T20:16:48 | 2024-08-15T19:49:29 | nomulus | google/nomulus | 1,685 | 353 |
```xml
import { DecoratorFunction, StoryContext } from 'storybook/internal/types';
import { Type } from '@angular/core';
import { ApplicationConfig } from '@angular/platform-browser';
import { computesTemplateFromComponent } from './angular-beta/ComputesTemplateFromComponent';
import { isComponent } from './angular-beta/utils/NgComponentAnalyzer';
import { AngularRenderer, ICollection, NgModuleMetadata } from './types';
// We use `any` here as the default type rather than `Args` because we need something that is
// castable to any component-specific args type when the user is being careful.
export const moduleMetadata =
<TArgs = any>(metadata: Partial<NgModuleMetadata>): DecoratorFunction<AngularRenderer, TArgs> =>
(storyFn) => {
const story = storyFn();
const storyMetadata = story.moduleMetadata || {};
metadata = metadata || {};
return {
...story,
moduleMetadata: {
declarations: [...(metadata.declarations || []), ...(storyMetadata.declarations || [])],
entryComponents: [
...(metadata.entryComponents || []),
...(storyMetadata.entryComponents || []),
],
imports: [...(metadata.imports || []), ...(storyMetadata.imports || [])],
schemas: [...(metadata.schemas || []), ...(storyMetadata.schemas || [])],
providers: [...(metadata.providers || []), ...(storyMetadata.providers || [])],
},
};
};
/**
* Decorator to set the config options which are available during the application bootstrap
* operation
*/
export function applicationConfig<TArgs = any>(
/** Set of config options available during the application bootstrap operation. */
config: ApplicationConfig
): DecoratorFunction<AngularRenderer, TArgs> {
return (storyFn) => {
const story = storyFn();
const storyConfig: ApplicationConfig | undefined = story.applicationConfig;
return {
...story,
applicationConfig:
storyConfig || config
? {
...config,
...storyConfig,
providers: [...(config?.providers || []), ...(storyConfig?.providers || [])],
}
: undefined,
};
};
}
export const componentWrapperDecorator =
<TArgs = any>(
element: Type<unknown> | ((story: string) => string),
props?: ICollection | ((storyContext: StoryContext<AngularRenderer, TArgs>) => ICollection)
): DecoratorFunction<AngularRenderer, TArgs> =>
(storyFn, storyContext) => {
const story = storyFn();
const currentProps = typeof props === 'function' ? (props(storyContext) as ICollection) : props;
const template = isComponent(element)
? computesTemplateFromComponent(element, currentProps ?? {}, story.template)
: element(story.template);
return {
...story,
template,
...(currentProps || story.props
? {
props: {
...currentProps,
...story.props,
},
}
: {}),
};
};
``` | /content/code_sandbox/code/frameworks/angular/src/client/decorators.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 626 |
```xml
const baseStyle = () => {
return {
color: 'text.900',
_dark: {
color: 'text.50',
},
fontWeight: 'bold',
lineHeight: 'sm',
};
};
const sizes = {
'4xl': {
fontSize: { base: '6xl', md: '7xl' },
letterSpacing: 'xl',
},
'3xl': {
fontSize: { base: '5xl', md: '6xl' },
letterSpacing: 'xl',
},
'2xl': {
fontSize: { base: '4xl', md: '5xl' },
},
'xl': {
fontSize: { base: '3xl', md: '4xl' },
},
'lg': {
fontSize: { base: '2xl', md: '3xl' },
},
'md': { fontSize: 'xl' },
'sm': { fontSize: 'md' },
'xs': { fontSize: 'sm' },
};
const defaultProps = {
size: 'lg',
};
export default {
baseStyle,
sizes,
defaultProps,
};
``` | /content/code_sandbox/src/theme/components/heading.ts | xml | 2016-04-15T11:37:23 | 2024-08-14T16:16:44 | NativeBase | GeekyAnts/NativeBase | 20,132 | 247 |
```xml
import {
commonCampaignInputs,
commonCampaignTypes,
commonFilterTypes,
paginateTypes
} from './common';
export const types = `
type SpinCampaign @key(fields: "_id") @cacheControl(maxAge: 3) {
_id: String,
${commonCampaignTypes}
buyScore: Float,
awards: JSON,
spinsCount: Int,
}
`;
export const queries = `
spinCampaignDetail(_id: String!): SpinCampaign
spinCampaigns(${commonFilterTypes} ${paginateTypes}): [SpinCampaign]
cpSpinCampaigns: [SpinCampaign]
spinCampaignsCount(${commonFilterTypes}): Int
`;
const SpinCampaignDoc = `
${commonCampaignInputs}
buyScore: Float,
awards: JSON
`;
export const mutations = `
spinCampaignsAdd(${SpinCampaignDoc}): SpinCampaign
spinCampaignsEdit(_id: String!, ${SpinCampaignDoc}): SpinCampaign
spinCampaignsRemove(_ids: [String]): JSON
`;
``` | /content/code_sandbox/packages/plugin-loyalties-api/src/graphql/schema/spinCampaign.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 217 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url">
<data>
<import type="android.view.View" />
<variable
name="feedback"
type="com.eventyay.organizer.data.feedback.Feedback" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/profile"
android:layout_width="@dimen/spacing_large"
android:layout_height="@dimen/spacing_large"
android:layout_marginLeft="@dimen/spacing_small"
android:layout_marginStart="@dimen/spacing_small"
android:layout_marginTop="@dimen/spacing_small"
android:background="@drawable/circle_placeholder"
android:contentDescription="@string/profile_picture"
app:circleImageUrl="@{ feedback.user.avatarUrl }"
app:placeholder="@{ @drawable/ic_account_circle }" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/spacing_small"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/spacing_small"
android:layout_marginStart="@dimen/spacing_small"
android:text='@{ String.valueOf(feedback.user.firstName + " " + feedback.user.lastName) }'
android:textSize="@dimen/text_size_normal"
tools:text="User Name" />
<RatingBar
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/spacing_small"
android:layout_marginLeft="@dimen/spacing_small"
android:layout_marginStart="@dimen/spacing_small"
android:layout_marginTop="@dimen/spacing_tiny"
android:rating="@{ safeUnbox(feedback.rating) }"
tools:rating="4" />
<TextView
android:id="@+id/comment_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/spacing_small"
android:layout_marginStart="@dimen/spacing_small"
android:text='@{ feedback.comment }'
android:textSize="@dimen/text_size_small"
android:ellipsize="end"
android:maxLines="2"
tools:text="Awesome Event" />
</LinearLayout>
</LinearLayout>
</layout>
``` | /content/code_sandbox/app/src/main/res/layout/feedbacklist_layout.xml | xml | 2016-08-13T08:08:39 | 2024-08-06T13:58:48 | open-event-organizer-android | fossasia/open-event-organizer-android | 1,783 | 591 |
```xml
import { vtkObject } from '../../../interfaces';
/**
*
*/
export interface IPriorityQueueInitialValues {
elements?: Array<any>;
}
export interface vtkPriorityQueue extends vtkObject {
/**
* Push an element to the queue while defining a priority.
* @param {Number} priority The priority of the element.
* @param element
*/
push(priority: number, element: any): void;
/**
*
*/
pop(): any | null;
/**
* Delete an element from the queue by its ID.
* @param {Number} id The id of the element.
*/
deleteById(id: number): void;
/**
* Get the length of the queue.
*/
length(): number;
}
/**
* Method used to decorate a given object (publicAPI+model) with vtkPriorityQueue characteristics.
*
* @param publicAPI object on which methods will be bounds (public)
* @param model object on which data structure will be bounds (protected)
* @param {IPriorityQueueInitialValues} [initialValues] (default: {})
*/
export function extend(
publicAPI: object,
model: object,
initialValues?: IPriorityQueueInitialValues
): void;
/**
* Method used to create a new instance of vtkPriorityQueue
* @param {IPriorityQueueInitialValues} [initialValues] for pre-setting some of its content
*/
export function newInstance(
initialValues?: IPriorityQueueInitialValues
): vtkPriorityQueue;
/**
* vtkPriorityQueue is a general object for creating and manipulating lists of
* object ids (e.g., point or cell ids). Object ids are sorted according to a
* user-specified priority, where entries at the top of the queue have the
* smallest values.
*/
export declare const vtkPriorityQueue: {
newInstance: typeof newInstance;
extend: typeof extend;
};
export default vtkPriorityQueue;
``` | /content/code_sandbox/Sources/Common/Core/PriorityQueue/index.d.ts | xml | 2016-05-02T15:44:11 | 2024-08-15T19:53:44 | vtk-js | Kitware/vtk-js | 1,200 | 395 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path
name="files"
path="." />
<cache-path
name="cache"
path="." />
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<external-cache-path
name="external_cache"
path="." />
<root-path
name="root"
path="storage"/>
</paths>
``` | /content/code_sandbox/app/src/main/res/xml/filepaths.xml | xml | 2016-05-04T11:46:20 | 2024-08-15T16:29:10 | android | meganz/android | 1,537 | 115 |
```xml
import { Component } from '@angular/core';
import { Code } from '@domain/code';
@Component({
selector: 'accessibility-doc',
template: ` <app-docsectiontext>
<h3>Screen Reader</h3>
<p>
Value to describe the source listbox and target listbox can be provided with <i>ariaLabelledBy</i> or <i>ariaLabel</i> props. The list elements has a <i>listbox</i> role with the <i>aria-multiselectable</i> attribute. Each list item has
an <i>option</i> role with <i>aria-selected</i> and <i>aria-disabled</i> as their attributes.
</p>
<p>
Controls buttons are <i>button</i> elements with an <i>aria-label</i> that refers to the <i>aria.moveTop</i>, <i>aria.moveUp</i>, <i>aria.moveDown</i>, <i>aria.moveBottom</i>,<i>aria.moveTo</i>, <i>aria.moveAllTo</i>,
<i>aria.moveFrom</i> and <i>aria.moveAllFrom</i> properties of the <a href="/configuration/#locale">locale</a> API by default, alternatively you may use<i>moveTopButtonProps</i>, <i>moveUpButtonProps</i>, <i>moveDownButtonProps</i>,
<i>moveToButtonProps</i>, <i>moveAllToButtonProps</i>, <i>moveFromButtonProps</i>, <i>moveFromButtonProps</i> and <i>moveAllFromButtonProps</i> to customize the buttons like overriding the default <i>aria-label</i> attributes.
</p>
<app-code [code]="code" [hideToggleCode]="true"></app-code>
<h3>PickList Keyboard Support</h3>
<div class="doc-tablewrapper">
<table class="doc-table">
<thead>
<tr>
<th>Key</th>
<th>Function</th>
</tr>
</thead>
<tbody>
<tr>
<td><i>tab</i></td>
<td>Moves focus to the first selected option, if there is none then first option receives the focus.</td>
</tr>
<tr>
<td><i>up arrow</i></td>
<td>Moves focus to the previous option.</td>
</tr>
<tr>
<td><i>down arrow</i></td>
<td>Moves focus to the next option.</td>
</tr>
<tr>
<td><i>enter</i></td>
<td>Toggles the selected state of the focused option.</td>
</tr>
<tr>
<td><i>space</i></td>
<td>Toggles the selected state of the focused option.</td>
</tr>
<tr>
<td><i>home</i></td>
<td>Moves focus to the first option.</td>
</tr>
<tr>
<td><i>end</i></td>
<td>Moves focus to the last option.</td>
</tr>
<tr>
<td><i>shift</i> + <i>down arrow</i></td>
<td>Moves focus to the next option and toggles the selection state.</td>
</tr>
<tr>
<td><i>shift</i> + <i>up arrow</i></td>
<td>Moves focus to the previous option and toggles the selection state.</td>
</tr>
<tr>
<td><i>shift</i> + <i>space</i></td>
<td>Selects the items between the most recently selected option and the focused option.</td>
</tr>
<tr>
<td><i>control</i> + <i>shift</i> + <i>home</i></td>
<td>Selects the focused options and all the options up to the first one.</td>
</tr>
<tr>
<td><i>control</i> + <i>shift</i> + <i>end</i></td>
<td>Selects the focused options and all the options down to the first one.</td>
</tr>
<tr>
<td><i>control</i> + <i>a</i></td>
<td>Selects all options.</td>
</tr>
</tbody>
</table>
</div>
<h3>Buttons Keyboard Support</h3>
<div class="doc-tablewrapper">
<table class="doc-table">
<thead>
<tr>
<th>Key</th>
<th>Function</th>
</tr>
</thead>
<tbody>
<tr>
<td><i>enter</i></td>
<td>Executes button action.</td>
</tr>
<tr>
<td><i>space</i></td>
<td>Executes button action.</td>
</tr>
</tbody>
</table>
</div>
</app-docsectiontext>`
})
export class AccessibilityDoc {
code: Code = {
html: `<span id="lb">Options</span>
<p-pickList ariaLabelledBy="lb" />
<p-pickList ariaLabel="City" />`
};
}
``` | /content/code_sandbox/src/app/showcase/doc/picklist/accessibilitydoc.ts | xml | 2016-01-16T09:23:28 | 2024-08-16T19:58:20 | primeng | primefaces/primeng | 9,969 | 1,230 |
```xml
import customScalars from '@erxes/api-utils/src/customScalars';
import burenScoringQueries from './queries/queries';
import mutations from './mutations/toSaveBurenScoring';
const resolvers: any = async () => ({
...customScalars,
Mutation: {
...mutations
},
Query: {
...burenScoringQueries,
},
});
export default resolvers;
``` | /content/code_sandbox/packages/plugin-burenscoring-api/src/graphql/resolvers/index.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 83 |
```xml
import React from 'react';
type IconProps = React.SVGProps<SVGSVGElement>;
export declare const IcDensityLow: (props: IconProps) => React.JSX.Element;
export {};
``` | /content/code_sandbox/packages/icons/lib/icDensityLow.d.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 43 |
```xml
///
///
///
/// path_to_url
///
/// Unless required by applicable law or agreed to in writing, software
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
///
import { Inject, Injectable, NgZone } from '@angular/core';
import {
AlarmCountCmd,
AlarmCountUnsubscribeCmd,
AlarmCountUpdate,
AlarmDataCmd,
AlarmDataUnsubscribeCmd,
AlarmDataUpdate,
EntityCountCmd,
EntityCountUnsubscribeCmd,
EntityCountUpdate,
EntityDataCmd,
EntityDataUnsubscribeCmd,
EntityDataUpdate,
isAlarmCountUpdateMsg,
isAlarmDataUpdateMsg,
isEntityCountUpdateMsg,
isEntityDataUpdateMsg,
isNotificationCountUpdateMsg,
isNotificationsUpdateMsg,
MarkAllAsReadCmd,
MarkAsReadCmd,
NotificationCountUpdate,
NotificationSubscriber,
NotificationsUpdate,
SubscriptionCmd,
SubscriptionUpdate,
TelemetryPluginCmdsWrapper,
TelemetrySubscriber,
UnreadCountSubCmd,
UnreadSubCmd,
UnsubscribeCmd,
WebsocketDataMsg
} from '@app/shared/models/telemetry/telemetry.models';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { AuthService } from '@core/auth/auth.service';
import { WINDOW } from '@core/services/window.service';
import { WebsocketService } from '@core/ws/websocket.service';
// @dynamic
@Injectable({
providedIn: 'root'
})
export class TelemetryWebsocketService extends WebsocketService<TelemetrySubscriber> {
cmdWrapper: TelemetryPluginCmdsWrapper;
constructor(protected store: Store<AppState>,
protected authService: AuthService,
protected ngZone: NgZone,
@Inject(WINDOW) protected window: Window) {
super(store, authService, ngZone, 'api/ws', new TelemetryPluginCmdsWrapper(), window);
}
public subscribe(subscriber: TelemetrySubscriber) {
this.isActive = true;
subscriber.subscriptionCommands.forEach(
(subscriptionCommand) => {
const cmdId = this.nextCmdId();
if (!(subscriptionCommand instanceof MarkAsReadCmd) && !(subscriptionCommand instanceof MarkAllAsReadCmd)) {
this.subscribersMap.set(cmdId, subscriber);
}
subscriptionCommand.cmdId = cmdId;
this.cmdWrapper.cmds.push(subscriptionCommand);
}
);
this.subscribersCount++;
this.publishCommands();
}
public update(subscriber: TelemetrySubscriber) {
if (!this.isReconnect) {
subscriber.subscriptionCommands.forEach(
(subscriptionCommand) => {
if (subscriptionCommand.cmdId && (subscriptionCommand instanceof EntityDataCmd || subscriptionCommand instanceof UnreadSubCmd)) {
this.cmdWrapper.cmds.push(subscriptionCommand);
}
}
);
this.publishCommands();
}
}
public unsubscribe(subscriber: TelemetrySubscriber) {
if (this.isActive) {
subscriber.subscriptionCommands.forEach(
(subscriptionCommand) => {
if (subscriptionCommand instanceof SubscriptionCmd) {
subscriptionCommand.unsubscribe = true;
this.cmdWrapper.cmds.push(subscriptionCommand);
} else if (subscriptionCommand instanceof EntityDataCmd) {
const entityDataUnsubscribeCmd = new EntityDataUnsubscribeCmd();
entityDataUnsubscribeCmd.cmdId = subscriptionCommand.cmdId;
this.cmdWrapper.cmds.push(entityDataUnsubscribeCmd);
} else if (subscriptionCommand instanceof AlarmDataCmd) {
const alarmDataUnsubscribeCmd = new AlarmDataUnsubscribeCmd();
alarmDataUnsubscribeCmd.cmdId = subscriptionCommand.cmdId;
this.cmdWrapper.cmds.push(alarmDataUnsubscribeCmd);
} else if (subscriptionCommand instanceof EntityCountCmd) {
const entityCountUnsubscribeCmd = new EntityCountUnsubscribeCmd();
entityCountUnsubscribeCmd.cmdId = subscriptionCommand.cmdId;
this.cmdWrapper.cmds.push(entityCountUnsubscribeCmd);
} else if (subscriptionCommand instanceof AlarmCountCmd) {
const alarmCountUnsubscribeCmd = new AlarmCountUnsubscribeCmd();
alarmCountUnsubscribeCmd.cmdId = subscriptionCommand.cmdId;
this.cmdWrapper.cmds.push(alarmCountUnsubscribeCmd);
} else if (subscriptionCommand instanceof UnreadCountSubCmd || subscriptionCommand instanceof UnreadSubCmd) {
const notificationsUnsubCmds = new UnsubscribeCmd();
notificationsUnsubCmds.cmdId = subscriptionCommand.cmdId;
this.cmdWrapper.cmds.push(notificationsUnsubCmds);
}
const cmdId = subscriptionCommand.cmdId;
if (cmdId) {
this.subscribersMap.delete(cmdId);
}
}
);
this.reconnectSubscribers.delete(subscriber);
this.subscribersCount--;
this.publishCommands();
}
}
processOnMessage(message: WebsocketDataMsg) {
let subscriber: TelemetrySubscriber | NotificationSubscriber;
if ('cmdId' in message && message.cmdId) {
subscriber = this.subscribersMap.get(message.cmdId);
if (subscriber instanceof NotificationSubscriber) {
if (isNotificationCountUpdateMsg(message)) {
subscriber.onNotificationCountUpdate(new NotificationCountUpdate(message));
} else if (isNotificationsUpdateMsg(message)) {
subscriber.onNotificationsUpdate(new NotificationsUpdate(message));
}
} else if (subscriber instanceof TelemetrySubscriber) {
if (isEntityDataUpdateMsg(message)) {
subscriber.onEntityData(new EntityDataUpdate(message));
} else if (isAlarmDataUpdateMsg(message)) {
subscriber.onAlarmData(new AlarmDataUpdate(message));
} else if (isEntityCountUpdateMsg(message)) {
subscriber.onEntityCount(new EntityCountUpdate(message));
} else if (isAlarmCountUpdateMsg(message)) {
subscriber.onAlarmCount(new AlarmCountUpdate(message));
}
}
} else if ('subscriptionId' in message && message.subscriptionId) {
subscriber = this.subscribersMap.get(message.subscriptionId) as TelemetrySubscriber;
if (subscriber) {
subscriber.onData(new SubscriptionUpdate(message));
}
}
}
}
``` | /content/code_sandbox/ui-ngx/src/app/core/ws/telemetry-websocket.service.ts | xml | 2016-12-01T09:33:30 | 2024-08-16T19:58:25 | thingsboard | thingsboard/thingsboard | 16,820 | 1,278 |
```xml
import { Observable } from '../Observable';
import { SchedulerAction, SchedulerLike } from '../types';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
/**
* Convert an object into an Observable of `[key, value]` pairs.
*
* <span class="informal">Turn entries of an object into a stream.</span>
*
* <img src="./img/pairs.png" width="100%">
*
* `pairs` takes an arbitrary object and returns an Observable that emits arrays. Each
* emitted array has exactly two elements - the first is a key from the object
* and the second is a value corresponding to that key. Keys are extracted from
* an object via `Object.keys` function, which means that they will be only
* enumerable keys that are present on an object directly - not ones inherited
* via prototype chain.
*
* By default these arrays are emitted synchronously. To change that you can
* pass a {@link SchedulerLike} as a second argument to `pairs`.
*
* @example <caption>Converts a javascript object to an Observable</caption>
* ```javascript
* const obj = {
* foo: 42,
* bar: 56,
* baz: 78
* };
*
* pairs(obj)
* .subscribe(
* value => console.log(value),
* err => {},
* () => console.log('the end!')
* );
*
* // Logs:
* // ["foo": 42],
* // ["bar": 56],
* // ["baz": 78],
* // "the end!"
* ```
*
* @param {Object} obj The object to inspect and turn into an
* Observable sequence.
* @param {Scheduler} [scheduler] An optional IScheduler to schedule
* when resulting Observable will emit values.
* @returns {(Observable<Array<string|T>>)} An observable sequence of
* [key, value] pairs from the object.
*/
export function pairs<T>(obj: Object, scheduler?: SchedulerLike): Observable<[string, T]> {
if (!scheduler) {
return new Observable<[string, T]>(subscriber => {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length && !subscriber.closed; i++) {
const key = keys[i];
if (obj.hasOwnProperty(key)) {
subscriber.next([key, obj[key]]);
}
}
subscriber.complete();
});
} else {
return new Observable<[string, T]>(subscriber => {
const keys = Object.keys(obj);
const subscription = new Subscription();
subscription.add(
scheduler.schedule<{ keys: string[], index: number, subscriber: Subscriber<[string, T]>, subscription: Subscription, obj: Object }>
(dispatch, 0, { keys, index: 0, subscriber, subscription, obj }));
return subscription;
});
}
}
/** @internal */
export function dispatch<T>(this: SchedulerAction<any>,
state: { keys: string[], index: number, subscriber: Subscriber<[string, T]>, subscription: Subscription, obj: Object }) {
const { keys, index, subscriber, subscription, obj } = state;
if (!subscriber.closed) {
if (index < keys.length) {
const key = keys[index];
subscriber.next([key, obj[key]]);
subscription.add(this.schedule({ keys, index: index + 1, subscriber, subscription, obj }));
} else {
subscriber.complete();
}
}
}
``` | /content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/src/internal/observable/pairs.ts | xml | 2016-09-05T10:18:44 | 2024-08-11T13:21:40 | LiquidCore | LiquidPlayer/LiquidCore | 1,010 | 732 |
```xml
import React, { useCallback, MouseEvent } from 'react'
import querystring from 'querystring'
import { getWorkspaceURL, getTeamURL } from '../../lib/utils/patterns'
import { SerializedWorkspace } from '../../interfaces/db/workspace'
import { SerializedTeam } from '../../interfaces/db/team'
import { useRouter } from '../../lib/router'
export type WorkspaceLinkIntent = 'index'
interface WorkspaceLinkProps {
workspace: SerializedWorkspace
team: SerializedTeam
draggable?: boolean
intent?: WorkspaceLinkIntent
className?: string
style?: React.CSSProperties
children?: React.ReactNode
tabIndex?: number
query?: any
onClick?: () => void
onFocus?: () => void
id?: string
}
const WorkspaceLink = ({
intent = 'index',
workspace,
team,
className,
style,
children,
query,
onClick,
draggable = false,
onFocus,
tabIndex,
id,
}: WorkspaceLinkProps) => {
const { push } = useRouter()
const href = getWorkspaceHref(workspace, team, intent, query)
const navigate = useCallback(
(event: MouseEvent<HTMLAnchorElement>) => {
event.preventDefault()
push(href)
},
[push, href]
)
return (
<a
href={href}
className={className}
style={style}
onClick={onClick != null ? onClick : navigate}
draggable={draggable}
onFocus={onFocus}
tabIndex={tabIndex}
id={id}
>
{children}
</a>
)
}
export default WorkspaceLink
export function getWorkspaceHref(
workspace: SerializedWorkspace,
team: SerializedTeam,
intent: WorkspaceLinkIntent,
query?: any
) {
const basePathname = `${getTeamURL(team)}${getWorkspaceURL(workspace)}`
const queryPathName = query != null ? `?${querystring.stringify(query)}` : ''
if (intent === 'index') {
return `${basePathname}${queryPathName}`
}
return `${basePathname}/${intent}${queryPathName}`
}
export function useNavigateToWorkspace() {
const { push } = useRouter()
return useCallback(
(
workspace: SerializedWorkspace,
team: SerializedTeam,
intent: WorkspaceLinkIntent,
query?: any
) => {
push(getWorkspaceHref(workspace, team, intent, query))
},
[push]
)
}
``` | /content/code_sandbox/src/cloud/components/Link/WorkspaceLink.tsx | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 518 |
```xml
import * as React from 'react';
import { styled } from '@mui/material/styles';
import { ReactElement } from 'react';
import {
Drawer,
DrawerProps,
useMediaQuery,
Theme,
useScrollTrigger,
} from '@mui/material';
import lodashGet from 'lodash/get';
import { useLocale } from 'ra-core';
import { useSidebarState } from './useSidebarState';
export const Sidebar = (props: SidebarProps) => {
const { appBarAlwaysOn, children, closedSize, size, ...rest } = props;
const isXSmall = useMediaQuery<Theme>(theme =>
theme.breakpoints.down('sm')
);
const [open, setOpen] = useSidebarState();
useLocale(); // force redraw on locale change
const trigger = useScrollTrigger();
const toggleSidebar = () => setOpen(!open);
return isXSmall ? (
<StyledDrawer
variant="temporary"
open={open}
onClose={toggleSidebar}
classes={SidebarClasses}
{...rest}
>
{children}
</StyledDrawer>
) : (
<StyledDrawer
variant="permanent"
open={open}
onClose={toggleSidebar}
classes={SidebarClasses}
className={
trigger && !appBarAlwaysOn ? SidebarClasses.appBarCollapsed : ''
}
{...rest}
>
<div className={SidebarClasses.fixed}>{children}</div>
</StyledDrawer>
);
};
export interface SidebarProps extends DrawerProps {
appBarAlwaysOn?: boolean;
children: ReactElement;
closedSize?: number;
size?: number;
}
const PREFIX = 'RaSidebar';
export const SidebarClasses = {
docked: `${PREFIX}-docked`,
paper: `${PREFIX}-paper`,
paperAnchorLeft: `${PREFIX}-paperAnchorLeft`,
paperAnchorRight: `${PREFIX}-paperAnchorRight`,
paperAnchorTop: `${PREFIX}-paperAnchorTop`,
paperAnchorBottom: `${PREFIX}-paperAnchorBottom`,
paperAnchorDockedLeft: `${PREFIX}-paperAnchorDockedLeft`,
paperAnchorDockedTop: `${PREFIX}-paperAnchorDockedTop`,
paperAnchorDockedRight: `${PREFIX}-paperAnchorDockedRight`,
paperAnchorDockedBottom: `${PREFIX}-paperAnchorDockedBottom`,
modal: `${PREFIX}-modal`,
fixed: `${PREFIX}-fixed`,
appBarCollapsed: `${PREFIX}-appBarCollapsed`,
};
const StyledDrawer = styled(Drawer, {
name: PREFIX,
slot: 'Root',
overridesResolver: (props, styles) => styles.root,
shouldForwardProp: () => true,
})(({ open, theme }) => ({
height: 'calc(100vh - 3em)',
marginTop: 0,
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
[`&.${SidebarClasses.appBarCollapsed}`]: {
// compensate the margin of the Layout appFrame instead of removing it in the Layout
// because otherwise, the appFrame content without margin may revert the scrollTrigger,
// leading to a visual jiggle
marginTop: theme.spacing(-6),
[theme.breakpoints.down('sm')]: {
marginTop: theme.spacing(-7),
},
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
[`& .${SidebarClasses.docked}`]: {},
[`& .${SidebarClasses.paper}`]: {},
[`& .${SidebarClasses.paperAnchorLeft}`]: {},
[`& .${SidebarClasses.paperAnchorRight}`]: {},
[`& .${SidebarClasses.paperAnchorTop}`]: {},
[`& .${SidebarClasses.paperAnchorBottom}`]: {},
[`& .${SidebarClasses.paperAnchorDockedLeft}`]: {},
[`& .${SidebarClasses.paperAnchorDockedTop}`]: {},
[`& .${SidebarClasses.paperAnchorDockedRight}`]: {},
[`& .${SidebarClasses.paperAnchorDockedBottom}`]: {},
[`& .${SidebarClasses.modal}`]: {},
[`& .${SidebarClasses.fixed}`]: {
position: 'fixed',
height: 'calc(100vh - 3em)',
overflowX: 'hidden',
// hide scrollbar
scrollbarWidth: 'none',
msOverflowStyle: 'none',
'&::-webkit-scrollbar': {
display: 'none',
},
},
[`& .MuiPaper-root`]: {
position: 'relative',
width: open
? lodashGet(theme, 'sidebar.width', DRAWER_WIDTH)
: lodashGet(theme, 'sidebar.closedWidth', CLOSED_DRAWER_WIDTH),
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
backgroundColor: 'transparent',
borderRight: 'none',
[theme.breakpoints.only('xs')]: {
marginTop: 0,
height: '100vh',
position: 'inherit',
backgroundColor: theme.palette.background.default,
},
[theme.breakpoints.up('md')]: {
border: 'none',
},
zIndex: 'inherit',
},
}));
export const DRAWER_WIDTH = 240;
export const CLOSED_DRAWER_WIDTH = 55;
``` | /content/code_sandbox/packages/ra-ui-materialui/src/layout/Sidebar.tsx | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 1,133 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:background="?attr/conversation_list_item_background"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<org.thoughtcrime.securesms.components.DocumentView
xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:id="@+id/document_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:visibility="gone"/>
<org.thoughtcrime.securesms.components.AudioView
xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:id="@+id/audio_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:visibility="gone"/>
<org.thoughtcrime.securesms.components.WebxdcView
xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:id="@+id/webxdc_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:visibility="gone"
app:compact="true"/>
<TextView android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:textSize="12sp"
android:textColor="?attr/conversation_list_item_date_color"
android:paddingTop="20dp"
tools:text="Jun 1"/>
</LinearLayout>
``` | /content/code_sandbox/src/main/res/layout/profile_document_item.xml | xml | 2016-07-03T07:32:36 | 2024-08-16T16:51:15 | deltachat-android | deltachat/deltachat-android | 1,082 | 434 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources translatable="false" xmlns:tools="path_to_url">
<string name="app_name">Emoji</string>
<bool name="leak_canary_add_launcher_icon" tools:ignore="UnusedResources">false</bool>
</resources>
``` | /content/code_sandbox/app/src/main/res/values/strings.xml | xml | 2016-03-09T16:01:10 | 2024-08-14T18:34:35 | Emoji | vanniktech/Emoji | 1,523 | 69 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="path_to_url">
<item>
<shape android:shape="rectangle">
<gradient
android:angle="270"
android:endColor="@color/colorPrimaryDark"
android:startColor="@color/colorPrimary"
android:type="linear" />
</shape>
</item>
</layer-list>
``` | /content/code_sandbox/app/src/main/res/drawable/toolbar_bg.xml | xml | 2016-02-22T10:00:46 | 2024-08-16T15:37:50 | Images-to-PDF | Swati4star/Images-to-PDF | 1,174 | 88 |
```xml
import { Component } from '@angular/core';
import { Code } from '@domain/code';
@Component({
selector: 'accessibility-doc',
template: ` <div>
<app-docsectiontext>
<h3>Screen Reader</h3>
<p>
InputTextarea component renders a native textarea element that implicitly includes any passed prop. Value to describe the component can either be provided via <i>label</i> tag combined with <i>id</i> prop or using
<i>aria-labelledby</i>, <i>aria-label</i> props.
</p>
</app-docsectiontext>
<app-code [code]="code" [hideToggleCode]="true" [hideCodeSandbox]="true" [hideStackBlitz]="true"></app-code>
<h3>Keyboard Support</h3>
<div class="doc-tablewrapper">
<table class="doc-table">
<thead>
<tr>
<th>Key</th>
<th>Function</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<i>tab</i>
</td>
<td>Moves focus to the input.</td>
</tr>
</tbody>
</table>
</div>
</div>`
})
export class AccessibilityDoc {
code: Code = {
basic: `<label for="address1">Address 1</label>
<textarea pInputTextarea id="address1"></textarea>
<span id="address2">Address 2</span>
<textarea pInputTextarea aria-labelledby="address2"></textarea>
<textarea pInputTextarea aria-label="Address Details"></textarea>`
};
}
``` | /content/code_sandbox/src/app/showcase/doc/inputtextarea/accessibilitydoc.ts | xml | 2016-01-16T09:23:28 | 2024-08-16T19:58:20 | primeng | primefaces/primeng | 9,969 | 364 |
```xml
import { IActivityLogForMonth } from '@erxes/ui-log/src/activityLogs/types';
import { IUser } from './auth/types';
export interface IRouterProps {
location: any;
match: any;
navigate: any;
}
export interface IAttachment {
name: string;
type: string;
url: string;
size?: number;
duration?: number;
}
export type IAttachmentPreview = {
name: string;
type: string;
data: string;
} | null;
export interface IAnimatedLoader {
height?: string;
width?: string;
color?: string;
round?: boolean;
margin?: string;
marginRight?: string;
isBox?: boolean;
withImage?: boolean;
}
export interface IBreadCrumbItem {
title: string;
link?: string;
}
export interface IQueryParams {
[key: string]: string;
}
export interface ISelectedOption {
label: string;
value: string;
}
export interface IConditionsRule {
_id: string;
kind?: string;
text: string;
condition: string;
value: string;
}
export type IDateColumn = {
month: number;
year: number;
};
export interface IFieldLogic {
fieldId?: string;
tempFieldId?: string;
logicOperator: string;
logicValue: string;
__typename?: string;
}
export interface ILocationOption {
lat: number;
lng: number;
description?: string;
marker?: string;
}
export interface IObjectListConfig {
key: string;
label: string;
type: string;
}
export interface IField {
_id: string;
key?: string;
contentType: string;
contentTypeId?: string;
type: string;
validation?: string;
regexValidation?: string;
field?: string;
text?: string;
code?: string;
content?: string;
description?: string;
options?: string[];
locationOptions?: ILocationOption[];
objectListConfigs?: IObjectListConfig[];
isRequired?: boolean;
order?: React.ReactNode;
canHide?: boolean;
isVisible?: boolean;
isVisibleInDetail?: boolean;
isVisibleToCreate?: boolean;
isDefinedByErxes?: boolean;
groupId?: string;
lastUpdatedUser?: IUser;
lastUpdatedUserId?: string;
associatedFieldId?: string;
column?: number;
associatedField?: {
_id: string;
text: string;
contentType: string;
};
logics?: IFieldLogic[];
logicAction?: string;
groupName?: string;
pageNumber?: number;
searchable?: boolean;
showInCard?: boolean;
keys?: string[];
productCategoryId?: string;
optionsValues?: string;
relationType?: string;
subFieldIds?: string[];
}
export interface IFormProps {
errors: any;
values: any;
registerChild: (child: React.ReactNode) => void;
runValidations?: (callback: any) => void;
resetSubmit?: () => void;
isSubmitted: boolean;
isSaved?: boolean;
}
export type IOption = {
label: string;
value: string;
avatar?: string;
extraValue?: string;
};
export type IButtonMutateProps = {
passedName?: string;
name?: string;
values: any;
isSubmitted: boolean;
confirmationUpdate?: boolean;
callback?: (data?: any) => void;
resetSubmit?: () => void;
beforeSubmit?: () => void;
size?: string;
object?: any;
text?: string;
icon?: string;
type?: string;
disableLoading?: boolean;
};
export type IMentionUser = {
id: string;
avatar?: string;
username: string;
fullName?: string;
title?: string;
};
export type IEditorProps = {
placeholder?: string;
onCtrlEnter?: (evt?: any) => void;
content: string;
onChange: (evt: any) => void;
onInstanceReady?: (e: any) => any;
height?: number | string;
insertItems?: any;
removeButtons?: string;
removePlugins?: string;
toolbarCanCollapse?: boolean;
showMentions?: boolean;
toolbar?: any[];
autoFocus?: boolean;
toolbarLocation?: 'top' | 'bottom';
autoGrow?: boolean;
autoGrowMinHeight?: number | string;
autoGrowMaxHeight?: number | string;
name?: string;
isSubmitted?: boolean;
formItems?: any;
contentType?: string;
};
export type QueryResponse = {
loading: boolean;
refetch: (variables?: any) => Promise<any>;
error?: string;
};
export type MutationVariables = {
_id: string;
};
export type ActivityLogQueryResponse = {
activityLogs: IActivityLogForMonth[];
loading: boolean;
};
export type Counts = {
[key: string]: number;
};
export interface IAbortController {
readonly signal: AbortSignal;
abort?: () => void;
}
``` | /content/code_sandbox/packages/erxes-ui/src/types.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,091 |
```xml
import { EncryptService } from "../../../platform/abstractions/encrypt.service";
import { EncString } from "../../../platform/models/domain/enc-string";
import { SymmetricCryptoKey } from "../../../platform/models/domain/symmetric-crypto-key";
import { OrgKey, UserPrivateKey } from "../../../types/key";
import { EncryptedOrganizationKeyData } from "../data/encrypted-organization-key.data";
export abstract class BaseEncryptedOrganizationKey {
abstract get encryptedOrganizationKey(): EncString;
static fromData(data: EncryptedOrganizationKeyData) {
switch (data.type) {
case "organization":
return new EncryptedOrganizationKey(data.key);
case "provider":
return new ProviderEncryptedOrganizationKey(data.key, data.providerId);
default:
return null;
}
}
static isProviderEncrypted(
key: EncryptedOrganizationKey | ProviderEncryptedOrganizationKey,
): key is ProviderEncryptedOrganizationKey {
return key.toData().type === "provider";
}
}
export class EncryptedOrganizationKey implements BaseEncryptedOrganizationKey {
constructor(private key: string) {}
async decrypt(encryptService: EncryptService, privateKey: UserPrivateKey) {
const decValue = await encryptService.rsaDecrypt(this.encryptedOrganizationKey, privateKey);
return new SymmetricCryptoKey(decValue) as OrgKey;
}
get encryptedOrganizationKey() {
return new EncString(this.key);
}
toData(): EncryptedOrganizationKeyData {
return {
type: "organization",
key: this.key,
};
}
}
export class ProviderEncryptedOrganizationKey implements BaseEncryptedOrganizationKey {
constructor(
private key: string,
private providerId: string,
) {}
async decrypt(encryptService: EncryptService, providerKeys: Record<string, SymmetricCryptoKey>) {
const decValue = await encryptService.decryptToBytes(
new EncString(this.key),
providerKeys[this.providerId],
);
return new SymmetricCryptoKey(decValue) as OrgKey;
}
get encryptedOrganizationKey() {
return new EncString(this.key);
}
toData(): EncryptedOrganizationKeyData {
return {
type: "provider",
key: this.key,
providerId: this.providerId,
};
}
}
``` | /content/code_sandbox/libs/common/src/admin-console/models/domain/encrypted-organization-key.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 482 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!-- -->
<shape xmlns:android="path_to_url"
android:padding="10dp"
android:shape="rectangle">
<solid android:color="#ffffffff"/>
<corners
android:bottomLeftRadius="3dp"
android:bottomRightRadius="3dp"
android:topLeftRadius="3dp"
android:topRightRadius="3dp"/>
<!-- -->
<stroke
android:width="1dp"
android:color="#cbcaca"
android:dashGap="0dp"
android:dashWidth="1dp"/>
</shape>
``` | /content/code_sandbox/app/src/main/res/drawable/background_white_round.xml | xml | 2016-01-28T12:16:02 | 2024-08-12T03:26:43 | NineGridView | jeasonlzy/NineGridView | 2,461 | 142 |
```xml
/*
* Wire
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see path_to_url
*
*/
/* eslint-disable */
import {MediaDeviceType} from './MediaDeviceType';
import {MediaDevicesHandler} from './MediaDevicesHandler';
/* yarn test:app --specs media/MediaDevicesHandler --nolegacy */
describe('MediaDevicesHandler', () => {
/**
* Test data from a real-world scenario:
* - Laptop webcam (Lenovo EasyCamera)
* - Laptop microphone (Realtek High Definition Audio)
* - USB webcam (Logitech HD Webcam C270)
* - Bluetooth Headset (Bose QuietComfort)
* - Two external monitors (DELL U2713HM)
*
* In total:
* - 2 cameras
* - 3 microphones
* - 4 speakers
*/
const realWorldTestSetup = {
microphones: [
{
deviceId: 'default',
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_INPUT,
label: 'Default - Microphone (HD Webcam C270) (046d:0825)',
},
{
deviceId: 'communications',
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_INPUT,
label: 'Communications - Headset (Bose QuietComfort Hands-Free) (Bluetooth)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_INPUT,
label: 'Headset (Bose QuietComfort Hands-Free) (Bluetooth)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_INPUT,
label: 'Microphonearray (Realtek High Definition Audio)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_INPUT,
label: 'Microphone (HD Webcam C270) (046d:0825)',
},
],
cameras: [
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.VIDEO_INPUT,
label: 'Lenovo EasyCamera (5986:068c)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.VIDEO_INPUT,
label: 'Logitech HD Webcam C270 (046d:0825)',
},
],
speakers: [
{
deviceId: 'default',
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_OUTPUT,
label: 'Default - Headset (Bose QuietComfort Stereo) (Bluetooth)',
},
{
deviceId: 'communications',
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_OUTPUT,
label: 'Communications - Headset (Bose QuietComfort Stereo) (Bluetooth)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_OUTPUT,
label: 'DELL U2713HM (Intel(R) Display-Audio)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_OUTPUT,
label: 'Headset (Bose QuietComfort Stereo) (Bluetooth)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_OUTPUT,
label: 'Speaker (Realtek High Definition Audio)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_OUTPUT,
label: 'DELL U2713HM (Intel(R) Display-Audio)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_OUTPUT,
label: 'Headset (Bose QuietComfort Stereo) (Bluetooth)',
},
],
};
const fakeWorldTestSetup = {
cameras: [
{deviceId: 'camera1', kind: MediaDeviceType.VIDEO_INPUT, label: 'Camera 1', groupId: '1'},
{deviceId: 'camera2', kind: MediaDeviceType.VIDEO_INPUT, label: 'Camera 2', groupId: '2'},
],
speakers: [
{deviceId: 'speaker1', kind: MediaDeviceType.AUDIO_OUTPUT, label: 'Speaker 1', groupId: '1'},
{deviceId: 'speaker2', kind: MediaDeviceType.AUDIO_OUTPUT, label: 'Speaker 2', groupId: '2'},
],
microphones: [
{deviceId: 'mic1', kind: MediaDeviceType.AUDIO_INPUT, label: 'Mic 1', groupId: '1'},
{deviceId: 'mic2', kind: MediaDeviceType.AUDIO_INPUT, label: 'Mic 2', groupId: '2'},
],
};
describe('refreshMediaDevices', () => {
it('filters duplicate microphones and keeps the ones marked with "communications"', () => {
spyOn(navigator.mediaDevices, 'enumerateDevices').and.returnValue(
Promise.resolve([
{
deviceId: 'default',
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_INPUT,
label: 'Default - Desktop Microphone (Microsoft LifeCam Studio(TM)) (045e:0772)',
},
{
deviceId: 'communications',
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_INPUT,
label: 'Communications - Desktop Microphone (Microsoft LifeCam Studio(TM)) (045e:0772)',
},
{
deviceId: your_sha256_hash,
groupId: your_sha256_hash,
kind: MediaDeviceType.AUDIO_INPUT,
label: 'Desktop Microphone (Microsoft LifeCam Studio(TM)) (045e:0772)',
},
]),
);
const devicesHandler = new MediaDevicesHandler();
setTimeout(() => {
expect(devicesHandler.availableDevices.audioinput().length).toEqual(1);
});
});
it('filters duplicate speakers', () => {
spyOn(navigator.mediaDevices, 'enumerateDevices').and.returnValue(
Promise.resolve([
...realWorldTestSetup.cameras,
...realWorldTestSetup.microphones,
...realWorldTestSetup.speakers,
]),
);
const devicesHandler = new MediaDevicesHandler();
expect(realWorldTestSetup.cameras.length).toEqual(2);
expect(realWorldTestSetup.microphones.length).toEqual(5);
expect(realWorldTestSetup.speakers.length).toEqual(7);
setTimeout(() => {
expect(devicesHandler.availableDevices.videoinput().length).toEqual(2);
expect(devicesHandler.availableDevices.audioinput().length).toEqual(3);
expect(devicesHandler.availableDevices.audiooutput().length).toEqual(4);
});
});
});
describe('constructor', () => {
it('loads available devices and listens to input devices changes', done => {
const enumerateDevicesSpy = spyOn(navigator.mediaDevices, 'enumerateDevices');
enumerateDevicesSpy.and.returnValue(
Promise.resolve([
...fakeWorldTestSetup.cameras,
...fakeWorldTestSetup.microphones,
...fakeWorldTestSetup.speakers,
]),
);
const devicesHandler = new MediaDevicesHandler();
setTimeout(() => {
expect(navigator.mediaDevices.enumerateDevices).toHaveBeenCalledTimes(1);
expect(devicesHandler.availableDevices.videoinput()).toEqual(fakeWorldTestSetup.cameras);
expect(devicesHandler.availableDevices.audiooutput()).toEqual(fakeWorldTestSetup.speakers);
const newCameras = [{deviceId: 'newcamera', kind: MediaDeviceType.VIDEO_INPUT}];
enumerateDevicesSpy.and.returnValue(Promise.resolve(newCameras));
navigator.mediaDevices!.ondevicechange?.(Event.prototype);
setTimeout(() => {
expect(navigator.mediaDevices.enumerateDevices).toHaveBeenCalledTimes(2);
expect(devicesHandler.availableDevices.videoinput()).toEqual(newCameras);
expect(devicesHandler.availableDevices.audiooutput()).toEqual([]);
done();
});
});
});
});
describe('currentAvailableDeviceId', () => {
it('only exposes available device', done => {
spyOn(navigator.mediaDevices, 'enumerateDevices').and.returnValue(
Promise.resolve([
...fakeWorldTestSetup.cameras,
...fakeWorldTestSetup.microphones,
...fakeWorldTestSetup.speakers,
]),
);
const devicesHandler = new MediaDevicesHandler();
setTimeout(() => {
devicesHandler.currentDeviceId.videoinput(fakeWorldTestSetup.cameras[0].deviceId);
expect(devicesHandler.currentAvailableDeviceId.videoinput()).toBe(fakeWorldTestSetup.cameras[0].deviceId);
devicesHandler.currentDeviceId.videoinput('not-existing-id');
expect(devicesHandler.currentAvailableDeviceId.videoinput()).toBe(
MediaDevicesHandler.CONFIG.DEFAULT_DEVICE.videoinput,
);
devicesHandler.currentDeviceId.audioinput(fakeWorldTestSetup.microphones[0].deviceId);
expect(devicesHandler.currentAvailableDeviceId.audioinput()).toBe(fakeWorldTestSetup.microphones[0].deviceId);
devicesHandler.currentDeviceId.audioinput('not-existing-id');
expect(devicesHandler.currentAvailableDeviceId.audioinput()).toBe(
MediaDevicesHandler.CONFIG.DEFAULT_DEVICE.audioinput,
);
devicesHandler.currentDeviceId.audiooutput(fakeWorldTestSetup.speakers[0].deviceId);
expect(devicesHandler.currentAvailableDeviceId.audiooutput()).toBe(fakeWorldTestSetup.speakers[0].deviceId);
devicesHandler.currentDeviceId.audiooutput('inexistant-id');
expect(devicesHandler.currentAvailableDeviceId.audiooutput()).toBe(
MediaDevicesHandler.CONFIG.DEFAULT_DEVICE.audiooutput,
);
done();
});
});
});
});
``` | /content/code_sandbox/src/script/media/MediaDevicesHandler.test.ts | xml | 2016-07-21T15:34:05 | 2024-08-16T11:40:13 | wire-webapp | wireapp/wire-webapp | 1,125 | 2,144 |
```xml
import { DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE } from './constants';
import { getFontFaceValueFromId } from './helpers/fontFace';
export interface FontData {
FontFace: string | null;
FontSize: number | null;
}
/**
* Helper used because of Squire problems to handle correctly default fonts
* TODO : Remove patches arround this issue
*/
export const defaultFontStyle = (fontData: FontData | undefined): string => {
let { FontFace, FontSize } = fontData || {};
FontFace = !FontFace ? DEFAULT_FONT_FACE : getFontFaceValueFromId(FontFace) || DEFAULT_FONT_FACE;
FontSize = !FontSize ? DEFAULT_FONT_SIZE : FontSize;
const stylesArray = [`font-family: ${FontFace};`, `font-size: ${FontSize}px;`];
return stylesArray.join(' ');
};
``` | /content/code_sandbox/packages/components/components/editor/helpers.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 182 |
```xml
import { Platform, ColorValue } from 'react-native';
import * as React from 'react';
import { Component } from 'react';
import GenericTouchable from './GenericTouchable';
import {
TouchableNativeFeedbackProps,
TouchableNativeFeedbackExtraProps,
} from './TouchableNativeFeedbackProps';
/**
* TouchableNativeFeedback behaves slightly different than RN's TouchableNativeFeedback.
* There's small difference with handling long press ripple since RN's implementation calls
* ripple animation via bridge. This solution leaves all animations' handling for native components so
* it follows native behaviours.
*/
export default class TouchableNativeFeedback extends Component<TouchableNativeFeedbackProps> {
static defaultProps = {
...GenericTouchable.defaultProps,
useForeground: true,
extraButtonProps: {
// Disable hiding ripple on Android
rippleColor: null,
},
};
// Could be taken as RNTouchableNativeFeedback.SelectableBackground etc. but the API may change
static SelectableBackground = (rippleRadius?: number) => ({
type: 'ThemeAttrAndroid',
// I added `attribute` prop to clone the implementation of RN and be able to use only 2 types
attribute: 'selectableItemBackground',
rippleRadius,
});
static SelectableBackgroundBorderless = (rippleRadius?: number) => ({
type: 'ThemeAttrAndroid',
attribute: 'selectableItemBackgroundBorderless',
rippleRadius,
});
static Ripple = (
color: ColorValue,
borderless: boolean,
rippleRadius?: number
) => ({
type: 'RippleAndroid',
color,
borderless,
rippleRadius,
});
static canUseNativeForeground = () =>
Platform.OS === 'android' && Platform.Version >= 23;
getExtraButtonProps() {
const extraProps: TouchableNativeFeedbackExtraProps = {};
const { background } = this.props;
if (background) {
// I changed type values to match those used in RN
// TODO(TS): check if it works the same as previous implementation - looks like it works the same as RN component, so it should be ok
if (background.type === 'RippleAndroid') {
extraProps['borderless'] = background.borderless;
extraProps['rippleColor'] = background.color;
} else if (background.type === 'ThemeAttrAndroid') {
extraProps['borderless'] =
background.attribute === 'selectableItemBackgroundBorderless';
}
// I moved it from above since it should be available in all options
extraProps['rippleRadius'] = background.rippleRadius;
}
extraProps['foreground'] = this.props.useForeground;
return extraProps;
}
render() {
const { style = {}, ...rest } = this.props;
return (
<GenericTouchable
{...rest}
style={style}
extraButtonProps={this.getExtraButtonProps()}
/>
);
}
}
``` | /content/code_sandbox/src/components/touchables/TouchableNativeFeedback.android.tsx | xml | 2016-10-27T08:31:38 | 2024-08-16T12:03:40 | react-native-gesture-handler | software-mansion/react-native-gesture-handler | 5,989 | 627 |
```xml
/// <reference path="../../localtypings/qrcode.d.ts" />
let loadPromise: Promise<boolean>;
function loadQrCodeGeneratorAsync(): Promise<boolean> {
if (!loadPromise)
loadPromise = pxt.BrowserUtils.loadScriptAsync("qrcode/qrcode.min.js")
.then(() => typeof qrcode !== "undefined")
.catch(e => false)
return loadPromise;
}
export function renderAsync(url: string): Promise<string> {
return loadQrCodeGeneratorAsync()
.then(loaded => {
if (!loaded) return undefined;
const c = qrcode(0, 'L');
let m = /^(https.*\/)([0-9-]+)$/.exec(url)
if (m) {
c.addData(m[1].toUpperCase(), 'Alphanumeric')
//c.addData("HTTPS://PXT.IO/", 'Alphanumeric')
c.addData(m[2].replace(/-/g, ""), 'Numeric')
} else {
m = /^(https.*\/)(_[a-zA-Z0-9]+)$/.exec(url)
if (m) {
c.addData(m[1].toUpperCase(), 'Alphanumeric')
c.addData(m[2], 'Byte')
} else {
c.addData(url, 'Byte')
}
}
c.make()
return c.createDataURL(5, 5)
}).catch(e => {
pxt.reportException(e);
return undefined;
})
}
``` | /content/code_sandbox/webapp/src/qr.ts | xml | 2016-01-24T19:35:52 | 2024-08-16T16:39:39 | pxt | microsoft/pxt | 2,069 | 307 |
```xml
/*************************************************************
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
/**
* @fileoverview Implements the CHTMLmo wrapper for the MmlMo object
*
* @author dpvc@mathjax.org (Davide Cervone)
*/
import {CHTMLWrapper, CHTMLConstructor, StringMap} from '../Wrapper.js';
import {CommonMoMixin, DirectionVH} from '../../common/Wrappers/mo.js';
import {MmlMo} from '../../../core/MmlTree/MmlNodes/mo.js';
import {StyleList} from '../../../util/StyleList.js';
import {DIRECTION} from '../FontData.js';
/*****************************************************************/
/**
* The CHTMLmo wrapper for the MmlMo object
*
* @template N The HTMLElement node class
* @template T The Text node class
* @template D The Document class
*/
// @ts-ignore
export class CHTMLmo<N, T, D> extends
CommonMoMixin<CHTMLConstructor<any, any, any>>(CHTMLWrapper) {
/**
* The mo wrapper
*/
public static kind = MmlMo.prototype.kind;
/**
* @override
*/
public static styles: StyleList = {
'mjx-stretchy-h': {
display: 'inline-table',
width: '100%'
},
'mjx-stretchy-h > *': {
display: 'table-cell',
width: 0
},
'mjx-stretchy-h > * > mjx-c': {
display: 'inline-block',
transform: 'scalex(1.0000001)' // improves blink positioning
},
'mjx-stretchy-h > * > mjx-c::before': {
display: 'inline-block',
width: 'initial'
},
'mjx-stretchy-h > mjx-ext': {
'/* IE */ overflow': 'hidden',
'/* others */ overflow': 'clip visible',
width: '100%'
},
'mjx-stretchy-h > mjx-ext > mjx-c::before': {
transform: 'scalex(500)'
},
'mjx-stretchy-h > mjx-ext > mjx-c': {
width: 0
},
'mjx-stretchy-h > mjx-beg > mjx-c': {
'margin-right': '-.1em'
},
'mjx-stretchy-h > mjx-end > mjx-c': {
'margin-left': '-.1em'
},
'mjx-stretchy-v': {
display: 'inline-block'
},
'mjx-stretchy-v > *': {
display: 'block'
},
'mjx-stretchy-v > mjx-beg': {
height: 0
},
'mjx-stretchy-v > mjx-end > mjx-c': {
display: 'block'
},
'mjx-stretchy-v > * > mjx-c': {
transform: 'scaley(1.0000001)', // improves Firefox and blink positioning
'transform-origin': 'left center',
overflow: 'hidden'
},
'mjx-stretchy-v > mjx-ext': {
display: 'block',
height: '100%',
'box-sizing': 'border-box',
border: '0px solid transparent',
'/* IE */ overflow': 'hidden',
'/* others */ overflow': 'visible clip',
},
'mjx-stretchy-v > mjx-ext > mjx-c::before': {
width: 'initial',
'box-sizing': 'border-box'
},
'mjx-stretchy-v > mjx-ext > mjx-c': {
transform: 'scaleY(500) translateY(.075em)',
overflow: 'visible'
},
'mjx-mark': {
display: 'inline-block',
height: '0px'
}
};
/**
* @override
*/
public toCHTML(parent: N) {
const attributes = this.node.attributes;
const symmetric = (attributes.get('symmetric') as boolean) && this.stretch.dir !== DIRECTION.Horizontal;
const stretchy = this.stretch.dir !== DIRECTION.None;
if (stretchy && this.size === null) {
this.getStretchedVariant([]);
}
let chtml = this.standardCHTMLnode(parent);
if (stretchy && this.size < 0) {
this.stretchHTML(chtml);
} else {
if (symmetric || attributes.get('largeop')) {
const u = this.em(this.getCenterOffset());
if (u !== '0') {
this.adaptor.setStyle(chtml, 'verticalAlign', u);
}
}
if (this.node.getProperty('mathaccent')) {
this.adaptor.setStyle(chtml, 'width', '0');
this.adaptor.setStyle(chtml, 'margin-left', this.em(this.getAccentOffset()));
}
for (const child of this.childNodes) {
child.toCHTML(chtml);
}
}
}
/**
* Create the HTML for a multi-character stretchy delimiter
*
* @param {N} chtml The parent element in which to put the delimiter
*/
protected stretchHTML(chtml: N) {
const c = this.getText().codePointAt(0);
this.font.delimUsage.add(c);
this.childNodes[0].markUsed();
const delim = this.stretch;
const stretch = delim.stretch;
const content: N[] = [];
//
// Set up the beginning, extension, and end pieces
//
if (stretch[0]) {
content.push(this.html('mjx-beg', {}, [this.html('mjx-c')]));
}
content.push(this.html('mjx-ext', {}, [this.html('mjx-c')]));
if (stretch.length === 4) {
//
// Braces have a middle and second extensible piece
//
content.push(
this.html('mjx-mid', {}, [this.html('mjx-c')]),
this.html('mjx-ext', {}, [this.html('mjx-c')])
);
}
if (stretch[2]) {
content.push(this.html('mjx-end', {}, [this.html('mjx-c')]));
}
//
// Set the styles needed
//
const styles: StringMap = {};
const {h, d, w} = this.bbox;
if (delim.dir === DIRECTION.Vertical) {
//
// Vertical needs an extra (empty) element to get vertical position right
// in some browsers (e.g., Safari)
//
content.push(this.html('mjx-mark'));
styles.height = this.em(h + d);
styles.verticalAlign = this.em(-d);
} else {
styles.width = this.em(w);
}
//
// Make the main element and add it to the parent
//
const dir = DirectionVH[delim.dir];
const properties = {class: this.char(delim.c || c), style: styles};
const html = this.html('mjx-stretchy-' + dir, properties, content);
this.adaptor.append(chtml, html);
}
}
``` | /content/code_sandbox/ts/output/chtml/Wrappers/mo.ts | xml | 2016-02-23T09:52:03 | 2024-08-16T04:46:50 | MathJax-src | mathjax/MathJax-src | 2,017 | 1,617 |
```xml
//
//
// Microsoft Bot Framework: path_to_url
//
// Bot Framework Emulator Github:
// path_to_url
//
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import { createGetConversationHandler } from './getConversation';
describe('stream handler', () => {
it('should attach the conversation to the reqiest', () => {
const mockConversation = {};
const state: any = {
conversations: {
conversationById: jest.fn(() => mockConversation),
},
};
const req: any = {
params: {
conversationId: 'convo1',
},
};
const res: any = {};
const next = jest.fn();
const getConversation = createGetConversationHandler(state);
getConversation(req, res, next);
expect(req.conversation).toEqual(mockConversation);
expect(next).toHaveBeenCalled();
});
});
``` | /content/code_sandbox/packages/app/main/src/server/routes/directLine/handlers/getConversation.spec.ts | xml | 2016-11-11T23:15:09 | 2024-08-16T12:45:29 | BotFramework-Emulator | microsoft/BotFramework-Emulator | 1,803 | 398 |
```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="M15 6.1c0 1.376-1.363 0.694-1.363 0.694L12.5 7H11a5.31 5.31 0 0 1-1.5 2 3.272 3.272 0 0 1-0.523 1.125c-0.077 0.091-0.06 0.2-0.068 0.33l0.091 2.3a0.264 0.264 0 0 1-0.266 0.25 0.242 0.242 0 0 1-0.234-0.205L8 9.5H4v3.253a0.247 0.247 0 0 1-0.247 0.247 0.25 0.25 0 0 1-0.24-0.2L3 10v-0.5a8.2 8.2 0 0 1-1.426-0.1A1.886 1.886 0 0 1 0.9 10.826c-0.128 0.083-0.148 0.211-0.133 0.386l0.19 1.538a0.25 0.25 0 0 1-0.25 0.25 0.238 0.238 0 0 1-0.23-0.174l-0.427-1.7a0.35 0.35 0 0 1 0.055-0.3c0.437-0.68-0.049-2.55-0.049-2.55A1.354 1.354 0 0 1 0 7.922V5.5a2.027 2.027 0 0 1 2.736-1.914s0.1 0.03 0.142 0.049a15.15 15.15 0 0 0 3.814 0.038l0.18-0.062a1.842 1.842 0 0 1 1.26 0c0.078 0.02 0.154 0.05 0.226 0.089 0.1 0.049 0.196 0.106 0.287 0.171A1.8 1.8 0 0 0 9.5 4h1V3l0.5 0.5c0.5-1.5 2.5-1 2.5-1a1.687 1.687 0 0 0-1.5 1l2.5 2a0.612 0.612 0 0 1 0.186-0.069 0.318 0.318 0 0 1 0.314 0.321V6.1Z"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_preset_maki_slaughterhouse.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 756 |
```xml
import { FunctionComponent } from 'react';
import { TChildrenRendererProps } from './shared-types';
import renderChildren from './renderChildren';
/**
* A component to render collections of tnodes.
* Especially useful when used with {@link useTNodeChildrenProps}.
*/
const TChildrenRenderer: FunctionComponent<TChildrenRendererProps> =
renderChildren.bind(null);
export default TChildrenRenderer;
``` | /content/code_sandbox/packages/render-html/src/TChildrenRenderer.tsx | xml | 2016-11-29T10:50:53 | 2024-08-08T06:53:22 | react-native-render-html | meliorence/react-native-render-html | 3,445 | 81 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="path_to_url"
android:id="@+id/deviceInfoRv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:overScrollMode="never" />
``` | /content/code_sandbox/lib/utildebug/src/main/res/layout/du_debug_device_info.xml | xml | 2016-07-30T18:18:32 | 2024-08-16T01:37:59 | AndroidUtilCode | Blankj/AndroidUtilCode | 33,178 | 68 |
```xml
import React from 'react';
import { MultiCascader, Button, Toggle, RadioGroup, Radio, Stack } from 'rsuite';
import DefaultPage from '@/components/Page';
import ImportGuide from '@/components/ImportGuide';
import PeoplesIcon from '@rsuite/icons/Peoples';
import AdminIcon from '@rsuite/icons/Admin';
import {
importFakerString,
mockAsyncData,
mockAsyncDataString,
mockTreeData,
mockTreeDataToString,
sandboxFakerVersion
} from '@/utils/mock';
const mockfile = {
name: 'mock.js',
content: [importFakerString, mockTreeDataToString, mockAsyncDataString].join('\n')
};
const sandboxDependencies = {
...sandboxFakerVersion
};
const inDocsComponents = {
'import-guide': () => <ImportGuide components={['MultiCascader']} />
};
export default function Page() {
return (
<DefaultPage
inDocsComponents={inDocsComponents}
dependencies={{
MultiCascader,
Button,
Toggle,
RadioGroup,
Radio,
PeoplesIcon,
AdminIcon,
Stack,
mockAsyncData,
mockTreeData
}}
sandboxDependencies={sandboxDependencies}
sandboxFiles={[mockfile]}
/>
);
}
``` | /content/code_sandbox/docs/pages/components/multi-cascader/index.tsx | xml | 2016-06-06T02:27:46 | 2024-08-16T16:41:54 | rsuite | rsuite/rsuite | 8,263 | 273 |
```xml
import _ from 'lodash';
import sinon from 'sinon';
import conformToMask from '../conformToMask';
import dynamicTests from './dynamicTests';
import testParameters, { noGuideMode, acceptedCharInMask, escapedMaskChar } from './testParameters';
import { convertMaskToPlaceholder } from '../utilities';
import keepCharPositionsTests from './keepCharPositionsTests';
import maskFunctionTests from './maskFunctionTests';
const testInputs = ['rawValue', 'mask', 'previousConformedValue', 'currentCaretPosition'];
const placeholderChar = '_';
describe('conformToMask', () => {
it('throws if mask is not an array or function', () => {
const err = 'Text-mask:conformToMask; The mask property must be an array.';
expect(() => conformToMask('', false)).to.throw(err);
expect(() => conformToMask('', true)).to.throw(err);
expect(() => conformToMask('', 'abc')).to.throw(err);
expect(() => conformToMask('', 123)).to.throw(err);
expect(() => conformToMask('', null)).to.throw(err);
expect(() => conformToMask('', {})).to.throw(err);
});
it('works with mask functions', () => {
const mask = () => [/\d/, /\d/, /\d/, /\d/];
expect(() => conformToMask('', mask)).to.not.throw();
});
it('calls the mask function', () => {
const maskSpy = sinon.spy(() => [/\d/, /\d/, /\d/, /\d/]);
const result = conformToMask('2', maskSpy);
expect(result.conformedValue).to.equal('2___');
expect(maskSpy.callCount).to.equal(1);
});
it('passes the rawValue to the mask function', () => {
const mask = value => {
expect(typeof value).to.equal('string');
expect(value).to.equal('2');
return [/\d/, /\d/, /\d/, /\d/];
};
const result = conformToMask('2', mask);
expect(result.conformedValue).to.equal('2___');
});
it('passes the config to the mask function', () => {
const mask = (_value, config) => {
expect(typeof config).to.equal('object');
expect(config).to.deep.equal({
currentCaretPosition: 2,
previousConformedValue: '1',
placeholderChar: '_'
});
return [/\d/, /\d/, /\d/, /\d/];
};
const result = conformToMask('12', mask, {
currentCaretPosition: 2,
previousConformedValue: '1',
placeholderChar: '_'
});
expect(result.conformedValue).to.equal('12__');
});
it('processes the result of the mask function and removes caretTraps', () => {
const mask = () => [/\d/, /\d/, '[]', '.', '[]', /\d/, /\d/];
const result = conformToMask('2', mask);
expect(result.conformedValue).to.equal('2_.__');
});
describe('Accepted character in mask', () => {
dynamicTests(
_.filter(acceptedCharInMask, test => !(test as any).skip),
test => ({
description:
`for input ${JSON.stringify(_.pick(test, testInputs))}, ` +
`it outputs '${test.conformedValue}' Line: ${test.line}`,
body: () => {
expect(
conformToMask(test.rawValue, test.mask, {
guide: true,
previousConformedValue: test.previousConformedValue,
placeholder: convertMaskToPlaceholder(test.mask, placeholderChar),
currentCaretPosition: test.currentCaretPosition
}).conformedValue
).to.equal(test.conformedValue);
}
})
);
});
describe('Guide mode tests', () => {
dynamicTests(
testParameters,
test => ({
description:
`for input ${JSON.stringify(_.pick(test, testInputs))}, ` +
`it outputs '${test.conformedValue}' Line: ${test.line}`,
body: () => {
expect(
conformToMask(test.rawValue, test.mask, {
previousConformedValue: test.previousConformedValue,
placeholder: convertMaskToPlaceholder(test.mask, placeholderChar),
currentCaretPosition: test.currentCaretPosition
}).conformedValue
).to.equal(test.conformedValue);
}
})
);
});
describe('No guide mode', () => {
dynamicTests(
noGuideMode,
test => ({
description:
`for input ${JSON.stringify(_.pick(test, testInputs))}, ` +
`it outputs '${test.conformedValue}'`,
body: () => {
expect(
conformToMask(test.rawValue, test.mask, {
guide: false,
previousConformedValue: test.previousConformedValue,
placeholder: convertMaskToPlaceholder(test.mask, placeholderChar),
currentCaretPosition: test.currentCaretPosition
}).conformedValue
).to.equal(test.conformedValue);
}
})
);
});
describe('Allow escaped masking character in mask', () => {
dynamicTests(
escapedMaskChar,
test => ({
description:
`for input ${JSON.stringify(_.pick(test, testInputs))}, ` +
`it outputs '${test.conformedValue}'`,
body: () => {
expect(
conformToMask(test.rawValue, test.mask, {
guide: true,
previousConformedValue: test.previousConformedValue,
placeholder: convertMaskToPlaceholder(test.mask, placeholderChar),
currentCaretPosition: test.currentCaretPosition
}).conformedValue
).to.equal(test.conformedValue);
}
})
);
});
describe('keepCharPositionsTests', () => {
dynamicTests(
keepCharPositionsTests,
test => ({
description:
`for input ${JSON.stringify(_.pick(test, testInputs))}, ` +
`it outputs '${test.conformedValue}' Line: ${test.line}`,
body: () => {
expect(
conformToMask(test.rawValue, test.mask, {
guide: true,
previousConformedValue: test.previousConformedValue,
placeholder: convertMaskToPlaceholder(test.mask, placeholderChar),
keepCharPositions: true,
currentCaretPosition: test.currentCaretPosition
}).conformedValue
).to.equal(test.conformedValue);
}
})
);
});
describe('Mask function', () => {
it('works with mask functions', () => {
const mask = () => [/\d/, /\d/, /\d/, /\d/];
expect(() => conformToMask('', mask)).to.not.throw();
});
it('calls the mask function', () => {
const maskSpy = sinon.spy(() => [/\d/, /\d/, /\d/, /\d/]);
const result = conformToMask('2', maskSpy);
expect(result.conformedValue).to.equal('2___');
expect(maskSpy.callCount).to.equal(1);
});
it('passes the rawValue to the mask function', () => {
const mask = value => {
expect(typeof value).to.equal('string');
expect(value).to.equal('2');
return [/\d/, /\d/, /\d/, /\d/];
};
const result = conformToMask('2', mask);
expect(result.conformedValue).to.equal('2___');
});
it('passes the config to the mask function', () => {
const mask = (_value, config) => {
expect(typeof config).to.equal('object');
expect(config).to.deep.equal({
currentCaretPosition: 2,
previousConformedValue: '1',
placeholderChar: '_'
});
return [/\d/, /\d/, /\d/, /\d/];
};
const result = conformToMask('12', mask, {
currentCaretPosition: 2,
previousConformedValue: '1',
placeholderChar: '_'
});
expect(result.conformedValue).to.equal('12__');
});
it('processes the result of the mask function and removes caretTraps', () => {
const mask = () => [/\d/, /\d/, '[]', '.', '[]', /\d/, /\d/];
const result = conformToMask('2', mask);
expect(result.conformedValue).to.equal('2_.__');
});
dynamicTests(
maskFunctionTests,
test => ({
description:
`for input ${JSON.stringify(_.pick(test, testInputs))}, ` +
`it outputs '${test.conformedValue}' Line: ${test.line}`,
body: () => {
expect(
conformToMask(test.rawValue, test.mask, {
guide: true,
previousConformedValue: test.previousConformedValue,
placeholder: convertMaskToPlaceholder(test.mask, placeholderChar),
currentCaretPosition: test.currentCaretPosition
}).conformedValue
).to.equal(test.conformedValue);
}
})
);
});
});
``` | /content/code_sandbox/src/MaskedInput/test/conformToMaskSpec.ts | xml | 2016-06-06T02:27:46 | 2024-08-16T16:41:54 | rsuite | rsuite/rsuite | 8,263 | 1,979 |
```xml
import { paramCase } from 'change-case';
export default (compName) => `import React, { forwardRef, useContext } from 'react';
import { createBEM } from '@zarm-design/bem';
import { ConfigContext } from '../config-provider';
import type { HTMLProps } from '../utils/utilityTypes';
import type { Base${compName}Props } from './interface';
export interface ${compName}CssVars {
}
export type ${compName}Props = Base${compName}Props & HTMLProps<${compName}CssVars>;
const ${compName} = forwardRef<HTMLDivElement, ${compName}Props>((props, ref) => {
const { className, children, ...restProps } = props;
const { prefixCls } = useContext(ConfigContext);
const bem = createBEM('${paramCase(compName)}', { prefixCls });
const cls = bem([className]);
return (
<div ref={ref} className={cls} {...restProps}>
{children}
</div>
);
});
${compName}.displayName = '${compName}';
${compName}.defaultProps = {};
export default ${compName};
`;
``` | /content/code_sandbox/packages/zarm-cli/src/templates/component/compTpl.ts | xml | 2016-07-13T11:45:37 | 2024-08-12T19:23:48 | zarm | ZhongAnTech/zarm | 1,707 | 246 |
```xml
import * as Log from '../../log';
import { logCmdError } from '../../utils/errors';
const CTRL_C = '\u0003';
const debug = require('debug')('expo:start:interface:keyPressHandler') as typeof console.log;
/** An abstract key stroke interceptor. */
export class KeyPressHandler {
private isInterceptingKeyStrokes = false;
private isHandlingKeyPress = false;
constructor(public onPress: (key: string) => Promise<any>) {}
/** Start observing interaction pause listeners. */
createInteractionListener() {
// Support observing prompts.
let wasIntercepting = false;
const listener = ({ pause }: { pause: boolean }) => {
if (pause) {
// Track if we were already intercepting key strokes before pausing, so we can
// resume after pausing.
wasIntercepting = this.isInterceptingKeyStrokes;
this.stopInterceptingKeyStrokes();
} else if (wasIntercepting) {
// Only start if we were previously intercepting.
this.startInterceptingKeyStrokes();
}
};
return listener;
}
private handleKeypress = async (key: string) => {
// Prevent sending another event until the previous event has finished.
if (this.isHandlingKeyPress && key !== CTRL_C) {
return;
}
this.isHandlingKeyPress = true;
try {
debug(`Key pressed: ${key}`);
await this.onPress(key);
} catch (error: any) {
await logCmdError(error);
} finally {
this.isHandlingKeyPress = false;
}
};
/** Start intercepting all key strokes and passing them to the input `onPress` method. */
startInterceptingKeyStrokes() {
if (this.isInterceptingKeyStrokes) {
return;
}
this.isInterceptingKeyStrokes = true;
const { stdin } = process;
// TODO: This might be here because of an old Node version.
if (!stdin.setRawMode) {
Log.warn('Using a non-interactive terminal, keyboard commands are disabled.');
return;
}
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', this.handleKeypress);
}
/** Stop intercepting all key strokes. */
stopInterceptingKeyStrokes() {
if (!this.isInterceptingKeyStrokes) {
return;
}
this.isInterceptingKeyStrokes = false;
const { stdin } = process;
stdin.removeListener('data', this.handleKeypress);
// TODO: This might be here because of an old Node version.
if (!stdin.setRawMode) {
Log.warn('Using a non-interactive terminal, keyboard commands are disabled.');
return;
}
stdin.setRawMode(false);
stdin.resume();
}
}
``` | /content/code_sandbox/packages/@expo/cli/src/start/interface/KeyPressHandler.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 621 |
```xml
import { DocumentNode } from 'graphql'
import { isRef } from 'vue-demi'
import { useQueryImpl, DocumentParameter, VariablesParameter, OptionsParameter, UseQueryOptions, UseQueryReturn } from './useQuery'
import type { OperationVariables } from '@apollo/client/core'
import { isServer } from './util/env.js'
export interface UseLazyQueryReturn<TResult, TVariables extends OperationVariables> extends UseQueryReturn<TResult, TVariables> {
/**
* Activate the query and starts loading.
* @param document Override document
* @param variables Override variables
* @param options Override options
* @returns Returns false if the query is already active, otherwise the next result of the query.
*/
load: (document?: DocumentNode | null, variables?: TVariables | null, options?: UseQueryOptions | null) => false | Promise<TResult>
}
export function useLazyQuery<
TResult = any,
TVariables extends Record<string, unknown> = any,
> (
document: DocumentParameter<TResult, TVariables>,
variables?: VariablesParameter<TVariables>,
options?: OptionsParameter<TResult, TVariables>,
): UseLazyQueryReturn<TResult, TVariables> {
const query = useQueryImpl<TResult, TVariables>(document, variables, options, true)
function load (
document?: DocumentNode | null,
variables?: TVariables | null,
options?: UseQueryOptions | null,
) {
if (document) {
query.document.value = document
}
if (variables) {
query.variables.value = variables
}
if (options) {
Object.assign(isRef(query.options) ? query.options.value : query.options, options)
}
const isFirstRun = query.forceDisabled.value
if (isFirstRun) {
query.forceDisabled.value = false
// If SSR, we need to start the query manually since `watch` on `isEnabled` in `useQueryImpl` won't be called.
if (isServer) {
query.start()
}
return new Promise<TResult>((resolve, reject) => {
const { off: offResult } = query.onResult((result) => {
if (!result.loading) {
resolve(result.data)
offResult()
offError()
}
})
const { off: offError } = query.onError((error) => {
reject(error)
offResult()
offError()
})
})
} else {
return false
}
}
return {
...query,
load,
}
}
``` | /content/code_sandbox/packages/vue-apollo-composable/src/useLazyQuery.ts | xml | 2016-09-18T18:44:06 | 2024-08-14T21:22:24 | apollo | vuejs/apollo | 6,009 | 539 |
```xml
<resources>
<string name="app_name">Sample</string>
<string name="navigation_drawer_open">Open navigation drawer</string>
<string name="navigation_drawer_close">Close navigation drawer</string>
<string name="action_settings">Settings</string>
<string name="image_view_description">ImageView</string>
<!-- TourGuide Text -->
<string name="guide_setup_profile">Welcome. Let\'s setup your profile. Just tap on the circle.</string>
</resources>
``` | /content/code_sandbox/sample/src/main/res/values/strings.xml | xml | 2016-01-30T13:08:17 | 2024-07-10T06:26:08 | MaterialIntroView | iammert/MaterialIntroView | 2,433 | 106 |
```xml
import * as React from 'react';
import { Image, StyleProp, StyleSheet, View, ViewStyle } from 'react-native';
import { getCardCoverStyle } from './utils';
import { useInternalTheme } from '../../core/theming';
import { grey200 } from '../../styles/themes/v2/colors';
import type { ThemeProp } from '../../types';
import { splitStyles } from '../../utils/splitStyles';
export type Props = React.ComponentPropsWithRef<typeof Image> & {
/**
* @internal
*/
index?: number;
/**
* @internal
*/
total?: number;
style?: StyleProp<ViewStyle>;
/**
* @optional
*/
theme?: ThemeProp;
};
/**
* A component to show a cover image inside a Card.
*
* ## Usage
* ```js
* import * as React from 'react';
* import { Card } from 'react-native-paper';
*
* const MyComponent = () => (
* <Card>
* <Card.Cover source={{ uri: 'path_to_url }} />
* </Card>
* );
*
* export default MyComponent;
* ```
*
* @extends Image props path_to_url#props
*/
const CardCover = ({
index,
total,
style,
theme: themeOverrides,
...rest
}: Props) => {
const theme = useInternalTheme(themeOverrides);
const flattenedStyles = (StyleSheet.flatten(style) || {}) as ViewStyle;
const [, borderRadiusStyles] = splitStyles(
flattenedStyles,
(style) => style.startsWith('border') && style.endsWith('Radius')
);
const coverStyle = getCardCoverStyle({
theme,
index,
total,
borderRadiusStyles,
});
return (
<View style={[styles.container, coverStyle, style]}>
<Image
{...rest}
style={[styles.image, coverStyle]}
accessibilityIgnoresInvertColors
/>
</View>
);
};
CardCover.displayName = 'Card.Cover';
const styles = StyleSheet.create({
container: {
height: 195,
backgroundColor: grey200,
overflow: 'hidden',
},
image: {
flex: 1,
height: undefined,
width: undefined,
padding: 16,
justifyContent: 'flex-end',
},
});
export default CardCover;
// @component-docs ignore-next-line
export { CardCover };
``` | /content/code_sandbox/src/components/Card/CardCover.tsx | xml | 2016-10-19T05:56:53 | 2024-08-16T08:48:04 | react-native-paper | callstack/react-native-paper | 12,646 | 511 |
```xml
import React from 'react';
import {
HTMLFieldProps,
connectField,
filterDOMProps,
joinName,
useField,
} from 'uniforms';
export type ListDelFieldProps = HTMLFieldProps<unknown, HTMLSpanElement>;
function ListDel({ disabled, name, readOnly, ...props }: ListDelFieldProps) {
const nameParts = joinName(null, name);
const nameIndex = +nameParts[nameParts.length - 1];
const parentName = joinName(nameParts.slice(0, -1));
const parent = useField<{ minCount?: number }, unknown[]>(
parentName,
{},
{ absoluteName: true },
)[0];
disabled ||= readOnly || parent.minCount! >= parent.value!.length;
function onAction(
event:
| React.KeyboardEvent<HTMLSpanElement>
| React.MouseEvent<HTMLSpanElement, MouseEvent>,
) {
if (!disabled && (!('key' in event) || event.key === 'Enter')) {
const value = parent.value!.slice();
value.splice(nameIndex, 1);
parent.onChange(value);
}
}
return (
<span
{...filterDOMProps(props)}
onClick={onAction}
onKeyDown={onAction}
role="button"
tabIndex={0}
>
-
</span>
);
}
export default connectField<ListDelFieldProps>(ListDel, {
initialValue: false,
kind: 'leaf',
});
``` | /content/code_sandbox/packages/uniforms-unstyled/src/ListDelField.tsx | xml | 2016-05-10T13:08:50 | 2024-08-13T11:27:18 | uniforms | vazco/uniforms | 1,934 | 311 |
```xml
import styled from "@emotion/styled"
import { observer } from "mobx-react-lite"
import { FC, useCallback } from "react"
import { useStores } from "../../hooks/useStores"
import { Localized } from "../../localize/useLocalization"
import { AutoScrollButton } from "../Toolbar/AutoScrollButton"
import QuantizeSelector from "../Toolbar/QuantizeSelector/QuantizeSelector"
import { ToolSelector } from "../Toolbar/ToolSelector"
import { Toolbar } from "../Toolbar/Toolbar"
const Title = styled.span`
font-weight: bold;
margin-right: 2em;
font-size: 1rem;
margin-left: 0.5rem;
`
const FlexibleSpacer = styled.div`
flex-grow: 1;
`
export const TempoGraphToolbar: FC = observer(() => {
const { tempoEditorStore } = useStores()
const { autoScroll, quantize, isQuantizeEnabled, mouseMode } =
tempoEditorStore
const onSelectQuantize = useCallback(
(denominator: number) => (tempoEditorStore.quantize = denominator),
[tempoEditorStore],
)
const onClickQuantizeSwitch = useCallback(() => {
tempoEditorStore.isQuantizeEnabled = !tempoEditorStore.isQuantizeEnabled
}, [tempoEditorStore])
return (
<Toolbar>
<Title>
<Localized name="tempo" />
</Title>
<FlexibleSpacer />
<ToolSelector
mouseMode={mouseMode}
onSelect={useCallback(
(mouseMode: any) => (tempoEditorStore.mouseMode = mouseMode),
[],
)}
/>
<QuantizeSelector
value={quantize}
enabled={isQuantizeEnabled}
onSelect={onSelectQuantize}
onClickSwitch={onClickQuantizeSwitch}
/>
<AutoScrollButton
onClick={() => (tempoEditorStore.autoScroll = !autoScroll)}
selected={autoScroll}
/>
</Toolbar>
)
})
``` | /content/code_sandbox/app/src/components/TempoGraph/TempoGraphToolbar.tsx | xml | 2016-03-06T15:19:53 | 2024-08-15T14:27:10 | signal | ryohey/signal | 1,238 | 425 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Behavior Version="5">
<Node Class="Behaviac.Design.Nodes.Behavior" AgentType="EmployeeParTestAgent" Domains="" Enable="true" HasOwnPrefabData="false" Id="-1" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<DescriptorRefs value="0:" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.Sequence" Enable="true" HasOwnPrefabData="false" Id="0" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.Sequence" Enable="true" HasOwnPrefabData="false" Id="1" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="4" Opl="static TNS::NE::NAT::eColor Self.ParTestAgentBase::STV_ECOLOR_0" Opr="Self.ParTestAgentBase::Func_eColorIR(static TNS::NE::NAT::eColor Self.ParTestAgentBase::STV_ECOLOR_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="5" Opl="static bool Self.ParTestAgentBase::STV_BOOL_0" Opr="Self.ParTestAgentBase::Func_BooleanIR(static bool Self.ParTestAgentBase::STV_BOOL_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="6" Opl="static char Self.ParTestAgentBase::STV_CHAR_0" Opr="Self.ParTestAgentBase::Func_CharIR(static char Self.ParTestAgentBase::STV_CHAR_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="7" Opl="static vector<TNS::NE::NAT::eColor> Self.ParTestAgentBase::STV_LIST_ECOLOR_0" Opr="Self.ParTestAgentBase::Func_eColorListIR(static vector<TNS::NE::NAT::eColor> Self.ParTestAgentBase::STV_LIST_ECOLOR_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="8" Opl="static vector<bool> Self.ParTestAgentBase::STV_LIST_BOOL_0" Opr="Self.ParTestAgentBase::Func_BooleanListIR(static vector<bool> Self.ParTestAgentBase::STV_LIST_BOOL_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="9" Opl="static vector<char> Self.ParTestAgentBase::STV_LIST_CHAR_0" Opr="Self.ParTestAgentBase::Func_CharListIR(static vector<char> Self.ParTestAgentBase::STV_LIST_CHAR_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="10" Opl="static vector<sbyte> Self.ParTestAgentBase::STV_LIST_SBYTE_0" Opr="Self.ParTestAgentBase::Func_SByteListIR(static vector<sbyte> Self.ParTestAgentBase::STV_LIST_SBYTE_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
</Connector>
</Node>
<Node Class="PluginBehaviac.Nodes.Sequence" Enable="true" HasOwnPrefabData="false" Id="2" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="15" Opl="static int Self.ParTestAgent::STV_INT_0" Opr="Self.ParTestAgent::Func_IntIR(static int Self.ParTestAgent::STV_INT_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="12" Opl="static TNS::ST::PER::WRK::kEmployee Self.ParTestAgent::STV_KEMPLOYEE_0" Opr="Self.ParTestAgent::Func_kEmployeeIR(static TNS::ST::PER::WRK::kEmployee Self.ParTestAgent::STV_KEMPLOYEE_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="13" Opl="static vector<int> Self.ParTestAgent::STV_LIST_INT_0" Opr="Self.ParTestAgent::Func_IntListIR(static vector<int> Self.ParTestAgent::STV_LIST_INT_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="11" Opl="static behaviac::vector<TNS::ST::PER::WRK::kEmployee> Self.ParTestAgent::STV_LIST_KEMPLOYEE_0" Opr="Self.ParTestAgent::Func_kEmployeeListIR(static behaviac::vector<TNS::ST::PER::WRK::kEmployee> Self.ParTestAgent::STV_LIST_KEMPLOYEE_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
</Connector>
</Node>
<Node Class="PluginBehaviac.Nodes.Sequence" Enable="true" HasOwnPrefabData="false" Id="3" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
<Connector Identifier="GenericChildren">
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="14" Opl="static float Self.EmployeeParTestAgent::STV_F_0" Opr="Self.EmployeeParTestAgent::Func_SingleIR(static float Self.EmployeeParTestAgent::STV_F_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="19" Opl="static string Self.EmployeeParTestAgent::STV_STR_0" Opr="Self.EmployeeParTestAgent::Func_StringIR(static string Self.EmployeeParTestAgent::STV_STR_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="17" Opl="static behaviac::Agent Self.EmployeeParTestAgent::STV_AGENT_0" Opr="Self.EmployeeParTestAgent::Func_AgentIR(static behaviac::Agent Self.EmployeeParTestAgent::STV_AGENT_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="18" Opl="static vector<float> Self.EmployeeParTestAgent::STV_LIST_F_0" Opr="Self.EmployeeParTestAgent::Func_SingleListIR(static vector<float> Self.EmployeeParTestAgent::STV_LIST_F_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="16" Opl="static vector<string> Self.EmployeeParTestAgent::STV_LIST_STR_0" Opr="Self.EmployeeParTestAgent::Func_StringListIR(static vector<string> Self.EmployeeParTestAgent::STV_LIST_STR_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
<Node Class="PluginBehaviac.Nodes.Assignment" Enable="true" HasOwnPrefabData="false" Id="20" Opl="static behaviac::vector<behaviac::Agent> Self.EmployeeParTestAgent::STV_LIST_AGENT_0" Opr="Self.EmployeeParTestAgent::Func_AgentListIR(static behaviac::vector<behaviac::Agent> Self.EmployeeParTestAgent::STV_LIST_AGENT_0)" PrefabName="" PrefabNodeId="-1">
<Comment Background="NoColor" Text="" />
</Node>
</Connector>
</Node>
</Connector>
</Node>
</Connector>
</Node>
</Behavior>
``` | /content/code_sandbox/integration/unity/Assets/behaviac/workspace/behaviors/par_test/static_property_as_left_value_and_param.xml | xml | 2016-11-21T05:08:08 | 2024-08-16T07:18:30 | behaviac | Tencent/behaviac | 2,831 | 2,223 |
```xml
import { getUserAgent } from '../src/utils/get-user-agent';
describe('getUserAgent util', () => {
test('should resolve with empty string if nothing found', () => {
const userAgent = getUserAgent({
headers: {},
} as any);
expect(userAgent).toEqual('');
});
test('should use user-agent header', () => {
const userAgent = getUserAgent({
headers: {
'user-agent': 'IE',
},
} as any);
expect(userAgent).toEqual('IE');
});
test('should use x-ucbrowser-ua header', () => {
const userAgent = getUserAgent({
headers: {
'x-ucbrowser-ua': 'IE',
},
} as any);
expect(userAgent).toEqual('IE');
});
test('should favor x-ucbrowser-ua over user-agent header', () => {
const userAgent = getUserAgent({
headers: {
'user-agent': 'Chrome',
'x-ucbrowser-ua': 'IE',
},
} as any);
expect(userAgent).toEqual('IE');
});
});
``` | /content/code_sandbox/packages/express-session/__tests__/utils.ts | xml | 2016-10-07T01:43:23 | 2024-07-14T11:57:08 | accounts | accounts-js/accounts | 1,492 | 238 |
```xml
<?xml version="1.0" encoding="utf-8"?><HelpTOCNode Title="CSharpParser Properties" Url="html/b717f267-2662-14ed-5247-fefc4d1d296b.htm"><HelpTOCNode Title="Args Property " Url="html/a456d967-d82c-977c-c4bc-f0399b313940.htm" /><HelpTOCNode Title="CmdScripts Property " Url="html/f09af14a-a96c-ff1c-f1b5-55440434391d.htm" /><HelpTOCNode Title="Code Property " Url="html/3e90a541-99ac-2d3d-ced7-932cec839e04.htm" /><HelpTOCNode Title="CompilerOptions Property " Url="html/d6b0dba1-3686-d6c9-603d-a8069d4da7f8.htm" /><HelpTOCNode Title="ExtraSearchDirs Property " Url="html/aa06b467-db5b-91fa-cfee-eafe8a850bba.htm" /><HelpTOCNode Title="HostOptions Property " Url="html/aada4d22-a321-2e08-5a3a-be3b1294612f.htm" /><HelpTOCNode Title="IgnoreNamespaces Property " Url="html/99715cef-706e-a399-64e1-da83f52f4b31.htm" /><HelpTOCNode Title="Imports Property " Url="html/834b1fdd-fabe-a0c9-6b35-3ce78dda2645.htm" /><HelpTOCNode Title="Inits Property " Url="html/471753f8-9f49-0b80-2adb-cca16d544c2e.htm" /><HelpTOCNode Title="ModifiedCode Property " Url="html/53b51249-bd71-9894-2630-5e027d1a169a.htm" /><HelpTOCNode Title="NuGets Property " Url="html/e0f33ea5-a8ae-ec13-347f-628523337c10.htm" /><HelpTOCNode Title="Precompilers Property " Url="html/b5c3d6fc-b602-6a2e-53ad-395d817f77fd.htm" /><HelpTOCNode Title="RefAssemblies Property " Url="html/15340d94-9413-8591-1a8a-4e72c0a5e954.htm" /><HelpTOCNode Title="References Property " Url="html/6425d73f-7f0d-6e96-f3b3-8506f414cca5.htm" /><HelpTOCNode Title="RefNamespaces Property " Url="html/8ffb5221-d395-1789-803e-2716762a85b6.htm" /><HelpTOCNode Title="ResFiles Property " Url="html/f278c301-ea20-80a0-593e-6a912b0eda89.htm" /></HelpTOCNode>
``` | /content/code_sandbox/docs/help/toc/b717f267-2662-14ed-5247-fefc4d1d296b.xml | xml | 2016-01-16T05:50:23 | 2024-08-14T17:35:38 | cs-script | oleg-shilo/cs-script | 1,583 | 679 |
```xml
import clone from 'lodash/clone';
/**
* A function that takes translations from a standard react-admin language package and converts them to i18next format.
* It transforms the following:
* - interpolations wrappers from `%{foo}` to `{{foo}}` unless a prefix and/or a suffix are provided
* - pluralization messages from a single key containing text like `"key": "foo |||| bar"` to multiple keys `"foo_one": "foo"` and `"foo_other": "bar"`
* @param raMessages The translations to convert. This is an object as found in packages such as ra-language-english.
* @param options Options to customize the conversion.
* @param options.prefix The prefix to use for interpolation variables. Defaults to `{{`.
* @param options.suffix The suffix to use for interpolation variables. Defaults to `}}`.
* @returns The converted translations as an object.
*
* @example Convert the english translations from ra-language-english to i18next format
* import englishMessages from 'ra-language-english';
* import { convertRaMessagesToI18next } from 'ra-i18n-18next';
*
* const messages = convertRaMessagesToI18next(englishMessages);
*
* @example Convert the english translations from ra-language-english to i18next format with custom interpolation wrappers
* import englishMessages from 'ra-language-english';
* import { convertRaMessagesToI18next } from 'ra-i18n-18next';
*
* const messages = convertRaMessagesToI18next(englishMessages, {
* prefix: '#{',
* suffix: '}#',
* });
*/
export const convertRaTranslationsToI18next = (
raMessages: object,
{ prefix = '{{', suffix = '}}' } = {}
) => {
return Object.keys(raMessages).reduce((acc, key) => {
if (typeof acc[key] === 'object') {
acc[key] = convertRaTranslationsToI18next(acc[key], {
prefix,
suffix,
});
return acc;
}
const message = acc[key] as string;
if (message.indexOf(' |||| ') > -1) {
const pluralVariants = message.split(' |||| ');
if (
pluralVariants.length > 2 &&
process.env.NODE_ENV === 'development'
) {
console.warn(
'A message contains more than two plural forms so we can not convert it to i18next format automatically. You should provide your own translations for this language.'
);
}
acc[`${key}_one`] = convertRaTranslationToI18next(
pluralVariants[0],
{
prefix,
suffix,
}
);
acc[`${key}_other`] = convertRaTranslationToI18next(
pluralVariants[1],
{
prefix,
suffix,
}
);
delete acc[key];
} else {
acc[key] = convertRaTranslationToI18next(message, {
prefix,
suffix,
});
}
return acc;
}, clone(raMessages));
};
/**
* A function that takes a single translation text from a standard react-admin language package and converts it to i18next format.
* It transforms the interpolations wrappers from `%{foo}` to `{{foo}}` unless a prefix and/or a suffix are provided
*
* @param translationText The translation text to convert.
* @param options Options to customize the conversion.
* @param options.prefix The prefix to use for interpolation variables. Defaults to `{{`.
* @param options.suffix The suffix to use for interpolation variables. Defaults to `}}`.
* @returns The converted translation text.
*
* @example Convert a single message to i18next format
* import { convertRaTranslationToI18next } from 'ra-i18n-18next';
*
* const messages = convertRaTranslationToI18next("Hello %{name}!");
* // "Hello {{name}}!"
*
* @example Convert the english translations from ra-language-english to i18next format with custom interpolation wrappers
* import englishMessages from 'ra-language-english';
* import { convertRaTranslationToI18next } from 'ra-i18n-18next';
*
* const messages = convertRaTranslationToI18next("Hello %{name}!", {
* prefix: '#{',
* suffix: '}#',
* });
* // "Hello #{name}#!"
*/
export const convertRaTranslationToI18next = (
translationText: string,
{ prefix = '{{', suffix = '}}' } = {}
) => {
const result = translationText.replace(
/%\{([a-zA-Z0-9-_]*)\}/g,
(match, p1) => `${prefix}${p1}${suffix}`
);
return result;
};
``` | /content/code_sandbox/packages/ra-i18n-i18next/src/convertRaTranslationsToI18next.ts | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 1,012 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.