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
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>$(DotNetStableTargetFramework)</TargetFramework>
<LibZipSharpBundleAllNativeLibraries>true</LibZipSharpBundleAllNativeLibraries>
<OutputPath>..\..\..\..\bin\Test$(Configuration)</OutputPath>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\..\..\..\product.snk</AssemblyOriginatorKeyFile>
<DebugSymbols>True</DebugSymbols>
<DebugType>portable</DebugType>
<NoWarn>$(NoWarn);CA1305</NoWarn>
</PropertyGroup>
<Import Project="..\..\..\..\Configuration.props" />
<Import Project="..\..\..\..\external\xamarin-android-tools\src\Microsoft.Android.Build.BaseTasks\MSBuildReferences.projitems" />
<Import Project="..\..\..\..\build-tools\scripts\NUnitReferences.projitems" />
<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="$(MonoCecilVersion)" />
<Reference Include="Xamarin.Android.Build.Debugging.Tasks" Condition="Exists('$(MicrosoftAndroidSdkOutDir)Xamarin.Android.Build.Debugging.Tasks.dll')">
<HintPath>$(MicrosoftAndroidSdkOutDir)Xamarin.Android.Build.Debugging.Tasks.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Xamarin.ProjectTools\Xamarin.ProjectTools.csproj" />
<ProjectReference Include="..\..\Xamarin.Android.Build.Tasks.csproj" />
<ProjectReference Include="..\..\..\..\external\xamarin-android-tools\src\Xamarin.Android.Tools.AndroidSdk\Xamarin.Android.Tools.AndroidSdk.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Remove="DebuggingTasksTests.cs" Condition="!Exists('$(MicrosoftAndroidSdkOutDir)Xamarin.Android.Build.Debugging.Tasks.dll')" />
<Compile Remove="Resources\ApacheHttpClient.cs" />
<Compile Remove="Expected\**" />
<Compile Include="..\..\..\..\tools\assembly-store-reader-mk2\AssemblyStore\*.cs" />
<Content Include="Expected\GenerateDesignerFileExpected.cs">
<Link>..\Expected\GenerateDesignerFileExpected.cs</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Expected\GenerateDesignerFileWithElevenStyleableAttributesExpected.cs">
<Link>..\Expected\GenerateDesignerFileWithElevenStyleableAttributesExpected.cs</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Expected\GenerateDesignerFileWithLibraryReferenceExpected.cs">
<Link>..\Expected\GenerateDesignerFileWithLibraryReferenceExpected.cs</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Expected\CheckPackageManagerAssemblyOrder.java">
<Link>..\Expected\CheckPackageManagerAssemblyOrder.java</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="ELFSharp" Version="$(ELFSharpVersion)" />
<PackageReference Include="ICSharpCode.Decompiler" Version="7.2.1.6856" />
<PackageReference Include="Humanizer" Version="$(HumanizerVersion)" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\*">
<LogicalName>%(FileName)%(Extension)</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="$(XamarinAndroidSourcePath)\src\Mono.Android\javadoc-copyright.xml" LogicalName="javadoc-copyright.xml" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj | xml | 2016-03-30T15:37:14 | 2024-08-16T19:22:13 | android | dotnet/android | 1,905 | 826 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/// <reference types="@stdlib/types"/>
import { NumericArray } from '@stdlib/types/array';
/**
* Interface describing `stdevyc`.
*/
interface Routine {
/**
* Computes the standard deviation of a strided array using a one-pass algorithm proposed by Youngs and Cramer.
*
* @param N - number of indexed elements
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @returns standard deviation
*
* @example
* var x = [ 1.0, -2.0, 2.0 ];
*
* var v = stdevyc( x.length, 1, x, 1 );
* // returns ~2.0817
*/
( N: number, correction: number, x: NumericArray, stride: number ): number;
/**
* Computes the standard deviation of a strided array using a one-pass algorithm proposed by Youngs and Cramer and alternative indexing semantics.
*
* @param N - number of indexed elements
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @param offset - starting index
* @returns standard deviation
*
* @example
* var x = [ 1.0, -2.0, 2.0 ];
*
* var v = stdevyc.ndarray( x.length, 1, x, 1, 0 );
* // returns ~2.0817
*/
ndarray( N: number, correction: number, x: NumericArray, stride: number, offset: number ): number;
}
/**
* Computes the standard deviation of a strided array using a one-pass algorithm proposed by Youngs and Cramer.
*
* @param N - number of indexed elements
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @returns standard deviation
*
* @example
* var x = [ 1.0, -2.0, 2.0 ];
*
* var v = stdevyc( x.length, 1, x, 1 );
* // returns ~2.0817
*
* @example
* var x = [ 1.0, -2.0, 2.0 ];
*
* var v = stdevyc.ndarray( x.length, 1, x, 1, 0 );
* // returns ~2.0817
*/
declare var stdevyc: Routine;
// EXPORTS //
export = stdevyc;
``` | /content/code_sandbox/lib/node_modules/@stdlib/stats/base/stdevyc/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 629 |
```xml
import {Knex} from "knex";
import {createColumns} from "../../../src/index.js";
import {User} from "../models/User.js";
export function up(knex: Knex): Promise<any> {
return knex.schema.createTable(User.tableName, (table: Knex.TableBuilder) => {
createColumns(table, User);
});
}
export function down(knex: Knex): Promise<any> {
return knex.schema.dropTable("users");
}
``` | /content/code_sandbox/packages/orm/objection/test/helpers/migrations/01_users.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 98 |
```xml
import { ExpoUpdatesManifest, EmbeddedManifest } from 'expo-manifests';
export type Manifest = ExpoUpdatesManifest | EmbeddedManifest;
export declare enum UpdateCheckResultNotAvailableReason {
/**
* No update manifest or rollback directive received from the update server.
*/
NO_UPDATE_AVAILABLE_ON_SERVER = "noUpdateAvailableOnServer",
/**
* An update manifest was received from the update server, but the update is not launchable,
* or does not pass the configured selection policy.
*/
UPDATE_REJECTED_BY_SELECTION_POLICY = "updateRejectedBySelectionPolicy",
/**
* An update manifest was received from the update server, but the update has been previously
* launched on this device and never successfully launched.
*/
UPDATE_PREVIOUSLY_FAILED = "updatePreviouslyFailed",
/**
* A rollback directive was received from the update server, but the directive does not pass
* the configured selection policy.
*/
ROLLBACK_REJECTED_BY_SELECTION_POLICY = "rollbackRejectedBySelectionPolicy",
/**
* A rollback directive was received from the update server, but this app has no embedded update.
*/
ROLLBACK_NO_EMBEDDED = "rollbackNoEmbeddedConfiguration"
}
/**
* The update check result when a rollback directive is received.
*/
export type UpdateCheckResultRollBack = {
/**
* Whether an update is available. This property is false for a roll back update.
*/
isAvailable: false;
/**
* The manifest of the update when available.
*/
manifest: undefined;
/**
* Whether a roll back to embedded update is available.
*/
isRollBackToEmbedded: true;
/**
* If no new update is found, this contains one of several enum values indicating the reason.
*/
reason: undefined;
};
/**
* The update check result when a new update is found on the server.
*/
export type UpdateCheckResultAvailable = {
/**
* Whether an update is available. This property is false for a roll back update.
*/
isAvailable: true;
/**
* The manifest of the update when available.
*/
manifest: Manifest;
/**
* Whether a roll back to embedded update is available.
*/
isRollBackToEmbedded: false;
/**
* If no new update is found, this contains one of several enum values indicating the reason.
*/
reason: undefined;
};
/**
* The update check result if no new update was found.
*/
export type UpdateCheckResultNotAvailable = {
/**
* Whether an update is available. This property is false for a roll back update.
*/
isAvailable: false;
/**
* The manifest of the update when available.
*/
manifest: undefined;
/**
* Whether a roll back to embedded update is available.
*/
isRollBackToEmbedded: false;
/**
* If no new update is found, this contains one of several enum values indicating the reason.
*/
reason: UpdateCheckResultNotAvailableReason;
};
/**
* The result of checking for a new update.
*/
export type UpdateCheckResult = UpdateCheckResultRollBack | UpdateCheckResultAvailable | UpdateCheckResultNotAvailable;
/**
* @deprecated
*/
export type UpdateCheckResultSuccess = UpdateCheckResultAvailable;
/**
* @deprecated
*/
export type UpdateCheckResultFailure = UpdateCheckResultNotAvailable;
/**
* The successful result of fetching a new update.
*/
export type UpdateFetchResultSuccess = {
/**
* Whether the fetched update is new (that is, a different version than what's currently running).
* Always `true` when `isRollBackToEmbedded` is `false`.
*/
isNew: true;
/**
* The manifest of the fetched update.
*/
manifest: Manifest;
/**
* Whether the fetched update is a roll back to the embedded update.
*/
isRollBackToEmbedded: false;
};
/**
* The failed result of fetching a new update.
*/
export type UpdateFetchResultFailure = {
/**
* Whether the fetched update is new (that is, a different version than what's currently running).
* Always `false` when `isRollBackToEmbedded` is `true`.
*/
isNew: false;
/**
* The manifest of the fetched update.
*/
manifest: undefined;
/**
* Whether the fetched update is a roll back to the embedded update.
*/
isRollBackToEmbedded: false;
};
/**
* The roll back to embedded result of fetching a new update.
*/
export type UpdateFetchResultRollBackToEmbedded = {
/**
* Whether the fetched update is new (that is, a different version than what's currently running).
* Always `false` when `isRollBackToEmbedded` is `true`.
*/
isNew: false;
/**
* The manifest of the fetched update.
*/
manifest: undefined;
/**
* Whether the fetched update is a roll back to the embedded update.
*/
isRollBackToEmbedded: true;
};
/**
* The result of fetching a new update.
*/
export type UpdateFetchResult = UpdateFetchResultSuccess | UpdateFetchResultFailure | UpdateFetchResultRollBackToEmbedded;
/**
* An object representing a single log entry from `expo-updates` logging on the client.
*/
export type UpdatesLogEntry = {
/**
* The time the log was written, in milliseconds since Jan 1 1970 UTC.
*/
timestamp: number;
/**
* The log entry message.
*/
message: string;
/**
* One of the defined code values for `expo-updates` log entries.
*/
code: UpdatesLogEntryCode;
/**
* One of the defined log level or severity values.
*/
level: UpdatesLogEntryLevel;
/**
* If present, the unique ID of an update associated with this log entry.
*/
updateId?: string;
/**
* If present, the unique ID or hash of an asset associated with this log entry.
*/
assetId?: string;
/**
* If present, an Android or iOS native stack trace associated with this log entry.
*/
stacktrace?: string[];
};
/**
* The possible code values for `expo-updates` log entries
*/
export declare enum UpdatesLogEntryCode {
NONE = "None",
NO_UPDATES_AVAILABLE = "NoUpdatesAvailable",
UPDATE_ASSETS_NOT_AVAILABLE = "UpdateAssetsNotAvailable",
UPDATE_SERVER_UNREACHABLE = "UpdateServerUnreachable",
UPDATE_HAS_INVALID_SIGNATURE = "UpdateHasInvalidSignature",
UPDATE_CODE_SIGNING_ERROR = "UpdateCodeSigningError",
UPDATE_FAILED_TO_LOAD = "UpdateFailedToLoad",
ASSETS_FAILED_TO_LOAD = "AssetsFailedToLoad",
JS_RUNTIME_ERROR = "JSRuntimeError",
INITIALIZATION_ERROR = "InitializationError",
UNKNOWN = "Unknown"
}
/**
* The possible log levels for `expo-updates` log entries
*/
export declare enum UpdatesLogEntryLevel {
TRACE = "trace",
DEBUG = "debug",
INFO = "info",
WARN = "warn",
ERROR = "error",
FATAL = "fatal"
}
/**
* The possible settings that determine if `expo-updates` will check for updates on app startup.
* By default, Expo will check for updates every time the app is loaded.
* Set this to `ON_ERROR_RECOVERY` to disable automatic checking unless recovering from an error.
* Set this to `NEVER` to completely disable automatic checking.
*/
export declare enum UpdatesCheckAutomaticallyValue {
/**
* Checks for updates whenever the app is loaded. This is the default setting.
*/
ON_LOAD = "ON_LOAD",
/**
* Only checks for updates when the app starts up after an error recovery.
*/
ON_ERROR_RECOVERY = "ON_ERROR_RECOVERY",
/**
* Only checks for updates when the app starts and has a Wi-Fi connection.
*/
WIFI_ONLY = "WIFI_ONLY",
/**
* Automatic update checks are off, and update checks must be done through the JS API.
*/
NEVER = "NEVER"
}
/**
* @hidden
*/
export type LocalAssets = Record<string, string>;
/**
* @hidden
*/
export type UpdatesNativeStateRollback = {
commitTime: string;
};
/**
* The native state machine context, either read directly from a native module method,
* or received in a state change event. Used internally by this module and not exported publicly.
* @hidden
*/
export type UpdatesNativeStateMachineContext = {
isUpdateAvailable: boolean;
isUpdatePending: boolean;
isChecking: boolean;
isDownloading: boolean;
isRestarting: boolean;
latestManifest?: Manifest;
downloadedManifest?: Manifest;
rollback?: UpdatesNativeStateRollback;
checkError?: Error;
downloadError?: Error;
lastCheckForUpdateTime?: Date;
};
/**
* @hidden
*/
export type UpdatesNativeStateChangeEvent = {
context: UpdatesNativeStateMachineContext;
};
//# sourceMappingURL=Updates.types.d.ts.map
``` | /content/code_sandbox/packages/expo-updates/build/Updates.types.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 1,907 |
```xml
const GRAPHQL_WS = 'graphql-ws';
// NOTE: This protocol is deprecated and will be removed soon.
/**
* @deprecated
*/
const GRAPHQL_SUBSCRIPTIONS = 'graphql-subscriptions';
export {
GRAPHQL_WS,
GRAPHQL_SUBSCRIPTIONS,
};
``` | /content/code_sandbox/src/protocol.ts | xml | 2016-07-19T22:58:49 | 2024-07-02T18:53:16 | subscriptions-transport-ws | apollographql/subscriptions-transport-ws | 1,517 | 57 |
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ant.ui.DEFAULT_VM_INSTALL" value="false"/>
<stringAttribute key="org.eclipse.debug.core.ATTR_REFRESH_SCOPE" value="${project}"/>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
<listEntry value="/tlatools/customBuild.xml"/>
</listAttribute>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
<listEntry value="1"/>
</listAttribute>
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<stringAttribute key="org.eclipse.jdt.launching.JRE_CONTAINER" value="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.eclipse.ant.internal.launching.remote.InternalAntRunner"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="tlatools"/>
<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_ANT_TARGETS" value="test,"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LAUNCH_CONFIGURATION_BUILD_SCOPE" value="${none}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/tlatools/customBuild.xml}"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/tlatools}"/>
<stringAttribute key="process_factory_id" value="org.eclipse.ant.ui.remoteAntProcessFactory"/>
</launchConfiguration>
``` | /content/code_sandbox/tlatools/org.lamport.tlatools/ide/RunAllTLCTests.launch | xml | 2016-02-02T08:48:27 | 2024-08-16T16:50:00 | tlaplus | tlaplus/tlaplus | 2,271 | 383 |
```xml
import {
DevicePropertiesSection,
TaggerSection,
TrackedDataSection
} from "../common";
import BasicInfoSection from "../common/BasicInfoSection";
import CustomFieldsSection from "@erxes/ui-contacts/src/customers/containers/CustomFieldsSection";
import { ICustomer } from "../../types";
import { IField } from "@erxes/ui/src/types";
import { IFieldsVisibility } from "@erxes/ui-contacts/src/customers/types";
import React from "react";
import Sidebar from "@erxes/ui/src/layout/components/Sidebar";
import WebsiteActivity from "@erxes/ui-contacts/src/customers/components/common/WebsiteActivity";
import { isEnabled } from "@erxes/ui/src/utils/core";
type Props = {
customer: ICustomer;
deviceFields: IField[];
fields: IField[];
taggerRefetchQueries?: any[];
wide?: boolean;
fieldsVisibility: (key: string) => IFieldsVisibility;
deviceFieldsVisibility: (key: string) => IFieldsVisibility;
};
export default class LeftSidebar extends React.Component<Props> {
render() {
const {
customer,
fieldsVisibility,
deviceFields,
fields,
wide,
taggerRefetchQueries,
deviceFieldsVisibility
} = this.props;
return (
<Sidebar wide={wide}>
<BasicInfoSection
customer={customer}
fieldsVisibility={fieldsVisibility}
fields={fields}
/>
<TaggerSection
data={customer}
type="core:customer"
refetchQueries={taggerRefetchQueries}
/>
<CustomFieldsSection customer={customer} isDetail={true} />
<DevicePropertiesSection
customer={customer}
fields={deviceFields}
deviceFieldsVisibility={deviceFieldsVisibility}
isDetail={true}
/>
<TrackedDataSection customer={customer} />
<WebsiteActivity urlVisits={customer.urlVisits || []} />
</Sidebar>
);
}
}
``` | /content/code_sandbox/packages/core-ui/src/modules/contacts/customers/components/detail/LeftSidebar.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 419 |
```xml
import type { Server } from 'http';
import { ENV_VARS } from '@apify/consts';
import log from '@apify/log';
import { BROWSER_POOL_EVENTS, BrowserPool, OperatingSystemsName, PuppeteerPlugin } from '@crawlee/browser-pool';
import { BLOCKED_STATUS_CODES } from '@crawlee/core';
import type { PuppeteerCrawlingContext, PuppeteerGoToOptions, PuppeteerRequestHandler } from '@crawlee/puppeteer';
import {
AutoscaledPool,
EnqueueStrategy,
ProxyConfiguration,
Request,
RequestList,
RequestState,
Session,
} from '@crawlee/puppeteer';
import { sleep } from '@crawlee/utils';
import puppeteer from 'puppeteer';
import type { HTTPResponse } from 'puppeteer';
import { runExampleComServer } from 'test/shared/_helper';
import { MemoryStorageEmulator } from 'test/shared/MemoryStorageEmulator';
import { BrowserCrawlerTest } from './basic_browser_crawler';
describe('BrowserCrawler', () => {
let prevEnvHeadless: string;
let logLevel: number;
const localStorageEmulator = new MemoryStorageEmulator();
let puppeteerPlugin: PuppeteerPlugin;
let serverAddress = 'path_to_url
let port: number;
let server: Server;
beforeAll(async () => {
prevEnvHeadless = process.env.CRAWLEE_HEADLESS;
process.env.CRAWLEE_HEADLESS = '1';
logLevel = log.getLevel();
log.setLevel(log.LEVELS.ERROR);
[server, port] = await runExampleComServer();
serverAddress += port;
});
beforeEach(async () => {
await localStorageEmulator.init();
puppeteerPlugin = new PuppeteerPlugin(puppeteer);
});
afterEach(async () => {
puppeteerPlugin = null;
});
afterAll(async () => {
await localStorageEmulator.destroy();
log.setLevel(logLevel);
process.env.CRAWLEE_HEADLESS = prevEnvHeadless;
server.close();
});
test('should work', async () => {
const sources = [
{ url: `${serverAddress}/?q=1` },
{ url: `${serverAddress}/?q=2` },
{ url: `${serverAddress}/?q=3` },
{ url: `${serverAddress}/?q=4` },
{ url: `${serverAddress}/?q=5` },
{ url: `${serverAddress}/?q=6` },
];
const sourcesCopy = JSON.parse(JSON.stringify(sources));
const processed: Request[] = [];
const failed: Request[] = [];
const requestList = await RequestList.open(null, sources);
const requestHandler: PuppeteerRequestHandler = async ({ page, request, response }) => {
await page.waitForSelector('title');
expect(response.status()).toBe(200);
request.userData.title = await page.title();
processed.push(request);
};
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
minConcurrency: 1,
maxConcurrency: 1,
requestHandler,
failedRequestHandler: async ({ request }) => {
failed.push(request);
},
});
await browserCrawler.run();
expect(browserCrawler.autoscaledPool.minConcurrency).toBe(1);
expect(processed).toHaveLength(6);
expect(failed).toHaveLength(0);
processed.forEach((request, id) => {
expect(request.url).toEqual(sourcesCopy[id].url);
expect(request.userData.title).toBe('Example Domain');
});
});
test('should teardown browser pool', async () => {
const requestList = await RequestList.open({
sources: [{ url: 'path_to_url }],
});
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: true,
requestHandler: async () => {},
maxRequestRetries: 1,
});
vitest.spyOn(browserCrawler.browserPool, 'destroy');
await browserCrawler.run();
expect(browserCrawler.browserPool.destroy).toBeCalled();
});
test('should retire session after TimeoutError', async () => {
const requestList = await RequestList.open({
sources: [{ url: 'path_to_url }],
});
class TimeoutError extends Error {}
let sessionGoto: Session;
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: PuppeteerCrawlingContext,
): Promise<HTTPResponse | null | undefined> {
vitest.spyOn(ctx.session, 'markBad');
sessionGoto = ctx.session;
throw new TimeoutError();
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: true,
requestHandler: async () => {},
maxRequestRetries: 1,
});
await browserCrawler.run();
expect(sessionGoto.markBad).toBeCalled();
});
test('should evaluate preNavigationHooks', async () => {
const requestList = await RequestList.open({
sources: [{ url: 'path_to_url }],
});
let isEvaluated = false;
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: PuppeteerCrawlingContext,
gotoOptions: PuppeteerGoToOptions,
): Promise<HTTPResponse | null | undefined> {
isEvaluated = ctx.hookFinished as boolean;
return ctx.page.goto(ctx.request.url, gotoOptions);
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: true,
requestHandler: async () => {},
maxRequestRetries: 0,
preNavigationHooks: [
async (crawlingContext) => {
await sleep(10);
crawlingContext.hookFinished = true;
},
],
});
await browserCrawler.run();
expect(isEvaluated).toBeTruthy();
});
test('should evaluate postNavigationHooks', async () => {
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
let isEvaluated = false;
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: true,
requestHandler: async ({ hookFinished }) => {
isEvaluated = hookFinished as boolean;
},
maxRequestRetries: 0,
postNavigationHooks: [
async (crawlingContext) => {
await sleep(10);
crawlingContext.hookFinished = true;
},
],
});
await browserCrawler.run();
expect(isEvaluated).toBeTruthy();
});
test('errorHandler has open page', async () => {
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
const result: string[] = [];
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async (ctx) => {
throw new Error('Test error');
},
maxRequestRetries: 1,
errorHandler: async (ctx, error) => {
result.push(await ctx.page.evaluate(() => window.location.origin));
},
});
await browserCrawler.run();
expect(result.length).toBe(1);
expect(result[0]).toBe(serverAddress);
});
test('should correctly track request.state', async () => {
const sources = [{ url: `${serverAddress}/?q=1` }];
const requestList = await RequestList.open(null, sources);
const requestStates: RequestState[] = [];
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
preNavigationHooks: [
async ({ request }) => {
requestStates.push(request.state);
},
],
postNavigationHooks: [
async ({ request }) => {
requestStates.push(request.state);
},
],
requestHandler: async ({ request }) => {
requestStates.push(request.state);
throw new Error('Error');
},
maxRequestRetries: 1,
errorHandler: async ({ request }) => {
requestStates.push(request.state);
},
});
await browserCrawler.run();
expect(requestStates).toEqual([
RequestState.BEFORE_NAV,
RequestState.AFTER_NAV,
RequestState.REQUEST_HANDLER,
RequestState.ERROR_HANDLER,
RequestState.BEFORE_NAV,
RequestState.AFTER_NAV,
RequestState.REQUEST_HANDLER,
]);
});
test('should allow modifying gotoOptions by pre navigation hooks', async () => {
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
let optionsGoto: PuppeteerGoToOptions;
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: PuppeteerCrawlingContext,
gotoOptions: PuppeteerGoToOptions,
): Promise<HTTPResponse | null | undefined> {
optionsGoto = gotoOptions;
return ctx.page.goto(ctx.request.url, gotoOptions);
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: true,
requestHandler: async () => {},
maxRequestRetries: 0,
preNavigationHooks: [
async (_crawlingContext, gotoOptions) => {
gotoOptions.timeout = 60000;
},
],
});
await browserCrawler.run();
expect(optionsGoto.timeout).toEqual(60000);
});
test('should ignore errors in Page.close()', async () => {
for (let i = 0; i < 2; i++) {
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
let failedCalled = false;
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async ({ page }) => {
page.close = async () => {
if (i === 0) {
throw new Error();
} else {
return Promise.reject(new Error());
}
};
return Promise.resolve();
},
failedRequestHandler: async () => {
failedCalled = true;
},
});
await browserCrawler.run();
expect(failedCalled).toBe(false);
}
});
test('should respect the requestHandlerTimeoutSecs option', async () => {
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
const callSpy = vitest.fn();
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async () => {
setTimeout(() => callSpy('good'), 300);
setTimeout(() => callSpy('bad'), 1500);
await new Promise(() => {});
},
requestHandlerTimeoutSecs: 0.5,
maxRequestRetries: 0,
});
await browserCrawler.run();
expect(callSpy).toBeCalledTimes(1);
expect(callSpy).toBeCalledWith('good');
});
test('should not throw without SessionPool', async () => {
const requestList = await RequestList.open({
sources: [{ url: 'path_to_url }],
});
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: false,
requestHandler: async () => {},
});
expect(browserCrawler).toBeDefined();
});
test('should correctly set session pool options', async () => {
const requestList = await RequestList.open({
sources: [{ url: 'path_to_url }],
});
const crawler = new BrowserCrawlerTest({
requestList,
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
useSessionPool: true,
persistCookiesPerSession: false,
sessionPoolOptions: {
sessionOptions: {
maxUsageCount: 1,
},
persistStateKeyValueStoreId: 'abc',
},
requestHandler: async () => {},
});
// @ts-expect-error Accessing private prop
expect(crawler.sessionPoolOptions.sessionOptions.maxUsageCount).toBe(1);
// @ts-expect-error Accessing private prop
expect(crawler.sessionPoolOptions.persistStateKeyValueStoreId).toBe('abc');
});
test.skip('should persist cookies per session', async () => {
const name = `list-${Math.random()}`;
const requestList = await RequestList.open({
persistStateKey: name,
persistRequestsKey: name,
sources: [
{ url: 'path_to_url },
{ url: 'path_to_url },
{ url: 'path_to_url },
{ url: 'path_to_url },
],
});
const goToPageSessions = [];
const loadedCookies: string[] = [];
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: true,
persistCookiesPerSession: true,
requestHandler: async ({ session, request }) => {
loadedCookies.push(session.getCookieString(request.url));
return Promise.resolve();
},
preNavigationHooks: [
async ({ session, page }) => {
await page.setCookie({
name: 'TEST',
value: '12321312312',
domain: 'example.com',
expires: Date.now() + 100000,
});
goToPageSessions.push(session);
},
],
});
await browserCrawler.run();
expect(loadedCookies).toHaveLength(4);
loadedCookies.forEach((cookie) => {
// TODO this test is flaky in CI and we need some more info to debug why.
if (cookie !== 'TEST=12321312312') {
// for some reason, the CI failures report the first cookie to be just empty string
// eslint-disable-next-line no-console
console.log('loadedCookies:');
// eslint-disable-next-line no-console
console.dir(loadedCookies);
}
expect(cookie).toEqual('TEST=12321312312');
});
});
test('should throw on "blocked" status codes', async () => {
const baseUrl = 'path_to_url
const sources = BLOCKED_STATUS_CODES.map((statusCode) => {
return {
url: baseUrl + statusCode,
userData: { statusCode },
};
});
const requestList = await RequestList.open(null, sources);
let called = false;
const failedRequests: Request[] = [];
const crawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: true,
persistCookiesPerSession: false,
maxRequestRetries: 0,
requestHandler: async () => {
called = true;
},
failedRequestHandler: async ({ request }) => {
failedRequests.push(request);
},
});
// @ts-expect-error Overriding protected method
crawler._navigationHandler = async ({ request }) => {
return { status: () => request.userData.statusCode };
};
await crawler.run();
expect(failedRequests.length).toBe(3);
failedRequests.forEach((fr) => {
const [msg] = fr.errorMessages;
expect(msg).toContain(`Request blocked - received ${fr.userData.statusCode} status code.`);
});
expect(called).toBe(false);
});
test('retryOnBlocked should retry on Cloudflare challenge', async () => {
const urls = [new URL('/special/cloudflareBlocking', serverAddress).href];
const maxSessionRotations = 1;
let processed = false;
const errorMessages: string[] = [];
const crawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
retryOnBlocked: true,
maxSessionRotations,
requestHandler: async ({ page, response }) => {
processed = true;
},
failedRequestHandler: async ({ request }) => {
errorMessages.push(...request.errorMessages);
},
});
await crawler.run(urls);
expect(errorMessages).toHaveLength(urls.length * (maxSessionRotations + 1));
expect(errorMessages.every((x) => x.includes('Detected a session error, rotating session...'))).toBe(true);
expect(processed).toBe(false);
});
test('retryOnBlocked throws on "blocked" status codes', async () => {
const baseUrl = 'path_to_url
const sources = BLOCKED_STATUS_CODES.map((statusCode) => {
return {
url: baseUrl + statusCode,
userData: { statusCode },
};
});
const requestList = await RequestList.open(null, sources);
const maxSessionRotations = 1;
const errorMessages: string[] = [];
let processed = false;
const crawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
retryOnBlocked: true,
maxSessionRotations,
requestHandler: async () => {
processed = true;
},
failedRequestHandler: async ({ request }) => {
errorMessages.push(...request.errorMessages);
},
});
// @ts-expect-error Overriding protected method
crawler._navigationHandler = async ({ request }) => {
return { status: () => request.userData.statusCode };
};
await crawler.run();
expect(errorMessages.length).toBe(sources.length * (maxSessionRotations + 1));
expect(errorMessages.every((x) => x.includes('Detected a session error, rotating session...'))).toBe(true);
expect(processed).toBe(false);
});
test('should throw on "blocked" status codes (retire session)', async () => {
const baseUrl = 'path_to_url
const sources = BLOCKED_STATUS_CODES.map((statusCode) => {
return {
url: baseUrl + statusCode,
userData: { statusCode },
};
});
const requestList = await RequestList.open(null, sources);
let called = false;
const failedRequests: Request[] = [];
const crawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: true,
persistCookiesPerSession: false,
maxRequestRetries: 0,
requestHandler: async () => {
called = true;
},
failedRequestHandler: async ({ request }) => {
failedRequests.push(request);
},
});
// @ts-expect-error Overriding protected method
crawler._navigationHandler = async ({ request }) => {
return { status: () => request.userData.statusCode };
};
await crawler.run();
expect(failedRequests.length).toBe(3);
failedRequests.forEach((fr) => {
const [msg] = fr.errorMessages;
expect(msg).toContain(`Request blocked - received ${fr.userData.statusCode} status code.`);
});
expect(called).toBe(false);
});
test('should retire browser with session', async () => {
const requestList = await RequestList.open({
sources: [{ url: 'path_to_url }],
});
let resolve: (value?: unknown) => void;
const retirementPromise = new Promise((r) => {
resolve = r;
});
let called = false;
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: PuppeteerCrawlingContext,
): Promise<HTTPResponse | null | undefined> {
ctx.crawler.browserPool.on(BROWSER_POOL_EVENTS.BROWSER_RETIRED, () => {
resolve();
called = true;
});
ctx.session.retire();
return ctx.page.goto(ctx.request.url);
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
useSessionPool: true,
requestHandler: async () => {
await retirementPromise;
},
maxRequestRetries: 1,
});
await browserCrawler.run();
expect(called).toBeTruthy();
});
test('should allow using fingerprints from browser pool', async () => {
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
useFingerprints: true,
fingerprintOptions: {
fingerprintGeneratorOptions: {
operatingSystems: [OperatingSystemsName.windows],
},
},
},
requestList,
useSessionPool: false,
requestHandler: async ({ browserController }) => {
expect(browserController.launchContext.fingerprint).toBeDefined();
},
});
await browserCrawler.run();
expect.hasAssertions();
});
describe('proxy', () => {
let requestList: RequestList;
beforeEach(async () => {
requestList = await RequestList.open({
sources: [
{ url: 'path_to_url },
{ url: 'path_to_url },
{ url: 'path_to_url },
{ url: 'path_to_url },
],
});
});
afterEach(() => {
requestList = null;
});
// TODO move to actor sdk tests before splitting the repos
// test('browser should launch with correct proxyUrl', async () => {
// process.env[ENV_VARS.PROXY_PASSWORD] = 'abc123';
// const status = { connected: true };
// const fakeCall = async () => {
// return { body: status } as never;
// };
//
// // @ts-expect-error FIXME
// const stub = gotScrapingSpy.mockImplementation(fakeCall);
// const proxyConfiguration = await Actor.createProxyConfiguration();
// const generatedProxyUrl = new URL(await proxyConfiguration.newUrl()).href.slice(0, -1);
// let browserProxy;
//
// const browserCrawler = new BrowserCrawlerTest({
// browserPoolOptions: {
// browserPlugins: [puppeteerPlugin],
// postLaunchHooks: [(pageId, browserController) => {
// browserProxy = browserController.launchContext.proxyUrl;
// }],
// },
// useSessionPool: false,
// persistCookiesPerSession: false,
// navigationTimeoutSecs: 1,
// requestList,
// maxRequestsPerCrawl: 1,
// maxRequestRetries: 0,
// requestHandler: async () => {},
// proxyConfiguration,
// });
// await browserCrawler.run();
// delete process.env[ENV_VARS.PROXY_PASSWORD];
//
// expect(browserProxy).toEqual(generatedProxyUrl);
//
// stub.mockClear();
// });
// TODO move to actor sdk tests before splitting the repos
// test('requestHandler should expose the proxyInfo object with sessions correctly', async () => {
// process.env[ENV_VARS.PROXY_PASSWORD] = 'abc123';
// const status = { connected: true };
// const fakeCall = async () => {
// return { body: status } as never;
// };
//
// // @ts-expect-error FIXME
// const stub = gotScrapingSpy.mockImplementation(fakeCall);
//
// const proxyConfiguration = await Actor.createProxyConfiguration();
// const proxies: ProxyInfo[] = [];
// const sessions: Session[] = [];
// const requestHandler = async ({ session, proxyInfo }: BrowserCrawlingContext) => {
// proxies.push(proxyInfo);
// sessions.push(session);
// };
//
// const browserCrawler = new BrowserCrawlerTest({
// browserPoolOptions: {
// browserPlugins: [puppeteerPlugin],
// },
// requestList,
// requestHandler,
//
// proxyConfiguration,
// useSessionPool: true,
// sessionPoolOptions: {
// maxPoolSize: 1,
// },
// });
//
// await browserCrawler.run();
//
// expect(proxies[0].sessionId).toEqual(sessions[0].id);
// expect(proxies[1].sessionId).toEqual(sessions[1].id);
// expect(proxies[2].sessionId).toEqual(sessions[2].id);
// expect(proxies[3].sessionId).toEqual(sessions[3].id);
//
// delete process.env[ENV_VARS.PROXY_PASSWORD];
// stub.mockClear();
// });
test('browser should launch with rotated custom proxy', async () => {
process.env[ENV_VARS.PROXY_PASSWORD] = 'abc123';
const proxyConfiguration = new ProxyConfiguration({
proxyUrls: ['path_to_url 'path_to_url 'path_to_url
});
const browserProxies: string[] = [];
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
maxOpenPagesPerBrowser: 1,
retireBrowserAfterPageCount: 1,
},
requestList,
requestHandler: async () => {},
proxyConfiguration,
maxRequestRetries: 0,
maxConcurrency: 1,
});
browserCrawler.browserPool.postLaunchHooks.push((_pageId, browserController) => {
browserProxies.push(browserController.launchContext.proxyUrl);
});
await browserCrawler.run();
// @ts-expect-error Accessing private property
const proxiesToUse = proxyConfiguration.proxyUrls;
for (const proxyUrl of proxiesToUse) {
expect(browserProxies.includes(new URL(proxyUrl).href.slice(0, -1))).toBeTruthy();
}
delete process.env[ENV_VARS.PROXY_PASSWORD];
});
test('proxy rotation on error works as expected', async () => {
const goodProxyUrl = 'path_to_url
const proxyConfiguration = new ProxyConfiguration({
proxyUrls: ['path_to_url 'path_to_url goodProxyUrl],
});
const requestHandler = vitest.fn();
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: PuppeteerCrawlingContext,
): Promise<HTTPResponse | null | undefined> {
const { session } = ctx;
const proxyInfo = await this.proxyConfiguration.newProxyInfo(session?.id);
if (proxyInfo.url !== goodProxyUrl) {
throw new Error('ERR_PROXY_CONNECTION_FAILED');
}
return null;
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
maxRequestRetries: 0,
maxConcurrency: 1,
useSessionPool: true,
proxyConfiguration,
requestHandler,
});
await expect(browserCrawler.run()).resolves.not.toThrow();
expect(requestHandler).toHaveBeenCalledTimes(requestList.length());
});
test('proxy rotation on error respects maxSessionRotations, calls failedRequestHandler', async () => {
const proxyConfiguration = new ProxyConfiguration({
proxyUrls: ['path_to_url 'path_to_url
});
const failedRequestHandler = vitest.fn();
/**
* The first increment is the base case when the proxy is retrieved for the first time.
*/
let numberOfRotations = -requestList.length();
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: PuppeteerCrawlingContext,
): Promise<HTTPResponse | null | undefined> {
const { session } = ctx;
const proxyInfo = await this.proxyConfiguration.newProxyInfo(session?.id);
numberOfRotations++;
if (proxyInfo.url.includes('localhost')) {
throw new Error('ERR_PROXY_CONNECTION_FAILED');
}
return null;
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
maxSessionRotations: 5,
maxConcurrency: 1,
proxyConfiguration,
requestHandler: async () => {},
failedRequestHandler,
});
await browserCrawler.run();
expect(failedRequestHandler).toBeCalledTimes(requestList.length());
expect(numberOfRotations).toBe(requestList.length() * 5);
});
test('proxy rotation logs the original proxy error', async () => {
const proxyConfiguration = new ProxyConfiguration({ proxyUrls: ['path_to_url });
const proxyError =
'Proxy responded with 400 - Bad request. Also, this error message contains some useful payload.';
const crawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: PuppeteerCrawlingContext,
): Promise<HTTPResponse | null | undefined> {
const { session } = ctx;
const proxyInfo = await this.proxyConfiguration.newProxyInfo(session?.id);
if (proxyInfo.url.includes('localhost')) {
throw new Error(proxyError);
}
return null;
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
maxSessionRotations: 1,
maxConcurrency: 1,
proxyConfiguration,
requestHandler: async () => {},
});
const spy = vitest.spyOn((crawler as any).log, 'warning' as any).mockImplementation(() => {});
await crawler.run([serverAddress]);
expect(spy).toBeCalled();
expect(spy.mock.calls[0][0]).toEqual(
'When using RequestList and RequestQueue at the same time, you should instantiate both explicitly and provide them in the crawler options, to ensure correctly handled restarts of the crawler.',
);
expect(spy.mock.calls[1][0]).toEqual(expect.stringContaining(proxyError));
});
});
describe('Crawling context', () => {
const sources = ['path_to_url
let requestList: RequestList;
let actualLogLevel: number;
beforeEach(async () => {
actualLogLevel = log.getLevel();
log.setLevel(log.LEVELS.OFF);
requestList = await RequestList.open(null, sources.slice());
});
afterAll(() => {
log.setLevel(actualLogLevel);
});
test('uses correct crawling context', async () => {
let prepareCrawlingContext: PuppeteerCrawlingContext;
const gotoFunction = async (crawlingContext: PuppeteerCrawlingContext) => {
prepareCrawlingContext = crawlingContext;
expect(crawlingContext.request).toBeInstanceOf(Request);
expect(crawlingContext.crawler.autoscaledPool).toBeInstanceOf(AutoscaledPool);
expect(crawlingContext.session).toBeInstanceOf(Session);
expect(typeof crawlingContext.page).toBe('object');
};
const requestHandler = async (crawlingContext: PuppeteerCrawlingContext) => {
expect(crawlingContext === prepareCrawlingContext).toEqual(true);
expect(crawlingContext.request).toBeInstanceOf(Request);
expect(crawlingContext.crawler.autoscaledPool).toBeInstanceOf(AutoscaledPool);
expect(crawlingContext.session).toBeInstanceOf(Session);
expect(typeof crawlingContext.page).toBe('object');
expect(crawlingContext.crawler).toBeInstanceOf(BrowserCrawlerTest);
expect(crawlingContext.hasOwnProperty('response')).toBe(true);
throw new Error('some error');
};
const failedRequestHandler = async (crawlingContext: PuppeteerCrawlingContext, error: Error) => {
expect(crawlingContext).toBe(prepareCrawlingContext);
expect(crawlingContext.request).toBeInstanceOf(Request);
expect(crawlingContext.crawler.autoscaledPool).toBeInstanceOf(AutoscaledPool);
expect(crawlingContext.session).toBeInstanceOf(Session);
expect(typeof crawlingContext.page).toBe('object');
expect(crawlingContext.crawler).toBeInstanceOf(BrowserCrawlerTest);
expect(crawlingContext.crawler.browserPool).toBeInstanceOf(BrowserPool);
expect(crawlingContext.hasOwnProperty('response')).toBe(true);
expect(crawlingContext.error).toBeInstanceOf(Error);
expect(error).toBeInstanceOf(Error);
expect(error.message).toEqual('some error');
};
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
maxRequestRetries: 0,
maxConcurrency: 1,
useSessionPool: true,
requestHandler,
failedRequestHandler,
});
// @ts-expect-error Overriding protected method
browserCrawler._navigationHandler = gotoFunction;
await browserCrawler.run();
});
});
test("enqueueLinks() should skip links that don't match the strategy post redirect", async () => {
const succeeded: string[] = [];
const crawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
maxConcurrency: 1,
maxRequestRetries: 0,
requestHandler: async ({ page, enqueueLinks }) => {
succeeded.push(await page.title());
await enqueueLinks({ strategy: EnqueueStrategy.SameOrigin });
},
});
await crawler.run([`${serverAddress}/special/redirect`]);
expect(succeeded).toHaveLength(1);
expect(succeeded[0]).toEqual('Redirecting outside');
});
});
``` | /content/code_sandbox/test/core/crawlers/browser_crawler.test.ts | xml | 2016-08-26T18:35:03 | 2024-08-16T16:40:08 | crawlee | apify/crawlee | 14,153 | 7,412 |
```xml
/** @jsx jsx */
import { jsx } from 'slate-hyperscript'
export const input = (
<element>
<text>word</text>
</element>
)
export const output = {
children: [
{
text: 'word',
},
],
}
``` | /content/code_sandbox/packages/slate-hyperscript/test/fixtures/element-text-string.tsx | xml | 2016-06-18T01:52:42 | 2024-08-16T18:43:42 | slate | ianstormtaylor/slate | 29,492 | 63 |
```xml
import { QueryResult } from "../../query-runner/QueryResult"
import { QueryRunner } from "../../query-runner/QueryRunner"
import { ObjectLiteral } from "../../common/ObjectLiteral"
import { TransactionNotStartedError } from "../../error/TransactionNotStartedError"
import { TableColumn } from "../../schema-builder/table/TableColumn"
import { Table } from "../../schema-builder/table/Table"
import { TableForeignKey } from "../../schema-builder/table/TableForeignKey"
import { TableIndex } from "../../schema-builder/table/TableIndex"
import { QueryRunnerAlreadyReleasedError } from "../../error/QueryRunnerAlreadyReleasedError"
import { View } from "../../schema-builder/view/View"
import { Query } from "../Query"
import { AuroraMysqlDriver } from "./AuroraMysqlDriver"
import { ReadStream } from "../../platform/PlatformTools"
import { OrmUtils } from "../../util/OrmUtils"
import { TableIndexOptions } from "../../schema-builder/options/TableIndexOptions"
import { TableUnique } from "../../schema-builder/table/TableUnique"
import { BaseQueryRunner } from "../../query-runner/BaseQueryRunner"
import { Broadcaster } from "../../subscriber/Broadcaster"
import { ColumnType } from "../types/ColumnTypes"
import { TableCheck } from "../../schema-builder/table/TableCheck"
import { IsolationLevel } from "../types/IsolationLevel"
import { TableExclusion } from "../../schema-builder/table/TableExclusion"
import { TypeORMError } from "../../error"
import { MetadataTableType } from "../types/MetadataTableType"
import { InstanceChecker } from "../../util/InstanceChecker"
/**
* Runs queries on a single mysql database connection.
*/
export class AuroraMysqlQueryRunner
extends BaseQueryRunner
implements QueryRunner
{
// your_sha256_hash---------
// Public Implemented Properties
// your_sha256_hash---------
/**
* Database driver used by connection.
*/
driver: AuroraMysqlDriver
protected client: any
// your_sha256_hash---------
// Protected Properties
// your_sha256_hash---------
/**
* Promise used to obtain a database connection from a pool for a first time.
*/
protected databaseConnectionPromise: Promise<any>
// your_sha256_hash---------
// Constructor
// your_sha256_hash---------
constructor(driver: AuroraMysqlDriver, client: any) {
super()
this.driver = driver
this.connection = driver.connection
this.client = client
this.broadcaster = new Broadcaster(this)
}
// your_sha256_hash---------
// Public Methods
// your_sha256_hash---------
/**
* Creates/uses database connection from the connection pool to perform further operations.
* Returns obtained database connection.
*/
async connect(): Promise<any> {
return {}
}
/**
* Releases used database connection.
* You cannot use query runner methods once its released.
*/
release(): Promise<void> {
this.isReleased = true
if (this.databaseConnection) this.databaseConnection.release()
return Promise.resolve()
}
/**
* Starts transaction on the current connection.
*/
async startTransaction(isolationLevel?: IsolationLevel): Promise<void> {
this.isTransactionActive = true
try {
await this.broadcaster.broadcast("BeforeTransactionStart")
} catch (err) {
this.isTransactionActive = false
throw err
}
if (this.transactionDepth === 0) {
this.transactionDepth += 1
await this.client.startTransaction()
} else {
this.transactionDepth += 1
await this.query(`SAVEPOINT typeorm_${this.transactionDepth - 1}`)
}
await this.broadcaster.broadcast("AfterTransactionStart")
}
/**
* Commits transaction.
* Error will be thrown if transaction was not started.
*/
async commitTransaction(): Promise<void> {
if (!this.isTransactionActive) throw new TransactionNotStartedError()
await this.broadcaster.broadcast("BeforeTransactionCommit")
if (this.transactionDepth > 1) {
this.transactionDepth -= 1
await this.query(
`RELEASE SAVEPOINT typeorm_${this.transactionDepth}`,
)
} else {
this.transactionDepth -= 1
await this.client.commitTransaction()
this.isTransactionActive = false
}
await this.broadcaster.broadcast("AfterTransactionCommit")
}
/**
* Rollbacks transaction.
* Error will be thrown if transaction was not started.
*/
async rollbackTransaction(): Promise<void> {
if (!this.isTransactionActive) throw new TransactionNotStartedError()
await this.broadcaster.broadcast("BeforeTransactionRollback")
if (this.transactionDepth > 1) {
this.transactionDepth -= 1
await this.query(
`ROLLBACK TO SAVEPOINT typeorm_${this.transactionDepth}`,
)
} else {
this.transactionDepth -= 1
await this.client.rollbackTransaction()
this.isTransactionActive = false
}
await this.broadcaster.broadcast("AfterTransactionRollback")
}
/**
* Executes a raw SQL query.
*/
async query(
query: string,
parameters?: any[],
useStructuredResult = false,
): Promise<any> {
if (this.isReleased) throw new QueryRunnerAlreadyReleasedError()
const raw = await this.client.query(query, parameters)
const result = new QueryResult()
result.raw = raw
if (raw?.hasOwnProperty("records") && Array.isArray(raw.records)) {
result.records = raw.records
}
if (raw?.hasOwnProperty("numberOfRecordsUpdated")) {
result.affected = raw.numberOfRecordsUpdated
}
if (!useStructuredResult) {
return result.raw
}
return result
}
/**
* Returns raw data stream.
*/
stream(
query: string,
parameters?: any[],
onEnd?: Function,
onError?: Function,
): Promise<ReadStream> {
if (this.isReleased) throw new QueryRunnerAlreadyReleasedError()
return new Promise(async (ok, fail) => {
try {
const databaseConnection = await this.connect()
const stream = databaseConnection.query(query, parameters)
if (onEnd) stream.on("end", onEnd)
if (onError) stream.on("error", onError)
ok(stream)
} catch (err) {
fail(err)
}
})
}
/**
* Returns all available database names including system databases.
*/
async getDatabases(): Promise<string[]> {
return Promise.resolve([])
}
/**
* Returns all available schema names including system schemas.
* If database parameter specified, returns schemas of that database.
*/
async getSchemas(database?: string): Promise<string[]> {
throw new TypeORMError(`MySql driver does not support table schemas`)
}
/**
* Checks if database with the given name exist.
*/
async hasDatabase(database: string): Promise<boolean> {
const result = await this.query(
`SELECT * FROM \`INFORMATION_SCHEMA\`.\`SCHEMATA\` WHERE \`SCHEMA_NAME\` = '${database}'`,
)
return result.length ? true : false
}
/**
* Loads currently using database
*/
async getCurrentDatabase(): Promise<string> {
const query = await this.query(`SELECT DATABASE() AS \`db_name\``)
return query[0]["db_name"]
}
/**
* Checks if schema with the given name exist.
*/
async hasSchema(schema: string): Promise<boolean> {
throw new TypeORMError(`MySql driver does not support table schemas`)
}
/**
* Loads currently using database schema
*/
async getCurrentSchema(): Promise<string> {
const query = await this.query(`SELECT SCHEMA() AS \`schema_name\``)
return query[0]["schema_name"]
}
/**
* Checks if table with the given name exist in the database.
*/
async hasTable(tableOrName: Table | string): Promise<boolean> {
const parsedTableName = this.driver.parseTableName(tableOrName)
const sql = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = '${parsedTableName.database}' AND \`TABLE_NAME\` = '${parsedTableName.tableName}'`
const result = await this.query(sql)
return result.length ? true : false
}
/**
* Checks if column with the given name exist in the given table.
*/
async hasColumn(
tableOrName: Table | string,
column: TableColumn | string,
): Promise<boolean> {
const parsedTableName = this.driver.parseTableName(tableOrName)
const columnName = InstanceChecker.isTableColumn(column)
? column.name
: column
const sql = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = '${parsedTableName.database}' AND \`TABLE_NAME\` = '${parsedTableName.tableName}' AND \`COLUMN_NAME\` = '${columnName}'`
const result = await this.query(sql)
return result.length ? true : false
}
/**
* Creates a new database.
*/
async createDatabase(
database: string,
ifNotExist?: boolean,
): Promise<void> {
const up = ifNotExist
? `CREATE DATABASE IF NOT EXISTS \`${database}\``
: `CREATE DATABASE \`${database}\``
const down = `DROP DATABASE \`${database}\``
await this.executeQueries(new Query(up), new Query(down))
}
/**
* Drops database.
*/
async dropDatabase(database: string, ifExist?: boolean): Promise<void> {
const up = ifExist
? `DROP DATABASE IF EXISTS \`${database}\``
: `DROP DATABASE \`${database}\``
const down = `CREATE DATABASE \`${database}\``
await this.executeQueries(new Query(up), new Query(down))
}
/**
* Creates a new table schema.
*/
async createSchema(
schemaPath: string,
ifNotExist?: boolean,
): Promise<void> {
throw new TypeORMError(
`Schema create queries are not supported by MySql driver.`,
)
}
/**
* Drops table schema.
*/
async dropSchema(schemaPath: string, ifExist?: boolean): Promise<void> {
throw new TypeORMError(
`Schema drop queries are not supported by MySql driver.`,
)
}
/**
* Creates a new table.
*/
async createTable(
table: Table,
ifNotExist: boolean = false,
createForeignKeys: boolean = true,
): Promise<void> {
if (ifNotExist) {
const isTableExist = await this.hasTable(table)
if (isTableExist) return Promise.resolve()
}
const upQueries: Query[] = []
const downQueries: Query[] = []
upQueries.push(this.createTableSql(table, createForeignKeys))
downQueries.push(this.dropTableSql(table))
// we must first drop indices, than drop foreign keys, because drop queries runs in reversed order
// and foreign keys will be dropped first as indices. This order is very important, because we can't drop index
// if it related to the foreign key.
// createTable does not need separate method to create indices, because it create indices in the same query with table creation.
table.indices.forEach((index) =>
downQueries.push(this.dropIndexSql(table, index)),
)
// if createForeignKeys is true, we must drop created foreign keys in down query.
// createTable does not need separate method to create foreign keys, because it create fk's in the same query with table creation.
if (createForeignKeys)
table.foreignKeys.forEach((foreignKey) =>
downQueries.push(this.dropForeignKeySql(table, foreignKey)),
)
return this.executeQueries(upQueries, downQueries)
}
/**
* Drop the table.
*/
async dropTable(
target: Table | string,
ifExist?: boolean,
dropForeignKeys: boolean = true,
): Promise<void> {
// It needs because if table does not exist and dropForeignKeys or dropIndices is true, we don't need
// to perform drop queries for foreign keys and indices.
if (ifExist) {
const isTableExist = await this.hasTable(target)
if (!isTableExist) return Promise.resolve()
}
// if dropTable called with dropForeignKeys = true, we must create foreign keys in down query.
const createForeignKeys: boolean = dropForeignKeys
const tablePath = this.getTablePath(target)
const table = await this.getCachedTable(tablePath)
const upQueries: Query[] = []
const downQueries: Query[] = []
if (dropForeignKeys)
table.foreignKeys.forEach((foreignKey) =>
upQueries.push(this.dropForeignKeySql(table, foreignKey)),
)
table.indices.forEach((index) =>
upQueries.push(this.dropIndexSql(table, index)),
)
upQueries.push(this.dropTableSql(table))
downQueries.push(this.createTableSql(table, createForeignKeys))
await this.executeQueries(upQueries, downQueries)
}
/**
* Creates a new view.
*/
async createView(
view: View,
syncWithMetadata: boolean = false,
): Promise<void> {
const upQueries: Query[] = []
const downQueries: Query[] = []
upQueries.push(this.createViewSql(view))
if (syncWithMetadata)
upQueries.push(await this.insertViewDefinitionSql(view))
downQueries.push(this.dropViewSql(view))
if (syncWithMetadata)
downQueries.push(await this.deleteViewDefinitionSql(view))
await this.executeQueries(upQueries, downQueries)
}
/**
* Drops the view.
*/
async dropView(target: View | string): Promise<void> {
const viewName = InstanceChecker.isView(target) ? target.name : target
const view = await this.getCachedView(viewName)
const upQueries: Query[] = []
const downQueries: Query[] = []
upQueries.push(await this.deleteViewDefinitionSql(view))
upQueries.push(this.dropViewSql(view))
downQueries.push(await this.insertViewDefinitionSql(view))
downQueries.push(this.createViewSql(view))
await this.executeQueries(upQueries, downQueries)
}
/**
* Renames a table.
*/
async renameTable(
oldTableOrName: Table | string,
newTableName: string,
): Promise<void> {
const upQueries: Query[] = []
const downQueries: Query[] = []
const oldTable = InstanceChecker.isTable(oldTableOrName)
? oldTableOrName
: await this.getCachedTable(oldTableOrName)
const newTable = oldTable.clone()
const { database } = this.driver.parseTableName(oldTable)
newTable.name = database ? `${database}.${newTableName}` : newTableName
// rename table
upQueries.push(
new Query(
`RENAME TABLE ${this.escapePath(oldTable)} TO ${this.escapePath(
newTable,
)}`,
),
)
downQueries.push(
new Query(
`RENAME TABLE ${this.escapePath(newTable)} TO ${this.escapePath(
oldTable,
)}`,
),
)
// rename index constraints
newTable.indices.forEach((index) => {
// build new constraint name
const columnNames = index.columnNames
.map((column) => `\`${column}\``)
.join(", ")
const newIndexName = this.connection.namingStrategy.indexName(
newTable,
index.columnNames,
index.where,
)
// build queries
let indexType = ""
if (index.isUnique) indexType += "UNIQUE "
if (index.isSpatial) indexType += "SPATIAL "
if (index.isFulltext) indexType += "FULLTEXT "
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(newTable)} DROP INDEX \`${
index.name
}\`, ADD ${indexType}INDEX \`${newIndexName}\` (${columnNames})`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
newTable,
)} DROP INDEX \`${newIndexName}\`, ADD ${indexType}INDEX \`${
index.name
}\` (${columnNames})`,
),
)
// replace constraint name
index.name = newIndexName
})
// rename foreign key constraint
newTable.foreignKeys.forEach((foreignKey) => {
// build new constraint name
const columnNames = foreignKey.columnNames
.map((column) => `\`${column}\``)
.join(", ")
const referencedColumnNames = foreignKey.referencedColumnNames
.map((column) => `\`${column}\``)
.join(",")
const newForeignKeyName =
this.connection.namingStrategy.foreignKeyName(
newTable,
foreignKey.columnNames,
)
// build queries
let up =
`ALTER TABLE ${this.escapePath(newTable)} DROP FOREIGN KEY \`${
foreignKey.name
}\`, ADD CONSTRAINT \`${newForeignKeyName}\` FOREIGN KEY (${columnNames}) ` +
`REFERENCES ${this.escapePath(
this.getTablePath(foreignKey),
)}(${referencedColumnNames})`
if (foreignKey.onDelete) up += ` ON DELETE ${foreignKey.onDelete}`
if (foreignKey.onUpdate) up += ` ON UPDATE ${foreignKey.onUpdate}`
let down =
`ALTER TABLE ${this.escapePath(
newTable,
)} DROP FOREIGN KEY \`${newForeignKeyName}\`, ADD CONSTRAINT \`${
foreignKey.name
}\` FOREIGN KEY (${columnNames}) ` +
`REFERENCES ${this.escapePath(
this.getTablePath(foreignKey),
)}(${referencedColumnNames})`
if (foreignKey.onDelete) down += ` ON DELETE ${foreignKey.onDelete}`
if (foreignKey.onUpdate) down += ` ON UPDATE ${foreignKey.onUpdate}`
upQueries.push(new Query(up))
downQueries.push(new Query(down))
// replace constraint name
foreignKey.name = newForeignKeyName
})
await this.executeQueries(upQueries, downQueries)
// rename old table and replace it in cached tabled;
oldTable.name = newTable.name
this.replaceCachedTable(oldTable, newTable)
}
/**
* Creates a new column from the column in the table.
*/
async addColumn(
tableOrName: Table | string,
column: TableColumn,
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
const clonedTable = table.clone()
const upQueries: Query[] = []
const downQueries: Query[] = []
const skipColumnLevelPrimary = clonedTable.primaryColumns.length > 0
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD ${this.buildCreateColumnSql(
column,
skipColumnLevelPrimary,
false,
)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} DROP COLUMN \`${
column.name
}\``,
),
)
// create or update primary key constraint
if (column.isPrimary && skipColumnLevelPrimary) {
// if we already have generated column, we must temporary drop AUTO_INCREMENT property.
const generatedColumn = clonedTable.columns.find(
(column) =>
column.isGenerated &&
column.generationStrategy === "increment",
)
if (generatedColumn) {
const nonGeneratedColumn = generatedColumn.clone()
nonGeneratedColumn.isGenerated = false
nonGeneratedColumn.generationStrategy = undefined
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
column.name
}\` ${this.buildCreateColumnSql(
nonGeneratedColumn,
true,
)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
nonGeneratedColumn.name
}\` ${this.buildCreateColumnSql(column, true)}`,
),
)
}
const primaryColumns = clonedTable.primaryColumns
let columnNames = primaryColumns
.map((column) => `\`${column.name}\``)
.join(", ")
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD PRIMARY KEY (${columnNames})`,
),
)
primaryColumns.push(column)
columnNames = primaryColumns
.map((column) => `\`${column.name}\``)
.join(", ")
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD PRIMARY KEY (${columnNames})`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`,
),
)
// if we previously dropped AUTO_INCREMENT property, we must bring it back
if (generatedColumn) {
const nonGeneratedColumn = generatedColumn.clone()
nonGeneratedColumn.isGenerated = false
nonGeneratedColumn.generationStrategy = undefined
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
nonGeneratedColumn.name
}\` ${this.buildCreateColumnSql(column, true)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
column.name
}\` ${this.buildCreateColumnSql(
nonGeneratedColumn,
true,
)}`,
),
)
}
}
// create column index
const columnIndex = clonedTable.indices.find(
(index) =>
index.columnNames.length === 1 &&
index.columnNames[0] === column.name,
)
if (columnIndex) {
upQueries.push(this.createIndexSql(table, columnIndex))
downQueries.push(this.dropIndexSql(table, columnIndex))
} else if (column.isUnique) {
const uniqueIndex = new TableIndex({
name: this.connection.namingStrategy.indexName(table, [
column.name,
]),
columnNames: [column.name],
isUnique: true,
})
clonedTable.indices.push(uniqueIndex)
clonedTable.uniques.push(
new TableUnique({
name: uniqueIndex.name,
columnNames: uniqueIndex.columnNames,
}),
)
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} ADD UNIQUE INDEX \`${
uniqueIndex.name
}\` (\`${column.name}\`)`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} DROP INDEX \`${
uniqueIndex.name
}\``,
),
)
}
await this.executeQueries(upQueries, downQueries)
clonedTable.addColumn(column)
this.replaceCachedTable(table, clonedTable)
}
/**
* Creates a new columns from the column in the table.
*/
async addColumns(
tableOrName: Table | string,
columns: TableColumn[],
): Promise<void> {
for (const column of columns) {
await this.addColumn(tableOrName, column)
}
}
/**
* Renames column in the given table.
*/
async renameColumn(
tableOrName: Table | string,
oldTableColumnOrName: TableColumn | string,
newTableColumnOrName: TableColumn | string,
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
const oldColumn = InstanceChecker.isTableColumn(oldTableColumnOrName)
? oldTableColumnOrName
: table.columns.find((c) => c.name === oldTableColumnOrName)
if (!oldColumn)
throw new TypeORMError(
`Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`,
)
let newColumn: TableColumn | undefined = undefined
if (InstanceChecker.isTableColumn(newTableColumnOrName)) {
newColumn = newTableColumnOrName
} else {
newColumn = oldColumn.clone()
newColumn.name = newTableColumnOrName
}
await this.changeColumn(table, oldColumn, newColumn)
}
/**
* Changes a column in the table.
*/
async changeColumn(
tableOrName: Table | string,
oldColumnOrName: TableColumn | string,
newColumn: TableColumn,
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
let clonedTable = table.clone()
const upQueries: Query[] = []
const downQueries: Query[] = []
const oldColumn = InstanceChecker.isTableColumn(oldColumnOrName)
? oldColumnOrName
: table.columns.find((column) => column.name === oldColumnOrName)
if (!oldColumn)
throw new TypeORMError(
`Column "${oldColumnOrName}" was not found in the "${table.name}" table.`,
)
if (
(newColumn.isGenerated !== oldColumn.isGenerated &&
newColumn.generationStrategy !== "uuid") ||
oldColumn.type !== newColumn.type ||
oldColumn.length !== newColumn.length ||
oldColumn.generatedType !== newColumn.generatedType
) {
await this.dropColumn(table, oldColumn)
await this.addColumn(table, newColumn)
// update cloned table
clonedTable = table.clone()
} else {
if (newColumn.name !== oldColumn.name) {
// We don't change any column properties, just rename it.
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
oldColumn.name
}\` \`${newColumn.name}\` ${this.buildCreateColumnSql(
oldColumn,
true,
true,
)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
newColumn.name
}\` \`${oldColumn.name}\` ${this.buildCreateColumnSql(
oldColumn,
true,
true,
)}`,
),
)
// rename index constraints
clonedTable.findColumnIndices(oldColumn).forEach((index) => {
// build new constraint name
index.columnNames.splice(
index.columnNames.indexOf(oldColumn.name),
1,
)
index.columnNames.push(newColumn.name)
const columnNames = index.columnNames
.map((column) => `\`${column}\``)
.join(", ")
const newIndexName =
this.connection.namingStrategy.indexName(
clonedTable,
index.columnNames,
index.where,
)
// build queries
let indexType = ""
if (index.isUnique) indexType += "UNIQUE "
if (index.isSpatial) indexType += "SPATIAL "
if (index.isFulltext) indexType += "FULLTEXT "
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} DROP INDEX \`${
index.name
}\`, ADD ${indexType}INDEX \`${newIndexName}\` (${columnNames})`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} DROP INDEX \`${newIndexName}\`, ADD ${indexType}INDEX \`${
index.name
}\` (${columnNames})`,
),
)
// replace constraint name
index.name = newIndexName
})
// rename foreign key constraints
clonedTable
.findColumnForeignKeys(oldColumn)
.forEach((foreignKey) => {
// build new constraint name
foreignKey.columnNames.splice(
foreignKey.columnNames.indexOf(oldColumn.name),
1,
)
foreignKey.columnNames.push(newColumn.name)
const columnNames = foreignKey.columnNames
.map((column) => `\`${column}\``)
.join(", ")
const referencedColumnNames =
foreignKey.referencedColumnNames
.map((column) => `\`${column}\``)
.join(",")
const newForeignKeyName =
this.connection.namingStrategy.foreignKeyName(
clonedTable,
foreignKey.columnNames,
)
// build queries
let up =
`ALTER TABLE ${this.escapePath(
table,
)} DROP FOREIGN KEY \`${
foreignKey.name
}\`, ADD CONSTRAINT \`${newForeignKeyName}\` FOREIGN KEY (${columnNames}) ` +
`REFERENCES ${this.escapePath(
this.getTablePath(foreignKey),
)}(${referencedColumnNames})`
if (foreignKey.onDelete)
up += ` ON DELETE ${foreignKey.onDelete}`
if (foreignKey.onUpdate)
up += ` ON UPDATE ${foreignKey.onUpdate}`
let down =
`ALTER TABLE ${this.escapePath(
table,
)} DROP FOREIGN KEY \`${newForeignKeyName}\`, ADD CONSTRAINT \`${
foreignKey.name
}\` FOREIGN KEY (${columnNames}) ` +
`REFERENCES ${this.escapePath(
this.getTablePath(foreignKey),
)}(${referencedColumnNames})`
if (foreignKey.onDelete)
down += ` ON DELETE ${foreignKey.onDelete}`
if (foreignKey.onUpdate)
down += ` ON UPDATE ${foreignKey.onUpdate}`
upQueries.push(new Query(up))
downQueries.push(new Query(down))
// replace constraint name
foreignKey.name = newForeignKeyName
})
// rename old column in the Table object
const oldTableColumn = clonedTable.columns.find(
(column) => column.name === oldColumn.name,
)
clonedTable.columns[
clonedTable.columns.indexOf(oldTableColumn!)
].name = newColumn.name
oldColumn.name = newColumn.name
}
if (this.isColumnChanged(oldColumn, newColumn, true)) {
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
oldColumn.name
}\` ${this.buildCreateColumnSql(newColumn, true)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
newColumn.name
}\` ${this.buildCreateColumnSql(oldColumn, true)}`,
),
)
}
if (newColumn.isPrimary !== oldColumn.isPrimary) {
// if table have generated column, we must drop AUTO_INCREMENT before changing primary constraints.
const generatedColumn = clonedTable.columns.find(
(column) =>
column.isGenerated &&
column.generationStrategy === "increment",
)
if (generatedColumn) {
const nonGeneratedColumn = generatedColumn.clone()
nonGeneratedColumn.isGenerated = false
nonGeneratedColumn.generationStrategy = undefined
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
generatedColumn.name
}\` ${this.buildCreateColumnSql(
nonGeneratedColumn,
true,
)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
nonGeneratedColumn.name
}\` ${this.buildCreateColumnSql(
generatedColumn,
true,
)}`,
),
)
}
const primaryColumns = clonedTable.primaryColumns
// if primary column state changed, we must always drop existed constraint.
if (primaryColumns.length > 0) {
const columnNames = primaryColumns
.map((column) => `\`${column.name}\``)
.join(", ")
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} DROP PRIMARY KEY`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD PRIMARY KEY (${columnNames})`,
),
)
}
if (newColumn.isPrimary === true) {
primaryColumns.push(newColumn)
// update column in table
const column = clonedTable.columns.find(
(column) => column.name === newColumn.name,
)
column!.isPrimary = true
const columnNames = primaryColumns
.map((column) => `\`${column.name}\``)
.join(", ")
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD PRIMARY KEY (${columnNames})`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} DROP PRIMARY KEY`,
),
)
} else {
const primaryColumn = primaryColumns.find(
(c) => c.name === newColumn.name,
)
primaryColumns.splice(
primaryColumns.indexOf(primaryColumn!),
1,
)
// update column in table
const column = clonedTable.columns.find(
(column) => column.name === newColumn.name,
)
column!.isPrimary = false
// if we have another primary keys, we must recreate constraint.
if (primaryColumns.length > 0) {
const columnNames = primaryColumns
.map((column) => `\`${column.name}\``)
.join(", ")
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD PRIMARY KEY (${columnNames})`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} DROP PRIMARY KEY`,
),
)
}
}
// if we have generated column, and we dropped AUTO_INCREMENT property before, we must bring it back
if (generatedColumn) {
const nonGeneratedColumn = generatedColumn.clone()
nonGeneratedColumn.isGenerated = false
nonGeneratedColumn.generationStrategy = undefined
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
nonGeneratedColumn.name
}\` ${this.buildCreateColumnSql(
generatedColumn,
true,
)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
generatedColumn.name
}\` ${this.buildCreateColumnSql(
nonGeneratedColumn,
true,
)}`,
),
)
}
}
if (newColumn.isUnique !== oldColumn.isUnique) {
if (newColumn.isUnique === true) {
const uniqueIndex = new TableIndex({
name: this.connection.namingStrategy.indexName(table, [
newColumn.name,
]),
columnNames: [newColumn.name],
isUnique: true,
})
clonedTable.indices.push(uniqueIndex)
clonedTable.uniques.push(
new TableUnique({
name: uniqueIndex.name,
columnNames: uniqueIndex.columnNames,
}),
)
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD UNIQUE INDEX \`${uniqueIndex.name}\` (\`${
newColumn.name
}\`)`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} DROP INDEX \`${uniqueIndex.name}\``,
),
)
} else {
const uniqueIndex = clonedTable.indices.find((index) => {
return (
index.columnNames.length === 1 &&
index.isUnique === true &&
!!index.columnNames.find(
(columnName) => columnName === newColumn.name,
)
)
})
clonedTable.indices.splice(
clonedTable.indices.indexOf(uniqueIndex!),
1,
)
const tableUnique = clonedTable.uniques.find(
(unique) => unique.name === uniqueIndex!.name,
)
clonedTable.uniques.splice(
clonedTable.uniques.indexOf(tableUnique!),
1,
)
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} DROP INDEX \`${uniqueIndex!.name}\``,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD UNIQUE INDEX \`${uniqueIndex!.name}\` (\`${
newColumn.name
}\`)`,
),
)
}
}
}
await this.executeQueries(upQueries, downQueries)
this.replaceCachedTable(table, clonedTable)
}
/**
* Changes a column in the table.
*/
async changeColumns(
tableOrName: Table | string,
changedColumns: { newColumn: TableColumn; oldColumn: TableColumn }[],
): Promise<void> {
for (const { oldColumn, newColumn } of changedColumns) {
await this.changeColumn(tableOrName, oldColumn, newColumn)
}
}
/**
* Drops column in the table.
*/
async dropColumn(
tableOrName: Table | string,
columnOrName: TableColumn | string,
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
const column = InstanceChecker.isTableColumn(columnOrName)
? columnOrName
: table.findColumnByName(columnOrName)
if (!column)
throw new TypeORMError(
`Column "${columnOrName}" was not found in table "${table.name}"`,
)
const clonedTable = table.clone()
const upQueries: Query[] = []
const downQueries: Query[] = []
// drop primary key constraint
if (column.isPrimary) {
// if table have generated column, we must drop AUTO_INCREMENT before changing primary constraints.
const generatedColumn = clonedTable.columns.find(
(column) =>
column.isGenerated &&
column.generationStrategy === "increment",
)
if (generatedColumn) {
const nonGeneratedColumn = generatedColumn.clone()
nonGeneratedColumn.isGenerated = false
nonGeneratedColumn.generationStrategy = undefined
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
generatedColumn.name
}\` ${this.buildCreateColumnSql(
nonGeneratedColumn,
true,
)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
nonGeneratedColumn.name
}\` ${this.buildCreateColumnSql(
generatedColumn,
true,
)}`,
),
)
}
// dropping primary key constraint
const columnNames = clonedTable.primaryColumns
.map((primaryColumn) => `\`${primaryColumn.name}\``)
.join(", ")
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
clonedTable,
)} DROP PRIMARY KEY`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
clonedTable,
)} ADD PRIMARY KEY (${columnNames})`,
),
)
// update column in table
const tableColumn = clonedTable.findColumnByName(column.name)
tableColumn!.isPrimary = false
// if primary key have multiple columns, we must recreate it without dropped column
if (clonedTable.primaryColumns.length > 0) {
const columnNames = clonedTable.primaryColumns
.map((primaryColumn) => `\`${primaryColumn.name}\``)
.join(", ")
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
clonedTable,
)} ADD PRIMARY KEY (${columnNames})`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
clonedTable,
)} DROP PRIMARY KEY`,
),
)
}
// if we have generated column, and we dropped AUTO_INCREMENT property before, and this column is not current dropping column, we must bring it back
if (generatedColumn && generatedColumn.name !== column.name) {
const nonGeneratedColumn = generatedColumn.clone()
nonGeneratedColumn.isGenerated = false
nonGeneratedColumn.generationStrategy = undefined
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
nonGeneratedColumn.name
}\` ${this.buildCreateColumnSql(
generatedColumn,
true,
)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
generatedColumn.name
}\` ${this.buildCreateColumnSql(
nonGeneratedColumn,
true,
)}`,
),
)
}
}
// drop column index
const columnIndex = clonedTable.indices.find(
(index) =>
index.columnNames.length === 1 &&
index.columnNames[0] === column.name,
)
if (columnIndex) {
clonedTable.indices.splice(
clonedTable.indices.indexOf(columnIndex),
1,
)
upQueries.push(this.dropIndexSql(table, columnIndex))
downQueries.push(this.createIndexSql(table, columnIndex))
} else if (column.isUnique) {
// we splice constraints both from table uniques and indices.
const uniqueName =
this.connection.namingStrategy.uniqueConstraintName(table, [
column.name,
])
const foundUnique = clonedTable.uniques.find(
(unique) => unique.name === uniqueName,
)
if (foundUnique)
clonedTable.uniques.splice(
clonedTable.uniques.indexOf(foundUnique),
1,
)
const indexName = this.connection.namingStrategy.indexName(table, [
column.name,
])
const foundIndex = clonedTable.indices.find(
(index) => index.name === indexName,
)
if (foundIndex)
clonedTable.indices.splice(
clonedTable.indices.indexOf(foundIndex),
1,
)
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} DROP INDEX \`${indexName}\``,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD UNIQUE INDEX \`${indexName}\` (\`${column.name}\`)`,
),
)
}
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} DROP COLUMN \`${
column.name
}\``,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD ${this.buildCreateColumnSql(column, true)}`,
),
)
await this.executeQueries(upQueries, downQueries)
clonedTable.removeColumn(column)
this.replaceCachedTable(table, clonedTable)
}
/**
* Drops the columns in the table.
*/
async dropColumns(
tableOrName: Table | string,
columns: TableColumn[] | string[],
): Promise<void> {
for (const column of columns) {
await this.dropColumn(tableOrName, column)
}
}
/**
* Creates a new primary key.
*/
async createPrimaryKey(
tableOrName: Table | string,
columnNames: string[],
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
const clonedTable = table.clone()
const up = this.createPrimaryKeySql(table, columnNames)
const down = this.dropPrimaryKeySql(table)
await this.executeQueries(up, down)
clonedTable.columns.forEach((column) => {
if (columnNames.find((columnName) => columnName === column.name))
column.isPrimary = true
})
this.replaceCachedTable(table, clonedTable)
}
/**
* Updates composite primary keys.
*/
async updatePrimaryKeys(
tableOrName: Table | string,
columns: TableColumn[],
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
const clonedTable = table.clone()
const columnNames = columns.map((column) => column.name)
const upQueries: Query[] = []
const downQueries: Query[] = []
// if table have generated column, we must drop AUTO_INCREMENT before changing primary constraints.
const generatedColumn = clonedTable.columns.find(
(column) =>
column.isGenerated && column.generationStrategy === "increment",
)
if (generatedColumn) {
const nonGeneratedColumn = generatedColumn.clone()
nonGeneratedColumn.isGenerated = false
nonGeneratedColumn.generationStrategy = undefined
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
generatedColumn.name
}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
nonGeneratedColumn.name
}\` ${this.buildCreateColumnSql(generatedColumn, true)}`,
),
)
}
// if table already have primary columns, we must drop them.
const primaryColumns = clonedTable.primaryColumns
if (primaryColumns.length > 0) {
const columnNames = primaryColumns
.map((column) => `\`${column.name}\``)
.join(", ")
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD PRIMARY KEY (${columnNames})`,
),
)
}
// update columns in table.
clonedTable.columns
.filter((column) => columnNames.indexOf(column.name) !== -1)
.forEach((column) => (column.isPrimary = true))
const columnNamesString = columnNames
.map((columnName) => `\`${columnName}\``)
.join(", ")
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD PRIMARY KEY (${columnNamesString})`,
),
)
downQueries.push(
new Query(`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`),
)
// if we already have generated column or column is changed to generated, and we dropped AUTO_INCREMENT property before, we must bring it back
const newOrExistGeneratedColumn = generatedColumn
? generatedColumn
: columns.find(
(column) =>
column.isGenerated &&
column.generationStrategy === "increment",
)
if (newOrExistGeneratedColumn) {
const nonGeneratedColumn = newOrExistGeneratedColumn.clone()
nonGeneratedColumn.isGenerated = false
nonGeneratedColumn.generationStrategy = undefined
upQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
nonGeneratedColumn.name
}\` ${this.buildCreateColumnSql(
newOrExistGeneratedColumn,
true,
)}`,
),
)
downQueries.push(
new Query(
`ALTER TABLE ${this.escapePath(table)} CHANGE \`${
newOrExistGeneratedColumn.name
}\` ${this.buildCreateColumnSql(nonGeneratedColumn, true)}`,
),
)
// if column changed to generated, we must update it in table
const changedGeneratedColumn = clonedTable.columns.find(
(column) => column.name === newOrExistGeneratedColumn.name,
)
changedGeneratedColumn!.isGenerated = true
changedGeneratedColumn!.generationStrategy = "increment"
}
await this.executeQueries(upQueries, downQueries)
this.replaceCachedTable(table, clonedTable)
}
/**
* Drops a primary key.
*/
async dropPrimaryKey(tableOrName: Table | string): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
const up = this.dropPrimaryKeySql(table)
const down = this.createPrimaryKeySql(
table,
table.primaryColumns.map((column) => column.name),
)
await this.executeQueries(up, down)
table.primaryColumns.forEach((column) => {
column.isPrimary = false
})
}
/**
* Creates a new unique constraint.
*/
async createUniqueConstraint(
tableOrName: Table | string,
uniqueConstraint: TableUnique,
): Promise<void> {
throw new TypeORMError(
`MySql does not support unique constraints. Use unique index instead.`,
)
}
/**
* Creates a new unique constraints.
*/
async createUniqueConstraints(
tableOrName: Table | string,
uniqueConstraints: TableUnique[],
): Promise<void> {
throw new TypeORMError(
`MySql does not support unique constraints. Use unique index instead.`,
)
}
/**
* Drops an unique constraint.
*/
async dropUniqueConstraint(
tableOrName: Table | string,
uniqueOrName: TableUnique | string,
): Promise<void> {
throw new TypeORMError(
`MySql does not support unique constraints. Use unique index instead.`,
)
}
/**
* Drops an unique constraints.
*/
async dropUniqueConstraints(
tableOrName: Table | string,
uniqueConstraints: TableUnique[],
): Promise<void> {
throw new TypeORMError(
`MySql does not support unique constraints. Use unique index instead.`,
)
}
/**
* Creates a new check constraint.
*/
async createCheckConstraint(
tableOrName: Table | string,
checkConstraint: TableCheck,
): Promise<void> {
throw new TypeORMError(`MySql does not support check constraints.`)
}
/**
* Creates a new check constraints.
*/
async createCheckConstraints(
tableOrName: Table | string,
checkConstraints: TableCheck[],
): Promise<void> {
throw new TypeORMError(`MySql does not support check constraints.`)
}
/**
* Drops check constraint.
*/
async dropCheckConstraint(
tableOrName: Table | string,
checkOrName: TableCheck | string,
): Promise<void> {
throw new TypeORMError(`MySql does not support check constraints.`)
}
/**
* Drops check constraints.
*/
async dropCheckConstraints(
tableOrName: Table | string,
checkConstraints: TableCheck[],
): Promise<void> {
throw new TypeORMError(`MySql does not support check constraints.`)
}
/**
* Creates a new exclusion constraint.
*/
async createExclusionConstraint(
tableOrName: Table | string,
exclusionConstraint: TableExclusion,
): Promise<void> {
throw new TypeORMError(`MySql does not support exclusion constraints.`)
}
/**
* Creates a new exclusion constraints.
*/
async createExclusionConstraints(
tableOrName: Table | string,
exclusionConstraints: TableExclusion[],
): Promise<void> {
throw new TypeORMError(`MySql does not support exclusion constraints.`)
}
/**
* Drops exclusion constraint.
*/
async dropExclusionConstraint(
tableOrName: Table | string,
exclusionOrName: TableExclusion | string,
): Promise<void> {
throw new TypeORMError(`MySql does not support exclusion constraints.`)
}
/**
* Drops exclusion constraints.
*/
async dropExclusionConstraints(
tableOrName: Table | string,
exclusionConstraints: TableExclusion[],
): Promise<void> {
throw new TypeORMError(`MySql does not support exclusion constraints.`)
}
/**
* Creates a new foreign key.
*/
async createForeignKey(
tableOrName: Table | string,
foreignKey: TableForeignKey,
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
// new FK may be passed without name. In this case we generate FK name manually.
if (!foreignKey.name)
foreignKey.name = this.connection.namingStrategy.foreignKeyName(
table,
foreignKey.columnNames,
)
const up = this.createForeignKeySql(table, foreignKey)
const down = this.dropForeignKeySql(table, foreignKey)
await this.executeQueries(up, down)
table.addForeignKey(foreignKey)
}
/**
* Creates a new foreign keys.
*/
async createForeignKeys(
tableOrName: Table | string,
foreignKeys: TableForeignKey[],
): Promise<void> {
const promises = foreignKeys.map((foreignKey) =>
this.createForeignKey(tableOrName, foreignKey),
)
await Promise.all(promises)
}
/**
* Drops a foreign key.
*/
async dropForeignKey(
tableOrName: Table | string,
foreignKeyOrName: TableForeignKey | string,
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
const foreignKey = InstanceChecker.isTableForeignKey(foreignKeyOrName)
? foreignKeyOrName
: table.foreignKeys.find((fk) => fk.name === foreignKeyOrName)
if (!foreignKey)
throw new TypeORMError(
`Supplied foreign key was not found in table ${table.name}`,
)
const up = this.dropForeignKeySql(table, foreignKey)
const down = this.createForeignKeySql(table, foreignKey)
await this.executeQueries(up, down)
table.removeForeignKey(foreignKey)
}
/**
* Drops a foreign keys from the table.
*/
async dropForeignKeys(
tableOrName: Table | string,
foreignKeys: TableForeignKey[],
): Promise<void> {
const promises = foreignKeys.map((foreignKey) =>
this.dropForeignKey(tableOrName, foreignKey),
)
await Promise.all(promises)
}
/**
* Creates a new index.
*/
async createIndex(
tableOrName: Table | string,
index: TableIndex,
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
// new index may be passed without name. In this case we generate index name manually.
if (!index.name) index.name = this.generateIndexName(table, index)
const up = this.createIndexSql(table, index)
const down = this.dropIndexSql(table, index)
await this.executeQueries(up, down)
table.addIndex(index, true)
}
/**
* Creates a new indices
*/
async createIndices(
tableOrName: Table | string,
indices: TableIndex[],
): Promise<void> {
const promises = indices.map((index) =>
this.createIndex(tableOrName, index),
)
await Promise.all(promises)
}
/**
* Drops an index.
*/
async dropIndex(
tableOrName: Table | string,
indexOrName: TableIndex | string,
): Promise<void> {
const table = InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName)
const index = InstanceChecker.isTableIndex(indexOrName)
? indexOrName
: table.indices.find((i) => i.name === indexOrName)
if (!index)
throw new TypeORMError(
`Supplied index ${indexOrName} was not found in table ${table.name}`,
)
// old index may be passed without name. In this case we generate index name manually.
if (!index.name) index.name = this.generateIndexName(table, index)
const up = this.dropIndexSql(table, index)
const down = this.createIndexSql(table, index)
await this.executeQueries(up, down)
table.removeIndex(index, true)
}
/**
* Drops an indices from the table.
*/
async dropIndices(
tableOrName: Table | string,
indices: TableIndex[],
): Promise<void> {
const promises = indices.map((index) =>
this.dropIndex(tableOrName, index),
)
await Promise.all(promises)
}
/**
* Clears all table contents.
* Note: this operation uses SQL's TRUNCATE query which cannot be reverted in transactions.
*/
async clearTable(tableOrName: Table | string): Promise<void> {
await this.query(`TRUNCATE TABLE ${this.escapePath(tableOrName)}`)
}
/**
* Removes all tables from the currently connected database.
* Be careful using this method and avoid using it in production or migrations
* (because it can clear all your database).
*/
async clearDatabase(database?: string): Promise<void> {
const dbName = database ? database : this.driver.database
if (dbName) {
const isDatabaseExist = await this.hasDatabase(dbName)
if (!isDatabaseExist) return Promise.resolve()
} else {
throw new TypeORMError(
`Can not clear database. No database is specified`,
)
}
const isAnotherTransactionActive = this.isTransactionActive
if (!isAnotherTransactionActive) await this.startTransaction()
try {
const selectViewDropsQuery = `SELECT concat('DROP VIEW IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`VIEWS\` WHERE \`TABLE_SCHEMA\` = '${dbName}'`
const dropViewQueries: ObjectLiteral[] = await this.query(
selectViewDropsQuery,
)
await Promise.all(
dropViewQueries.map((q) => this.query(q["query"])),
)
const disableForeignKeysCheckQuery = `SET FOREIGN_KEY_CHECKS = 0;`
const dropTablesQuery = `SELECT concat('DROP TABLE IF EXISTS \`', table_schema, '\`.\`', table_name, '\`') AS \`query\` FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE \`TABLE_SCHEMA\` = '${dbName}'`
const enableForeignKeysCheckQuery = `SET FOREIGN_KEY_CHECKS = 1;`
await this.query(disableForeignKeysCheckQuery)
const dropQueries: ObjectLiteral[] = await this.query(
dropTablesQuery,
)
await Promise.all(
dropQueries.map((query) => this.query(query["query"])),
)
await this.query(enableForeignKeysCheckQuery)
if (!isAnotherTransactionActive) {
await this.commitTransaction()
}
} catch (error) {
try {
// we throw original error even if rollback thrown an error
if (!isAnotherTransactionActive) {
await this.rollbackTransaction()
}
} catch (rollbackError) {}
throw error
}
}
// your_sha256_hash---------
// Protected Methods
// your_sha256_hash---------
protected async loadViews(viewNames?: string[]): Promise<View[]> {
const hasTable = await this.hasTable(this.getTypeormMetadataTableName())
if (!hasTable) {
return []
}
if (!viewNames) {
viewNames = []
}
const currentDatabase = await this.getCurrentDatabase()
const viewsCondition = viewNames
.map((tableName) => {
let { database, tableName: name } =
this.driver.parseTableName(tableName)
if (!database) {
database = currentDatabase
}
return `(\`t\`.\`schema\` = '${database}' AND \`t\`.\`name\` = '${name}')`
})
.join(" OR ")
const query =
`SELECT \`t\`.*, \`v\`.\`check_option\` FROM ${this.escapePath(
this.getTypeormMetadataTableName(),
)} \`t\` ` +
`INNER JOIN \`information_schema\`.\`views\` \`v\` ON \`v\`.\`table_schema\` = \`t\`.\`schema\` AND \`v\`.\`table_name\` = \`t\`.\`name\` WHERE \`t\`.\`type\` = '${
MetadataTableType.VIEW
}' ${viewsCondition ? `AND (${viewsCondition})` : ""}`
const dbViews = await this.query(query)
return dbViews.map((dbView: any) => {
const view = new View()
const db =
dbView["schema"] === currentDatabase
? undefined
: dbView["schema"]
view.database = dbView["schema"]
view.name = this.driver.buildTableName(
dbView["name"],
undefined,
db,
)
view.expression = dbView["value"]
return view
})
}
/**
* Loads all tables (with given names) from the database and creates a Table from them.
*/
protected async loadTables(tableNames?: string[]): Promise<Table[]> {
// if no tables given then no need to proceed
if (tableNames && tableNames.length === 0) {
return []
}
const dbTables: { TABLE_NAME: string; TABLE_SCHEMA: string }[] = []
const currentDatabase = await this.getCurrentDatabase()
if (!tableNames) {
const tablesSql = `SELECT TABLE_NAME, TABLE_SCHEMA FROM \`INFORMATION_SCHEMA\`.\`TABLES\``
dbTables.push(...(await this.query(tablesSql)))
} else {
const tablesCondition = tableNames
.map((tableName) => {
let [database, name] = tableName.split(".")
if (!name) {
name = database
database = this.driver.database || currentDatabase
}
return `(\`TABLE_SCHEMA\` = '${database}' AND \`TABLE_NAME\` = '${name}')`
})
.join(" OR ")
const tablesSql =
`SELECT TABLE_NAME, TABLE_SCHEMA FROM \`INFORMATION_SCHEMA\`.\`TABLES\` WHERE ` +
tablesCondition
dbTables.push(...(await this.query(tablesSql)))
}
if (dbTables.length === 0) {
return []
}
const columnsCondition = dbTables
.map(({ TABLE_NAME, TABLE_SCHEMA }) => {
return `(\`TABLE_SCHEMA\` = '${TABLE_SCHEMA}' AND \`TABLE_NAME\` = '${TABLE_NAME}')`
})
.join(" OR ")
const columnsSql =
`SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE ` +
columnsCondition
const primaryKeySql = `SELECT * FROM \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` WHERE \`CONSTRAINT_NAME\` = 'PRIMARY' AND (${columnsCondition})`
const collationsSql = `SELECT \`SCHEMA_NAME\`, \`DEFAULT_CHARACTER_SET_NAME\` as \`CHARSET\`, \`DEFAULT_COLLATION_NAME\` AS \`COLLATION\` FROM \`INFORMATION_SCHEMA\`.\`SCHEMATA\``
const indicesCondition = dbTables
.map(({ TABLE_NAME, TABLE_SCHEMA }) => {
return `(\`s\`.\`TABLE_SCHEMA\` = '${TABLE_SCHEMA}' AND \`s\`.\`TABLE_NAME\` = '${TABLE_NAME}')`
})
.join(" OR ")
const indicesSql =
`SELECT \`s\`.* FROM \`INFORMATION_SCHEMA\`.\`STATISTICS\` \`s\` ` +
`LEFT JOIN \`INFORMATION_SCHEMA\`.\`REFERENTIAL_CONSTRAINTS\` \`rc\` ON \`s\`.\`INDEX_NAME\` = \`rc\`.\`CONSTRAINT_NAME\` ` +
`WHERE (${indicesCondition}) AND \`s\`.\`INDEX_NAME\` != 'PRIMARY' AND \`rc\`.\`CONSTRAINT_NAME\` IS NULL`
const foreignKeysCondition = dbTables
.map(({ TABLE_NAME, TABLE_SCHEMA }) => {
return `(\`kcu\`.\`TABLE_SCHEMA\` = '${TABLE_SCHEMA}' AND \`kcu\`.\`TABLE_NAME\` = '${TABLE_NAME}')`
})
.join(" OR ")
const foreignKeysSql =
`SELECT \`kcu\`.\`TABLE_SCHEMA\`, \`kcu\`.\`TABLE_NAME\`, \`kcu\`.\`CONSTRAINT_NAME\`, \`kcu\`.\`COLUMN_NAME\`, \`kcu\`.\`REFERENCED_TABLE_SCHEMA\`, ` +
`\`kcu\`.\`REFERENCED_TABLE_NAME\`, \`kcu\`.\`REFERENCED_COLUMN_NAME\`, \`rc\`.\`DELETE_RULE\` \`ON_DELETE\`, \`rc\`.\`UPDATE_RULE\` \`ON_UPDATE\` ` +
`FROM \`INFORMATION_SCHEMA\`.\`KEY_COLUMN_USAGE\` \`kcu\` ` +
`INNER JOIN \`INFORMATION_SCHEMA\`.\`REFERENTIAL_CONSTRAINTS\` \`rc\` ON \`rc\`.\`constraint_name\` = \`kcu\`.\`constraint_name\` ` +
`WHERE ` +
foreignKeysCondition
const [
dbColumns,
dbPrimaryKeys,
dbCollations,
dbIndices,
dbForeignKeys,
]: ObjectLiteral[][] = await Promise.all([
this.query(columnsSql),
this.query(primaryKeySql),
this.query(collationsSql),
this.query(indicesSql),
this.query(foreignKeysSql),
])
// create tables for loaded tables
return Promise.all(
dbTables.map(async (dbTable) => {
const table = new Table()
const dbCollation = dbCollations.find(
(coll) => coll["SCHEMA_NAME"] === dbTable["TABLE_SCHEMA"],
)!
const defaultCollation = dbCollation["COLLATION"]
const defaultCharset = dbCollation["CHARSET"]
// We do not need to join database name, when database is by default.
const db =
dbTable["TABLE_SCHEMA"] === currentDatabase
? undefined
: dbTable["TABLE_SCHEMA"]
table.database = dbTable["TABLE_SCHEMA"]
table.name = this.driver.buildTableName(
dbTable["TABLE_NAME"],
undefined,
db,
)
// create columns from the loaded columns
table.columns = dbColumns
.filter(
(dbColumn) =>
dbColumn["TABLE_NAME"] === dbTable["TABLE_NAME"] &&
dbColumn["TABLE_SCHEMA"] ===
dbTable["TABLE_SCHEMA"],
)
.map((dbColumn) => {
const columnUniqueIndices = dbIndices.filter(
(dbIndex) => {
return (
dbIndex["TABLE_NAME"] ===
dbTable["TABLE_NAME"] &&
dbIndex["TABLE_SCHEMA"] ===
dbTable["TABLE_SCHEMA"] &&
dbIndex["COLUMN_NAME"] ===
dbColumn["COLUMN_NAME"] &&
parseInt(dbIndex["NON_UNIQUE"], 10) === 0
)
},
)
const tableMetadata =
this.connection.entityMetadatas.find(
(metadata) =>
this.getTablePath(table) ===
this.getTablePath(metadata),
)
const hasIgnoredIndex =
columnUniqueIndices.length > 0 &&
tableMetadata &&
tableMetadata.indices.some((index) => {
return columnUniqueIndices.some(
(uniqueIndex) => {
return (
index.name ===
uniqueIndex["INDEX_NAME"] &&
index.synchronize === false
)
},
)
})
const isConstraintComposite = columnUniqueIndices.every(
(uniqueIndex) => {
return dbIndices.some(
(dbIndex) =>
dbIndex["INDEX_NAME"] ===
uniqueIndex["INDEX_NAME"] &&
dbIndex["COLUMN_NAME"] !==
dbColumn["COLUMN_NAME"],
)
},
)
const tableColumn = new TableColumn()
tableColumn.name = dbColumn["COLUMN_NAME"]
tableColumn.type = dbColumn["DATA_TYPE"].toLowerCase()
// Unsigned columns are handled differently when it comes to width.
// Hence, we need to set the unsigned attribute before we check the width.
tableColumn.unsigned = tableColumn.zerofill
? true
: dbColumn["COLUMN_TYPE"].indexOf("unsigned") !== -1
if (
this.driver.withWidthColumnTypes.indexOf(
tableColumn.type as ColumnType,
) !== -1
) {
const width = dbColumn["COLUMN_TYPE"].substring(
dbColumn["COLUMN_TYPE"].indexOf("(") + 1,
dbColumn["COLUMN_TYPE"].indexOf(")"),
)
tableColumn.width =
width &&
!this.isDefaultColumnWidth(
table,
tableColumn,
parseInt(width),
)
? parseInt(width)
: undefined
}
if (
dbColumn["COLUMN_DEFAULT"] === null ||
dbColumn["COLUMN_DEFAULT"] === undefined
) {
tableColumn.default = undefined
} else {
tableColumn.default =
dbColumn["COLUMN_DEFAULT"] ===
"CURRENT_TIMESTAMP"
? dbColumn["COLUMN_DEFAULT"]
: `'${dbColumn["COLUMN_DEFAULT"]}'`
}
if (dbColumn["EXTRA"].indexOf("on update") !== -1) {
tableColumn.onUpdate = dbColumn["EXTRA"].substring(
dbColumn["EXTRA"].indexOf("on update") + 10,
)
}
if (dbColumn["GENERATION_EXPRESSION"]) {
tableColumn.asExpression =
dbColumn["GENERATION_EXPRESSION"]
tableColumn.generatedType =
dbColumn["EXTRA"].indexOf("VIRTUAL") !== -1
? "VIRTUAL"
: "STORED"
}
tableColumn.isUnique =
columnUniqueIndices.length > 0 &&
!hasIgnoredIndex &&
!isConstraintComposite
tableColumn.isNullable =
dbColumn["IS_NULLABLE"] === "YES"
tableColumn.isPrimary = dbPrimaryKeys.some(
(dbPrimaryKey) => {
return (
dbPrimaryKey["TABLE_NAME"] ===
dbColumn["TABLE_NAME"] &&
dbPrimaryKey["TABLE_SCHEMA"] ===
dbColumn["TABLE_SCHEMA"] &&
dbPrimaryKey["COLUMN_NAME"] ===
dbColumn["COLUMN_NAME"]
)
},
)
tableColumn.zerofill =
dbColumn["COLUMN_TYPE"].indexOf("zerofill") !== -1
tableColumn.isGenerated =
dbColumn["EXTRA"].indexOf("auto_increment") !== -1
if (tableColumn.isGenerated)
tableColumn.generationStrategy = "increment"
tableColumn.comment =
typeof dbColumn["COLUMN_COMMENT"] === "string" &&
dbColumn["COLUMN_COMMENT"].length === 0
? undefined
: dbColumn["COLUMN_COMMENT"]
if (dbColumn["CHARACTER_SET_NAME"])
tableColumn.charset =
dbColumn["CHARACTER_SET_NAME"] ===
defaultCharset
? undefined
: dbColumn["CHARACTER_SET_NAME"]
if (dbColumn["COLLATION_NAME"])
tableColumn.collation =
dbColumn["COLLATION_NAME"] === defaultCollation
? undefined
: dbColumn["COLLATION_NAME"]
// check only columns that have length property
if (
this.driver.withLengthColumnTypes.indexOf(
tableColumn.type as ColumnType,
) !== -1 &&
dbColumn["CHARACTER_MAXIMUM_LENGTH"]
) {
const length =
dbColumn["CHARACTER_MAXIMUM_LENGTH"].toString()
tableColumn.length = !this.isDefaultColumnLength(
table,
tableColumn,
length,
)
? length
: ""
}
if (
tableColumn.type === "decimal" ||
tableColumn.type === "double" ||
tableColumn.type === "float"
) {
if (
dbColumn["NUMERIC_PRECISION"] !== null &&
!this.isDefaultColumnPrecision(
table,
tableColumn,
dbColumn["NUMERIC_PRECISION"],
)
)
tableColumn.precision = parseInt(
dbColumn["NUMERIC_PRECISION"],
)
if (
dbColumn["NUMERIC_SCALE"] !== null &&
!this.isDefaultColumnScale(
table,
tableColumn,
dbColumn["NUMERIC_SCALE"],
)
)
tableColumn.scale = parseInt(
dbColumn["NUMERIC_SCALE"],
)
}
if (
tableColumn.type === "enum" ||
tableColumn.type === "simple-enum" ||
tableColumn.type === "set"
) {
const colType = dbColumn["COLUMN_TYPE"]
const items = colType
.substring(
colType.indexOf("(") + 1,
colType.lastIndexOf(")"),
)
.split(",")
tableColumn.enum = (items as string[]).map(
(item) => {
return item.substring(1, item.length - 1)
},
)
tableColumn.length = ""
}
if (
(tableColumn.type === "datetime" ||
tableColumn.type === "time" ||
tableColumn.type === "timestamp") &&
dbColumn["DATETIME_PRECISION"] !== null &&
dbColumn["DATETIME_PRECISION"] !== undefined &&
!this.isDefaultColumnPrecision(
table,
tableColumn,
parseInt(dbColumn["DATETIME_PRECISION"]),
)
) {
tableColumn.precision = parseInt(
dbColumn["DATETIME_PRECISION"],
)
}
return tableColumn
})
// find foreign key constraints of table, group them by constraint name and build TableForeignKey.
const tableForeignKeyConstraints = OrmUtils.uniq(
dbForeignKeys.filter((dbForeignKey) => {
return (
dbForeignKey["TABLE_NAME"] ===
dbTable["TABLE_NAME"] &&
dbForeignKey["TABLE_SCHEMA"] ===
dbTable["TABLE_SCHEMA"]
)
}),
(dbForeignKey) => dbForeignKey["CONSTRAINT_NAME"],
)
table.foreignKeys = tableForeignKeyConstraints.map(
(dbForeignKey) => {
const foreignKeys = dbForeignKeys.filter(
(dbFk) =>
dbFk["CONSTRAINT_NAME"] ===
dbForeignKey["CONSTRAINT_NAME"],
)
// if referenced table located in currently used db, we don't need to concat db name to table name.
const database =
dbForeignKey["REFERENCED_TABLE_SCHEMA"] ===
currentDatabase
? undefined
: dbForeignKey["REFERENCED_TABLE_SCHEMA"]
const referencedTableName = this.driver.buildTableName(
dbForeignKey["REFERENCED_TABLE_NAME"],
undefined,
database,
)
return new TableForeignKey({
name: dbForeignKey["CONSTRAINT_NAME"],
columnNames: foreignKeys.map(
(dbFk) => dbFk["COLUMN_NAME"],
),
referencedDatabase:
dbForeignKey["REFERENCED_TABLE_SCHEMA"],
referencedTableName: referencedTableName,
referencedColumnNames: foreignKeys.map(
(dbFk) => dbFk["REFERENCED_COLUMN_NAME"],
),
onDelete: dbForeignKey["ON_DELETE"],
onUpdate: dbForeignKey["ON_UPDATE"],
})
},
)
// find index constraints of table, group them by constraint name and build TableIndex.
const tableIndexConstraints = OrmUtils.uniq(
dbIndices.filter((dbIndex) => {
return (
dbIndex["TABLE_NAME"] === dbTable["TABLE_NAME"] &&
dbIndex["TABLE_SCHEMA"] === dbTable["TABLE_SCHEMA"]
)
}),
(dbIndex) => dbIndex["INDEX_NAME"],
)
table.indices = tableIndexConstraints.map((constraint) => {
const indices = dbIndices.filter((index) => {
return (
index["TABLE_SCHEMA"] ===
constraint["TABLE_SCHEMA"] &&
index["TABLE_NAME"] === constraint["TABLE_NAME"] &&
index["INDEX_NAME"] === constraint["INDEX_NAME"]
)
})
const nonUnique = parseInt(constraint["NON_UNIQUE"], 10)
return new TableIndex(<TableIndexOptions>{
table: table,
name: constraint["INDEX_NAME"],
columnNames: indices.map((i) => i["COLUMN_NAME"]),
isUnique: nonUnique === 0,
isSpatial: constraint["INDEX_TYPE"] === "SPATIAL",
isFulltext: constraint["INDEX_TYPE"] === "FULLTEXT",
})
})
return table
}),
)
}
/**
* Builds create table sql
*/
protected createTableSql(table: Table, createForeignKeys?: boolean): Query {
const columnDefinitions = table.columns
.map((column) => this.buildCreateColumnSql(column, true))
.join(", ")
let sql = `CREATE TABLE ${this.escapePath(table)} (${columnDefinitions}`
// we create unique indexes instead of unique constraints, because MySql does not have unique constraints.
// if we mark column as Unique, it means that we create UNIQUE INDEX.
table.columns
.filter((column) => column.isUnique)
.forEach((column) => {
const isUniqueIndexExist = table.indices.some((index) => {
return (
index.columnNames.length === 1 &&
!!index.isUnique &&
index.columnNames.indexOf(column.name) !== -1
)
})
const isUniqueConstraintExist = table.uniques.some((unique) => {
return (
unique.columnNames.length === 1 &&
unique.columnNames.indexOf(column.name) !== -1
)
})
if (!isUniqueIndexExist && !isUniqueConstraintExist)
table.indices.push(
new TableIndex({
name: this.connection.namingStrategy.uniqueConstraintName(
table,
[column.name],
),
columnNames: [column.name],
isUnique: true,
}),
)
})
// as MySql does not have unique constraints, we must create table indices from table uniques and mark them as unique.
if (table.uniques.length > 0) {
table.uniques.forEach((unique) => {
const uniqueExist = table.indices.some(
(index) => index.name === unique.name,
)
if (!uniqueExist) {
table.indices.push(
new TableIndex({
name: unique.name,
columnNames: unique.columnNames,
isUnique: true,
}),
)
}
})
}
if (table.indices.length > 0) {
const indicesSql = table.indices
.map((index) => {
const columnNames = index.columnNames
.map((columnName) => `\`${columnName}\``)
.join(", ")
if (!index.name)
index.name = this.connection.namingStrategy.indexName(
table,
index.columnNames,
index.where,
)
let indexType = ""
if (index.isUnique) indexType += "UNIQUE "
if (index.isSpatial) indexType += "SPATIAL "
if (index.isFulltext) indexType += "FULLTEXT "
return `${indexType}INDEX \`${index.name}\` (${columnNames})`
})
.join(", ")
sql += `, ${indicesSql}`
}
if (table.foreignKeys.length > 0 && createForeignKeys) {
const foreignKeysSql = table.foreignKeys
.map((fk) => {
const columnNames = fk.columnNames
.map((columnName) => `\`${columnName}\``)
.join(", ")
if (!fk.name)
fk.name = this.connection.namingStrategy.foreignKeyName(
table,
fk.columnNames,
)
const referencedColumnNames = fk.referencedColumnNames
.map((columnName) => `\`${columnName}\``)
.join(", ")
let constraint = `CONSTRAINT \`${
fk.name
}\` FOREIGN KEY (${columnNames}) REFERENCES ${this.escapePath(
this.getTablePath(fk),
)} (${referencedColumnNames})`
if (fk.onDelete) constraint += ` ON DELETE ${fk.onDelete}`
if (fk.onUpdate) constraint += ` ON UPDATE ${fk.onUpdate}`
return constraint
})
.join(", ")
sql += `, ${foreignKeysSql}`
}
if (table.primaryColumns.length > 0) {
const columnNames = table.primaryColumns
.map((column) => `\`${column.name}\``)
.join(", ")
sql += `, PRIMARY KEY (${columnNames})`
}
sql += `) ENGINE=${table.engine || "InnoDB"}`
return new Query(sql)
}
/**
* Builds drop table sql
*/
protected dropTableSql(tableOrName: Table | string): Query {
return new Query(`DROP TABLE ${this.escapePath(tableOrName)}`)
}
protected createViewSql(view: View): Query {
if (typeof view.expression === "string") {
return new Query(
`CREATE VIEW ${this.escapePath(view)} AS ${view.expression}`,
)
} else {
return new Query(
`CREATE VIEW ${this.escapePath(view)} AS ${view
.expression(this.connection)
.getQuery()}`,
)
}
}
protected async insertViewDefinitionSql(view: View): Promise<Query> {
const currentDatabase = await this.getCurrentDatabase()
const expression =
typeof view.expression === "string"
? view.expression.trim()
: view.expression(this.connection).getQuery()
return this.insertTypeormMetadataSql({
type: MetadataTableType.VIEW,
schema: currentDatabase,
name: view.name,
value: expression,
})
}
/**
* Builds drop view sql.
*/
protected dropViewSql(viewOrPath: View | string): Query {
return new Query(`DROP VIEW ${this.escapePath(viewOrPath)}`)
}
/**
* Builds remove view sql.
*/
protected async deleteViewDefinitionSql(
viewOrPath: View | string,
): Promise<Query> {
const currentDatabase = await this.getCurrentDatabase()
const viewName = InstanceChecker.isView(viewOrPath)
? viewOrPath.name
: viewOrPath
return this.deleteTypeormMetadataSql({
type: MetadataTableType.VIEW,
schema: currentDatabase,
name: viewName,
})
}
/**
* Builds create index sql.
*/
protected createIndexSql(table: Table, index: TableIndex): Query {
const columns = index.columnNames
.map((columnName) => `\`${columnName}\``)
.join(", ")
let indexType = ""
if (index.isUnique) indexType += "UNIQUE "
if (index.isSpatial) indexType += "SPATIAL "
if (index.isFulltext) indexType += "FULLTEXT "
return new Query(
`CREATE ${indexType}INDEX \`${index.name}\` ON ${this.escapePath(
table,
)} (${columns})`,
)
}
/**
* Builds drop index sql.
*/
protected dropIndexSql(
table: Table,
indexOrName: TableIndex | string,
): Query {
let indexName = InstanceChecker.isTableIndex(indexOrName)
? indexOrName.name
: indexOrName
return new Query(
`DROP INDEX \`${indexName}\` ON ${this.escapePath(table)}`,
)
}
/**
* Builds create primary key sql.
*/
protected createPrimaryKeySql(table: Table, columnNames: string[]): Query {
const columnNamesString = columnNames
.map((columnName) => `\`${columnName}\``)
.join(", ")
return new Query(
`ALTER TABLE ${this.escapePath(
table,
)} ADD PRIMARY KEY (${columnNamesString})`,
)
}
/**
* Builds drop primary key sql.
*/
protected dropPrimaryKeySql(table: Table): Query {
return new Query(
`ALTER TABLE ${this.escapePath(table)} DROP PRIMARY KEY`,
)
}
/**
* Builds create foreign key sql.
*/
protected createForeignKeySql(
table: Table,
foreignKey: TableForeignKey,
): Query {
const columnNames = foreignKey.columnNames
.map((column) => `\`${column}\``)
.join(", ")
const referencedColumnNames = foreignKey.referencedColumnNames
.map((column) => `\`${column}\``)
.join(",")
let sql =
`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT \`${
foreignKey.name
}\` FOREIGN KEY (${columnNames}) ` +
`REFERENCES ${this.escapePath(
this.getTablePath(foreignKey),
)}(${referencedColumnNames})`
if (foreignKey.onDelete) sql += ` ON DELETE ${foreignKey.onDelete}`
if (foreignKey.onUpdate) sql += ` ON UPDATE ${foreignKey.onUpdate}`
return new Query(sql)
}
/**
* Builds drop foreign key sql.
*/
protected dropForeignKeySql(
table: Table,
foreignKeyOrName: TableForeignKey | string,
): Query {
const foreignKeyName = InstanceChecker.isTableForeignKey(
foreignKeyOrName,
)
? foreignKeyOrName.name
: foreignKeyOrName
return new Query(
`ALTER TABLE ${this.escapePath(
table,
)} DROP FOREIGN KEY \`${foreignKeyName}\``,
)
}
/**
* Escapes a given comment so it's safe to include in a query.
*/
protected escapeComment(comment?: string) {
if (!comment || comment.length === 0) {
return `''`
}
comment = comment
.replace(/\\/g, "\\\\") // MySQL allows escaping characters via backslashes
.replace(/'/g, "''")
.replace(/\u0000/g, "") // Null bytes aren't allowed in comments
return `'${comment}'`
}
/**
* Escapes given table or view path.
*/
protected escapePath(target: Table | View | string): string {
const { database, tableName } = this.driver.parseTableName(target)
if (database && database !== this.driver.database) {
return `\`${database}\`.\`${tableName}\``
}
return `\`${tableName}\``
}
/**
* Builds a part of query to create/change a column.
*/
protected buildCreateColumnSql(
column: TableColumn,
skipPrimary: boolean,
skipName: boolean = false,
) {
let c = ""
if (skipName) {
c = this.connection.driver.createFullType(column)
} else {
c = `\`${column.name}\` ${this.connection.driver.createFullType(
column,
)}`
}
if (column.asExpression)
c += ` AS (${column.asExpression}) ${
column.generatedType ? column.generatedType : "VIRTUAL"
}`
// if you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to that column.
if (column.zerofill) {
c += " ZEROFILL"
} else if (column.unsigned) {
c += " UNSIGNED"
}
if (column.enum)
c += ` (${column.enum
.map((value) => "'" + value + "'")
.join(", ")})`
if (column.charset) c += ` CHARACTER SET "${column.charset}"`
if (column.collation) c += ` COLLATE "${column.collation}"`
if (!column.isNullable) c += " NOT NULL"
if (column.isNullable) c += " NULL"
if (column.isPrimary && !skipPrimary) c += " PRIMARY KEY"
if (column.isGenerated && column.generationStrategy === "increment")
// don't use skipPrimary here since updates can update already exist primary without auto inc.
c += " AUTO_INCREMENT"
if (column.comment)
c += ` COMMENT ${this.escapeComment(column.comment)}`
if (column.default !== undefined && column.default !== null)
c += ` DEFAULT ${column.default}`
if (column.onUpdate) c += ` ON UPDATE ${column.onUpdate}`
return c
}
/**
* Checks if column display width is by default.
*/
protected isDefaultColumnWidth(
table: Table,
column: TableColumn,
width: number,
): boolean {
// if table have metadata, we check if length is specified in column metadata
if (this.connection.hasMetadata(table.name)) {
const metadata = this.connection.getMetadata(table.name)
const columnMetadata = metadata.findColumnWithDatabaseName(
column.name,
)
if (columnMetadata && columnMetadata.width) return false
}
const defaultWidthForType =
this.connection.driver.dataTypeDefaults &&
this.connection.driver.dataTypeDefaults[column.type] &&
this.connection.driver.dataTypeDefaults[column.type].width
if (defaultWidthForType) {
// In MariaDB & MySQL 5.7, the default widths of certain numeric types are 1 less than
// the usual defaults when the column is unsigned.
// This also applies to Aurora MySQL.
const typesWithReducedUnsignedDefault = [
"int",
"tinyint",
"smallint",
"mediumint",
]
const needsAdjustment =
typesWithReducedUnsignedDefault.indexOf(column.type) !== -1
if (column.unsigned && needsAdjustment) {
return defaultWidthForType - 1 === width
} else {
return defaultWidthForType === width
}
}
return false
}
/**
* Change table comment.
*/
changeTableComment(
tableOrName: Table | string,
comment?: string,
): Promise<void> {
throw new TypeORMError(
`aurora-mysql driver does not support change table comment.`,
)
}
}
``` | /content/code_sandbox/src/driver/aurora-mysql/AuroraMysqlQueryRunner.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 19,416 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>Author</key>
<string>Vandroiy</string>
<key>CodecID</key>
<integer>20751</integer>
<key>CodecName</key>
<string>CX20751_2</string>
<key>Files</key>
<dict>
<key>Layouts</key>
<array>
<dict>
<key>Comment</key>
<string>Mirone - Conexant 20752</string>
<key>Id</key>
<integer>3</integer>
<key>Path</key>
<string>layout3.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Andres ZeroCross - Asus A455LF - WX039D</string>
<key>Id</key>
<integer>21</integer>
<key>Path</key>
<string>layout21.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom Conexant 20751</string>
<key>Id</key>
<integer>28</integer>
<key>Path</key>
<string>layout28.xml.zlib</string>
</dict>
</array>
<key>Platforms</key>
<array>
<dict>
<key>Comment</key>
<string>Mirone - Conexant 20752</string>
<key>Id</key>
<integer>3</integer>
<key>Path</key>
<string>PlatformsM.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Andres ZeroCross - Asus A455LF - WX039D</string>
<key>Id</key>
<integer>21</integer>
<key>Path</key>
<string>Platforms21.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Custom Conexant 20751</string>
<key>Id</key>
<integer>28</integer>
<key>Path</key>
<string>Platforms28.xml.zlib</string>
</dict>
</array>
</dict>
<key>Patches</key>
<array>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>xgYASIu/aAE=</data>
<key>MinKernel</key>
<integer>18</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>xgYBSIu/aAE=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcYGAEmLvCQ=</data>
<key>MaxKernel</key>
<integer>13</integer>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcYGAUmLvCQ=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcYGAEiLu2g=</data>
<key>MinKernel</key>
<integer>14</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcYGAUiLu2g=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcaGQwEAAAA=</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcaGQwEAAAE=</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>ixnUEQ==</data>
<key>MinKernel</key>
<integer>13</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>D1HxFA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>gxnUEQ==</data>
<key>MaxKernel</key>
<integer>15</integer>
<key>MinKernel</key>
<integer>15</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>ihnUEQ==</data>
<key>MinKernel</key>
<integer>16</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>a3Bzaes=</data>
<key>MinKernel</key>
<integer>14</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Provider</key>
<string>Wern Apfel</string>
<key>Replace</key>
<data>Y2ltaes=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>D7bCg/kD</data>
<key>MinKernel</key>
<string>14</string>
<key>Name</key>
<string>AppleHDA</string>
<key>Provider</key>
<string>Vasishath Kaushal</string>
<key>Replace</key>
<data>D7bCg/kB</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>D7fwg/oC</data>
<key>MinKernel</key>
<string>14</string>
<key>Name</key>
<string>AppleHDA</string>
<key>Provider</key>
<string>Vasishath Kaushal</string>
<key>Replace</key>
<data>D7fwg/oB</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>D7bqg/gD</data>
<key>MinKernel</key>
<string>20</string>
<key>Name</key>
<string>AppleHDA</string>
<key>Provider</key>
<string>Vasishath Kaushal - Ported to Big Sur by Luca91</string>
<key>Replace</key>
<data>D7bqg/gB</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>weEIRTHkg/gC</data>
<key>MinKernel</key>
<string>20</string>
<key>Name</key>
<string>AppleHDA</string>
<key>Provider</key>
<string>Vasishath Kaushal - Ported to Big Sur by Luca91</string>
<key>Replace</key>
<data>weEIRTHkg/gB</data>
</dict>
</array>
<key>Revisions</key>
<array>
<integer>1048832</integer>
<integer>1048577</integer>
</array>
<key>Vendor</key>
<string>Conexant</string>
</dict>
</plist>
``` | /content/code_sandbox/Resources/CX20751_2/Info.plist | xml | 2016-03-07T20:45:58 | 2024-08-14T08:57:03 | AppleALC | acidanthera/AppleALC | 3,420 | 2,156 |
```xml
import { describe, it, expect, afterEach } from 'vitest';
import fs from 'fs-extra';
import sleep from '../../../src/util/sleep';
import tmp from 'tmp-promise';
import getLatestVersion from '../../../src/util/get-latest-version';
import { join } from 'path';
import { vi } from 'vitest';
tmp.setGracefulCleanup();
vi.setConfig({ testTimeout: 25000 });
const cacheDir = tmp.tmpNameSync({
prefix: 'test-vercel-cli-get-latest-version-',
});
const cacheFile = join(cacheDir, 'package-updates', 'vercel-latest.json');
const pkg = {
name: 'vercel',
version: '27.3.0',
};
const versionRE = /^\d+\.\d+\.\d+$/;
describe('get latest version', () => {
afterEach(() => fs.remove(cacheDir));
it('should find newer version async', async () => {
// 1. first call, no cache file
let latest = getLatestVersion({
cacheDir,
pkg,
});
expect(latest).toEqual(undefined);
await waitForCacheFile();
let cache = await fs.readJSON(cacheFile);
expect(typeof cache).toEqual('object');
expect(typeof cache.expireAt).toEqual('number');
expect(cache.expireAt).toBeGreaterThan(Date.now());
expect(typeof cache.version).toEqual('string');
expect(cache.version).toEqual(expect.stringMatching(versionRE));
expect(cache.notifyAt).toEqual(undefined);
// 2. call again and this time it'll return the version from the cache
latest = getLatestVersion({
cacheDir,
pkg,
});
expect(typeof latest).toBe('string');
expect(latest).toEqual(expect.stringMatching(versionRE));
cache = await fs.readJSON(cacheFile);
expect(cache.version).toEqual(expect.stringMatching(versionRE));
expect(cache.notifyAt).not.toEqual(undefined);
// 3. notification already done, should skip
latest = getLatestVersion({
cacheDir,
pkg,
});
expect(latest).toEqual(undefined);
});
it('should not find a newer version', async () => {
// 1. first call, no cache file
let latest = getLatestVersion({
cacheDir,
updateCheckInterval: 1,
pkg: {
...pkg,
version: '999.0.0',
},
});
expect(latest).toEqual(undefined);
await waitForCacheFile();
// 2. call again and should recheck and still not find a new version
latest = getLatestVersion({
cacheDir,
updateCheckInterval: 1,
pkg: {
...pkg,
version: '999.0.0',
},
});
expect(latest).toEqual(undefined);
});
it('should not check twice', async () => {
// 1. first call, no cache file
let latest = getLatestVersion({
cacheDir,
updateCheckInterval: 1,
pkg,
});
expect(latest).toEqual(undefined);
// 2. immediately call again, but should hopefully still be undefined
latest = getLatestVersion({
cacheDir,
updateCheckInterval: 1,
pkg,
});
expect(latest).toEqual(undefined);
await waitForCacheFile();
// 3. call again and should recheck and find a new version
latest = getLatestVersion({
cacheDir,
updateCheckInterval: 1,
pkg,
});
expect(typeof latest).toBe('string');
expect(latest).toEqual(expect.stringMatching(versionRE));
});
it('should error if no arguments are passed in', () => {
expect(() => getLatestVersion(undefined as any)).toThrow(TypeError);
});
it('should error package is invalid', () => {
expect(() => getLatestVersion({} as any)).toThrow(TypeError);
expect(() => getLatestVersion({ pkg: null as any })).toThrow(TypeError);
expect(() => getLatestVersion({ pkg: {} })).toThrow(TypeError);
expect(() => getLatestVersion({ pkg: { name: null as any } })).toThrow(
TypeError
);
expect(() => getLatestVersion({ pkg: { name: '' } })).toThrow(TypeError);
});
it('should reset notify if newer version is available', async () => {
// 1. seed the cache file with both a expireAt and notifyAt in the future
// with an out-of-date latest version
await fs.mkdirs(join(cacheDir, 'package-updates'));
await fs.writeJSON(cacheFile, {
expireAt: Date.now(),
notifyAt: Date.now() - 60000,
version: '28.0.0',
});
// 2. get the latest version
let latest = getLatestVersion({
cacheDir,
pkg,
});
expect(latest).toEqual('28.0.0');
// we need to wait up to 20 seconds for the cacheFile to be updated
for (let i = 0; i < 80; i++) {
await sleep(250);
try {
const cache = await fs.readJSON(cacheFile);
if (cache.version !== '28.0.0') {
break;
}
} catch {
// cacheFile has not been updated yet
}
if (i + 1 === 80) {
throw new Error(`Timed out waiting for worker to fetch latest version`);
}
}
let cache = await fs.readJSON(cacheFile);
expect(cache.version).toEqual(expect.stringMatching(versionRE));
expect(cache.version).not.toEqual('28.0.0');
expect(cache.notifyAt).toEqual(undefined);
});
});
async function waitForCacheFile() {
const seconds = 20;
for (let i = 0; i < seconds * 4; i++) {
await sleep(250);
if (await fs.pathExists(cacheFile)) {
return;
}
}
}
``` | /content/code_sandbox/packages/cli/test/unit/util/get-latest-version.test.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 1,279 |
```xml
import _ from 'underscore';
import MailspringStore from 'mailspring-store';
import { MessageStore } from 'mailspring-exports';
class GithubStore extends MailspringStore {
_link: string = null;
_lastItemIds: string[];
// It's very common practive for {MailspringStore}s to listen to other parts of N1.
// Since Stores are singletons and constructed once on `require`, there is no
// teardown step to turn off listeners.
constructor() {
super();
this.listenTo(MessageStore, this._onMessageStoreChanged);
}
// This is the only public method on `GithubStore` and it's read only.
// All {MailspringStore}s ONLY have reader methods. No setter methods. Use an
// `Action` instead!
//
// This is the computed & cached value that our `ViewOnGithubButton` will
// render.
link() {
return this._link;
}
// Private methods
_onMessageStoreChanged() {
if (!MessageStore.threadId()) {
return;
}
const itemIds = _.pluck(MessageStore.items(), 'id');
if (itemIds.length === 0 || _.isEqual(itemIds, this._lastItemIds)) {
return;
}
this._lastItemIds = itemIds;
this._link = this._isRelevantThread() ? this._findGitHubLink() : null;
this.trigger();
}
_findGitHubLink() {
let msg = MessageStore.items()[0];
if (!msg.body) {
// The msg body may be null if it's collapsed. In that case, use the
// last message. This may be less relaiable since the last message
// might be a side-thread that doesn't contain the link in the quoted
// text.
msg = _.last(MessageStore.items());
}
// Use a regex to parse the message body for GitHub URLs - this is a quick
// and dirty method to determine the GitHub object the email is about:
// path_to_url
const re = /<a.*?href=['"](.*?)['"].*?view.*?it.*?on.*?github.*?\/a>/gim;
const firstMatch = re.exec(msg.body);
if (firstMatch) {
// [0] is the full match and [1] is the matching group
return firstMatch[1];
}
return null;
}
_isRelevantThread() {
const participants = MessageStore.thread().participants || [];
const githubDomainRegex = /@github\.com/gi;
return participants.some(contact => githubDomainRegex.test(contact.email));
}
}
/*
IMPORTANT NOTE:
All {MailspringStore}s are constructed upon their first `require` by another
module. Since `require` is cached, they are only constructed once and
are therefore singletons.
*/
export default new GithubStore();
``` | /content/code_sandbox/app/internal_packages/message-view-on-github/lib/github-store.ts | xml | 2016-10-13T06:45:50 | 2024-08-16T18:14:37 | Mailspring | Foundry376/Mailspring | 15,331 | 637 |
```xml
<!-- drawable/star-outline.xml -->
<vector xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="#5f6267" android:pathData="M12,15.39L8.24,17.66L9.23,13.38L5.91,10.5L10.29,10.13L12,6.09L13.71,10.13L18.09,10.5L14.77,13.38L15.76,17.66M22,9.24L14.81,8.63L12,2L9.19,8.63L2,9.24L7.45,13.97L5.82,21L12,17.27L18.18,21L16.54,13.97L22,9.24Z"
tools:ignore="VectorRaster" />
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_thx.xml | xml | 2016-02-21T04:39:19 | 2024-08-16T13:35:51 | GeometricWeather | WangDaYeeeeee/GeometricWeather | 2,420 | 236 |
```xml
import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants';
import { FeatureCode } from '../../../../containers/features';
import { getUnlimitedVPNFeatures, getVPNFeatures } from '../../helpers/offerCopies';
import type { OfferConfig } from '../../interface';
import bannerImage from './EOY-VPN-App-Modal-996x176-60.png';
import bannerImage2x from './EOY-VPN-App-Modal-1992x352-60.png';
import Layout from './Layout';
const config: OfferConfig = {
ID: 'black-friday-2023-vpn-free',
autoPopUp: 'each-time',
featureCode: FeatureCode.OfferBlackFriday2023VPNFree,
images: {
bannerImage,
bannerImage2x,
},
darkBackground: true,
deals: [
{
ref: 'eoy_23_vpn-free-modal-v1p',
dealName: PLAN_NAMES[PLANS.VPN],
planIDs: {
[PLANS.VPN]: 1,
},
cycle: CYCLE.MONTHLY,
couponCode: COUPON_CODES.END_OF_YEAR_2023,
features: getVPNFeatures,
popular: 1,
mobileOrder: 1,
isGuaranteed: true,
},
{
ref: 'eoy_23_vpn-free-modal-v15p',
dealName: PLAN_NAMES[PLANS.VPN],
planIDs: {
[PLANS.VPN]: 1,
},
cycle: CYCLE.FIFTEEN,
couponCode: COUPON_CODES.END_OF_YEAR_2023,
features: getVPNFeatures,
popular: 2,
mobileOrder: 2,
isGuaranteed: true,
},
{
ref: 'eoy_23_vpn-free-modal-v30p',
dealName: PLAN_NAMES[PLANS.VPN],
planIDs: {
[PLANS.VPN]: 1,
},
cycle: CYCLE.THIRTY,
couponCode: COUPON_CODES.END_OF_YEAR_2023,
features: getVPNFeatures,
popular: 3,
mobileOrder: 3,
isGuaranteed: true,
},
{
ref: 'eoy_23_vpn-free-modal-u12',
dealName: PLAN_NAMES[PLANS.BUNDLE],
planIDs: {
[PLANS.BUNDLE]: 1,
},
cycle: CYCLE.YEARLY,
couponCode: COUPON_CODES.END_OF_YEAR_2023,
features: getUnlimitedVPNFeatures,
popular: 4,
mobileOrder: 4,
isGuaranteed: true,
},
],
layout: Layout,
};
export default config;
``` | /content/code_sandbox/packages/components/containers/offers/operations/blackFridayVPN2023Free/configuration.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 603 |
```xml
import {
commitMutationPromiseNormalized,
createMutation,
MutationInput,
} from "coral-framework/lib/relay";
import { graphql } from "relay-runtime";
import { Environment } from "relay-runtime";
import { UpdateStorySettingsMutation as MutationTypes } from "coral-admin/__generated__/UpdateStorySettingsMutation.graphql";
let clientMutationId = 0;
const UpdateStorySettingsMutation = createMutation(
"updateStorySettings",
(environment: Environment, input: MutationInput<MutationTypes>) =>
commitMutationPromiseNormalized<any>(environment, {
mutation: graphql`
mutation UpdateStorySettingsMutation(
$input: UpdateStorySettingsInput!
) {
updateStorySettings(input: $input) {
story {
settings {
mode
moderation
live {
configurable
enabled
}
premodLinksEnable
}
}
}
}
`,
variables: {
input: {
...input,
clientMutationId: (clientMutationId++).toString(),
},
},
})
);
export default UpdateStorySettingsMutation;
``` | /content/code_sandbox/client/src/core/client/admin/components/StoryInfoDrawer/UpdateStorySettingsMutation.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 230 |
```xml
/*
* Squidex Headless CMS
*
* @license
*/
import { UntypedFormControl, Validators } from '@angular/forms';
import { ExtendedFormGroup, Form, hasNoValue$ } from '@app/framework';
import { CreateWorkflowDto } from '../services/workflows.service';
export class AddWorkflowForm extends Form<ExtendedFormGroup, CreateWorkflowDto> {
public get name() {
return this.form.controls['name'];
}
public hasNoName = hasNoValue$(this.name);
constructor() {
super(new ExtendedFormGroup({
name: new UntypedFormControl('',
Validators.required,
),
}));
}
}
``` | /content/code_sandbox/frontend/src/app/shared/state/workflows.forms.ts | xml | 2016-08-29T05:53:40 | 2024-08-16T17:39:38 | squidex | Squidex/squidex | 2,222 | 134 |
```xml
// MIT-style license that can be found in the LICENSE file or at
// path_to_url
import {
Expression,
GenericAtRule,
Interpolation,
StringExpression,
css,
scss,
} from '..';
type EachFn = Parameters<Interpolation['each']>[0];
let node: Interpolation;
describe('an interpolation', () => {
describe('empty', () => {
function describeNode(
description: string,
create: () => Interpolation
): void {
describe(description, () => {
beforeEach(() => void (node = create()));
it('has sassType interpolation', () =>
expect(node.sassType).toBe('interpolation'));
it('has no nodes', () => expect(node.nodes).toHaveLength(0));
it('is plain', () => expect(node.isPlain).toBe(true));
it('has a plain value', () => expect(node.asPlain).toBe(''));
});
}
// TODO: Are there any node types that allow empty interpolation?
describeNode('constructed manually', () => new Interpolation());
});
describe('with no expressions', () => {
function describeNode(
description: string,
create: () => Interpolation
): void {
describe(description, () => {
beforeEach(() => void (node = create()));
it('has sassType interpolation', () =>
expect(node.sassType).toBe('interpolation'));
it('has a single node', () => {
expect(node.nodes).toHaveLength(1);
expect(node.nodes[0]).toBe('foo');
});
it('is plain', () => expect(node.isPlain).toBe(true));
it('has a plain value', () => expect(node.asPlain).toBe('foo'));
});
}
describeNode(
'parsed as SCSS',
() => (scss.parse('@foo').nodes[0] as GenericAtRule).nameInterpolation
);
describeNode(
'parsed as CSS',
() => (css.parse('@foo').nodes[0] as GenericAtRule).nameInterpolation
);
describeNode(
'constructed manually',
() => new Interpolation({nodes: ['foo']})
);
});
describe('with only an expression', () => {
function describeNode(
description: string,
create: () => Interpolation
): void {
describe(description, () => {
beforeEach(() => void (node = create()));
it('has sassType interpolation', () =>
expect(node.sassType).toBe('interpolation'));
it('has a single node', () =>
expect(node).toHaveStringExpression(0, 'foo'));
it('is not plain', () => expect(node.isPlain).toBe(false));
it('has no plain value', () => expect(node.asPlain).toBe(null));
});
}
describeNode(
'parsed as SCSS',
() => (scss.parse('@#{foo}').nodes[0] as GenericAtRule).nameInterpolation
);
describeNode(
'constructed manually',
() => new Interpolation({nodes: [{text: 'foo'}]})
);
});
describe('with mixed text and expressions', () => {
function describeNode(
description: string,
create: () => Interpolation
): void {
describe(description, () => {
beforeEach(() => void (node = create()));
it('has sassType interpolation', () =>
expect(node.sassType).toBe('interpolation'));
it('has multiple nodes', () => {
expect(node.nodes).toHaveLength(3);
expect(node.nodes[0]).toBe('foo');
expect(node).toHaveStringExpression(1, 'bar');
expect(node.nodes[2]).toBe('baz');
});
it('is not plain', () => expect(node.isPlain).toBe(false));
it('has no plain value', () => expect(node.asPlain).toBe(null));
});
}
describeNode(
'parsed as SCSS',
() =>
(scss.parse('@foo#{bar}baz').nodes[0] as GenericAtRule)
.nameInterpolation
);
describeNode(
'constructed manually',
() => new Interpolation({nodes: ['foo', {text: 'bar'}, 'baz']})
);
});
describe('can add', () => {
beforeEach(() => void (node = new Interpolation()));
it('a single interpolation', () => {
const interpolation = new Interpolation({nodes: ['foo', {text: 'bar'}]});
const string = interpolation.nodes[1];
node.append(interpolation);
expect(node.nodes).toEqual(['foo', string]);
expect(string).toHaveProperty('parent', node);
expect(interpolation.nodes).toHaveLength(0);
});
it('a list of interpolations', () => {
node.append([
new Interpolation({nodes: ['foo']}),
new Interpolation({nodes: ['bar']}),
]);
expect(node.nodes).toEqual(['foo', 'bar']);
});
it('a single expression', () => {
const string = new StringExpression({text: 'foo'});
node.append(string);
expect(node.nodes[0]).toBe(string);
expect(string.parent).toBe(node);
});
it('a list of expressions', () => {
const string1 = new StringExpression({text: 'foo'});
const string2 = new StringExpression({text: 'bar'});
node.append([string1, string2]);
expect(node.nodes[0]).toBe(string1);
expect(node.nodes[1]).toBe(string2);
expect(string1.parent).toBe(node);
expect(string2.parent).toBe(node);
});
it("a single expression's properties", () => {
node.append({text: 'foo'});
expect(node).toHaveStringExpression(0, 'foo');
});
it('a list of properties', () => {
node.append([{text: 'foo'}, {text: 'bar'}]);
expect(node).toHaveStringExpression(0, 'foo');
expect(node).toHaveStringExpression(1, 'bar');
});
it('a single string', () => {
node.append('foo');
expect(node.nodes).toEqual(['foo']);
});
it('a list of strings', () => {
node.append(['foo', 'bar']);
expect(node.nodes).toEqual(['foo', 'bar']);
});
it('undefined', () => {
node.append(undefined);
expect(node.nodes).toHaveLength(0);
});
});
describe('append', () => {
beforeEach(() => void (node = new Interpolation({nodes: ['foo', 'bar']})));
it('adds multiple children to the end', () => {
node.append('baz', 'qux');
expect(node.nodes).toEqual(['foo', 'bar', 'baz', 'qux']);
});
it('can be called during iteration', () =>
testEachMutation(['foo', 'bar', 'baz'], 0, () => node.append('baz')));
it('returns itself', () => expect(node.append()).toBe(node));
});
describe('each', () => {
beforeEach(() => void (node = new Interpolation({nodes: ['foo', 'bar']})));
it('calls the callback for each node', () => {
const fn: EachFn = jest.fn();
node.each(fn);
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenNthCalledWith(1, 'foo', 0);
expect(fn).toHaveBeenNthCalledWith(2, 'bar', 1);
});
it('returns undefined if the callback is void', () =>
expect(node.each(() => {})).toBeUndefined());
it('returns false and stops iterating if the callback returns false', () => {
const fn: EachFn = jest.fn(() => false);
expect(node.each(fn)).toBe(false);
expect(fn).toHaveBeenCalledTimes(1);
});
});
describe('every', () => {
beforeEach(
() => void (node = new Interpolation({nodes: ['foo', 'bar', 'baz']}))
);
it('returns true if the callback returns true for all elements', () =>
expect(node.every(() => true)).toBe(true));
it('returns false if the callback returns false for any element', () =>
expect(node.every(element => element !== 'bar')).toBe(false));
});
describe('index', () => {
beforeEach(
() =>
void (node = new Interpolation({
nodes: ['foo', 'bar', {text: 'baz'}, 'bar'],
}))
);
it('returns the first index of a given string', () =>
expect(node.index('bar')).toBe(1));
it('returns the first index of a given expression', () =>
expect(node.index(node.nodes[2])).toBe(2));
it('returns a number as-is', () => expect(node.index(3)).toBe(3));
});
describe('insertAfter', () => {
beforeEach(
() => void (node = new Interpolation({nodes: ['foo', 'bar', 'baz']}))
);
it('inserts a node after the given element', () => {
node.insertAfter('bar', 'qux');
expect(node.nodes).toEqual(['foo', 'bar', 'qux', 'baz']);
});
it('inserts a node at the beginning', () => {
node.insertAfter(-1, 'qux');
expect(node.nodes).toEqual(['qux', 'foo', 'bar', 'baz']);
});
it('inserts a node at the end', () => {
node.insertAfter(3, 'qux');
expect(node.nodes).toEqual(['foo', 'bar', 'baz', 'qux']);
});
it('inserts multiple nodes', () => {
node.insertAfter(1, ['qux', 'qax', 'qix']);
expect(node.nodes).toEqual(['foo', 'bar', 'qux', 'qax', 'qix', 'baz']);
});
it('inserts before an iterator', () =>
testEachMutation(['foo', 'bar', ['baz', 5]], 1, () =>
node.insertAfter(0, ['qux', 'qax', 'qix'])
));
it('inserts after an iterator', () =>
testEachMutation(['foo', 'bar', 'qux', 'qax', 'qix', 'baz'], 1, () =>
node.insertAfter(1, ['qux', 'qax', 'qix'])
));
it('returns itself', () =>
expect(node.insertAfter('foo', 'qux')).toBe(node));
});
describe('insertBefore', () => {
beforeEach(
() => void (node = new Interpolation({nodes: ['foo', 'bar', 'baz']}))
);
it('inserts a node before the given element', () => {
node.insertBefore('bar', 'qux');
expect(node.nodes).toEqual(['foo', 'qux', 'bar', 'baz']);
});
it('inserts a node at the beginning', () => {
node.insertBefore(0, 'qux');
expect(node.nodes).toEqual(['qux', 'foo', 'bar', 'baz']);
});
it('inserts a node at the end', () => {
node.insertBefore(4, 'qux');
expect(node.nodes).toEqual(['foo', 'bar', 'baz', 'qux']);
});
it('inserts multiple nodes', () => {
node.insertBefore(1, ['qux', 'qax', 'qix']);
expect(node.nodes).toEqual(['foo', 'qux', 'qax', 'qix', 'bar', 'baz']);
});
it('inserts before an iterator', () =>
testEachMutation(['foo', 'bar', ['baz', 5]], 1, () =>
node.insertBefore(1, ['qux', 'qax', 'qix'])
));
it('inserts after an iterator', () =>
testEachMutation(['foo', 'bar', 'qux', 'qax', 'qix', 'baz'], 1, () =>
node.insertBefore(2, ['qux', 'qax', 'qix'])
));
it('returns itself', () =>
expect(node.insertBefore('foo', 'qux')).toBe(node));
});
describe('prepend', () => {
beforeEach(
() => void (node = new Interpolation({nodes: ['foo', 'bar', 'baz']}))
);
it('inserts one node', () => {
node.prepend('qux');
expect(node.nodes).toEqual(['qux', 'foo', 'bar', 'baz']);
});
it('inserts multiple nodes', () => {
node.prepend('qux', 'qax', 'qix');
expect(node.nodes).toEqual(['qux', 'qax', 'qix', 'foo', 'bar', 'baz']);
});
it('inserts before an iterator', () =>
testEachMutation(['foo', 'bar', ['baz', 5]], 1, () =>
node.prepend('qux', 'qax', 'qix')
));
it('returns itself', () => expect(node.prepend('qux')).toBe(node));
});
describe('push', () => {
beforeEach(() => void (node = new Interpolation({nodes: ['foo', 'bar']})));
it('inserts one node', () => {
node.push('baz');
expect(node.nodes).toEqual(['foo', 'bar', 'baz']);
});
it('can be called during iteration', () =>
testEachMutation(['foo', 'bar', 'baz'], 0, () => node.push('baz')));
it('returns itself', () => expect(node.push('baz')).toBe(node));
});
describe('removeAll', () => {
beforeEach(
() =>
void (node = new Interpolation({nodes: ['foo', {text: 'bar'}, 'baz']}))
);
it('removes all nodes', () => {
node.removeAll();
expect(node.nodes).toHaveLength(0);
});
it("removes a node's parents", () => {
const string = node.nodes[1];
node.removeAll();
expect(string).toHaveProperty('parent', undefined);
});
it('can be called during iteration', () =>
testEachMutation(['foo'], 0, () => node.removeAll()));
it('returns itself', () => expect(node.removeAll()).toBe(node));
});
describe('removeChild', () => {
beforeEach(
() =>
void (node = new Interpolation({nodes: ['foo', {text: 'bar'}, 'baz']}))
);
it('removes a matching node', () => {
const string = node.nodes[1];
node.removeChild('foo');
expect(node.nodes).toEqual([string, 'baz']);
});
it('removes a node at index', () => {
node.removeChild(1);
expect(node.nodes).toEqual(['foo', 'baz']);
});
it("removes a node's parents", () => {
const string = node.nodes[1];
node.removeAll();
expect(string).toHaveProperty('parent', undefined);
});
it('removes a node before the iterator', () =>
testEachMutation(['foo', node.nodes[1], ['baz', 1]], 1, () =>
node.removeChild(1)
));
it('removes a node after the iterator', () =>
testEachMutation(['foo', node.nodes[1]], 1, () => node.removeChild(2)));
it('returns itself', () => expect(node.removeChild(0)).toBe(node));
});
describe('some', () => {
beforeEach(
() => void (node = new Interpolation({nodes: ['foo', 'bar', 'baz']}))
);
it('returns false if the callback returns false for all elements', () =>
expect(node.some(() => false)).toBe(false));
it('returns true if the callback returns true for any element', () =>
expect(node.some(element => element === 'bar')).toBe(true));
});
describe('first', () => {
it('returns the first element', () =>
expect(new Interpolation({nodes: ['foo', 'bar', 'baz']}).first).toBe(
'foo'
));
it('returns undefined for an empty interpolation', () =>
expect(new Interpolation().first).toBeUndefined());
});
describe('last', () => {
it('returns the last element', () =>
expect(new Interpolation({nodes: ['foo', 'bar', 'baz']}).last).toBe(
'baz'
));
it('returns undefined for an empty interpolation', () =>
expect(new Interpolation().last).toBeUndefined());
});
describe('stringifies', () => {
it('with no nodes', () => expect(new Interpolation().toString()).toBe(''));
it('with only text', () =>
expect(new Interpolation({nodes: ['foo', 'bar', 'baz']}).toString()).toBe(
'foobarbaz'
));
it('with only expressions', () =>
expect(
new Interpolation({nodes: [{text: 'foo'}, {text: 'bar'}]}).toString()
).toBe('#{foo}#{bar}'));
it('with mixed text and expressions', () =>
expect(
new Interpolation({nodes: ['foo', {text: 'bar'}, 'baz']}).toString()
).toBe('foo#{bar}baz'));
describe('with text', () => {
beforeEach(
() => void (node = new Interpolation({nodes: ['foo', 'bar', 'baz']}))
);
it('take precedence when the value matches', () => {
node.raws.text = [{raw: 'f\\6f o', value: 'foo'}];
expect(node.toString()).toBe('f\\6f obarbaz');
});
it("ignored when the value doesn't match", () => {
node.raws.text = [{raw: 'f\\6f o', value: 'bar'}];
expect(node.toString()).toBe('foobarbaz');
});
});
describe('with expressions', () => {
beforeEach(
() =>
void (node = new Interpolation({
nodes: [{text: 'foo'}, {text: 'bar'}],
}))
);
it('with before', () => {
node.raws.expressions = [{before: '/**/'}];
expect(node.toString()).toBe('#{/**/foo}#{bar}');
});
it('with after', () => {
node.raws.expressions = [{after: '/**/'}];
expect(node.toString()).toBe('#{foo/**/}#{bar}');
});
});
});
describe('clone', () => {
let original: Interpolation;
beforeEach(
() =>
void (original = new Interpolation({
nodes: ['foo', {text: 'bar'}, 'baz'],
raws: {expressions: [{before: ' '}]},
}))
);
describe('with no overrides', () => {
let clone: Interpolation;
beforeEach(() => void (clone = original.clone()));
describe('has the same properties:', () => {
it('nodes', () => {
expect(clone.nodes).toHaveLength(3);
expect(clone.nodes[0]).toBe('foo');
expect(clone.nodes[1]).toHaveInterpolation('text', 'bar');
expect(clone.nodes[1]).toHaveProperty('parent', clone);
expect(clone.nodes[2]).toBe('baz');
});
it('raws', () =>
expect(clone.raws).toEqual({expressions: [{before: ' '}]}));
it('source', () => expect(clone.source).toBe(original.source));
});
describe('creates a new', () => {
it('self', () => expect(clone).not.toBe(original));
for (const attr of ['raws', 'nodes'] as const) {
it(attr, () => expect(clone[attr]).not.toBe(original[attr]));
}
});
describe('sets parent for', () => {
it('nodes', () =>
expect(clone.nodes[1]).toHaveProperty('parent', clone));
});
});
describe('overrides', () => {
describe('raws', () => {
it('defined', () =>
expect(
original.clone({raws: {expressions: [{after: ' '}]}}).raws
).toEqual({expressions: [{after: ' '}]}));
it('undefined', () =>
expect(original.clone({raws: undefined}).raws).toEqual({
expressions: [{before: ' '}],
}));
});
describe('nodes', () => {
it('defined', () =>
expect(original.clone({nodes: ['qux']}).nodes).toEqual(['qux']));
it('undefined', () => {
const clone = original.clone({nodes: undefined});
expect(clone.nodes).toHaveLength(3);
expect(clone.nodes[0]).toBe('foo');
expect(clone.nodes[1]).toHaveInterpolation('text', 'bar');
expect(clone.nodes[1]).toHaveProperty('parent', clone);
expect(clone.nodes[2]).toBe('baz');
});
});
});
});
it('toJSON', () =>
expect(
(scss.parse('@foo#{bar}baz').nodes[0] as GenericAtRule).nameInterpolation
).toMatchSnapshot());
});
/**
* Runs `node.each`, asserting that it sees each element and index in {@link
* elements} in order. If an index isn't explicitly provided, it defaults to the
* index in {@link elements}.
*
* When it reaches {@link indexToModify}, it calls {@link modify}, which is
* expected to modify `node.nodes`.
*/
function testEachMutation(
elements: ([string | Expression, number] | string | Expression)[],
indexToModify: number,
modify: () => void
): void {
const fn: EachFn = jest.fn((child, i) => {
if (i === indexToModify) modify();
});
node.each(fn);
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
const [value, index] = Array.isArray(element) ? element : [element, i];
expect(fn).toHaveBeenNthCalledWith(i + 1, value, index);
}
expect(fn).toHaveBeenCalledTimes(elements.length);
}
``` | /content/code_sandbox/pkg/sass-parser/lib/src/interpolation.test.ts | xml | 2016-10-31T20:15:56 | 2024-08-16T17:16:45 | dart-sass | sass/dart-sass | 3,868 | 4,825 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/**
* Interface defining function options.
*/
interface Options {
/**
* The maximum number of pending invocations at any one time.
*/
limit?: number;
/**
* Boolean indicating whether to wait for a previous invocation to complete before invoking a provided function for the next own property (default: false).
*/
series?: boolean;
/**
* Execution context.
*/
thisArg?: any;
}
/**
* Callback invoked upon completion.
*/
type DoneNullary = () => void;
/**
* Callback invoked upon completion.
*
* @param error - encountered error or null
*/
type DoneUnary = ( error: Error | null ) => void;
/**
* Callback invoked upon completion.
*
* @param error - encountered error or null
* @param out - output object
*/
type DoneBinary = ( error: Error | null, out: any ) => void;
/**
* Callback invoked upon completion.
*
* @param error - encountered error or null
* @param out - output object
*/
type DoneCallback = DoneNullary | DoneUnary | DoneBinary;
/**
* Callback function.
*/
type Nullary = () => void;
/**
* Callback function.
*
* @param error - encountered error or null
*/
type Unary = ( error: Error | null ) => void;
/**
* Callback function.
*
* @param error - encountered error or null
* @param group - value group
*/
type Binary = ( error: Error | null, group: string ) => void;
/**
* Callback function.
*
* @param error - encountered error or null
* @param group - value group
*/
type Callback = Nullary | Unary | Binary;
/**
* Transform function.
*
* @param key - object key
* @param next - a callback to be invoked after processing an object `value`
*/
type BinaryTransform = ( value: any, next: Callback ) => void;
/**
* Transform function.
*
* @param key - object key
* @param value - object value corresponding to `key`
* @param next - a callback to be invoked after processing an object `value`
*/
type TernaryTransform = ( value: any, index: number, next: Callback ) => void;
/**
* Transform function.
*
* @param key - object key
* @param value - object value corresponding to `key`
* @param obj - the input object
* @param next - a callback to be invoked after processing an object `value`
*/
type QuaternaryTransform = ( value: any, index: number, obj: any, next: Callback ) => void;
/**
* Transform function.
*
* @param key - object key
* @param value - object value corresponding to `key`
* @param obj - the input object
* @param next - a callback to be invoked after processing an object `value`
*/
type Transform = Unary | BinaryTransform | TernaryTransform | QuaternaryTransform;
/**
* Maps keys from one object to a new object having the same values.
*
* @param obj - the input object
* @param done - function to invoke upon completion
*/
type FactoryFunction = ( obj: any, done: DoneCallback ) => void;
/**
* Interface for `mapValuesAsync`.
*/
interface MapValuesAsync {
/**
* Maps values from one object to a new object having the same keys.
*
* ## Notes
*
* - If a provided function calls the provided callback with a truthy error argument, the function suspends execution and immediately calls the `done` callback for subsequent error handling.
* - This function does **not** guarantee that execution is asynchronous. To do so, wrap the `done` callback in a function which either executes at the end of the current stack (e.g., `nextTick`) or during a subsequent turn of the event loop (e.g., `setImmediate`, `setTimeout`).
* - Iteration and insertion order are **not** guaranteed.
* - The function only operates on own properties, not inherited properties.
*
*
* @param obj - source object
* @param options - function options
* @param options.thisArg - execution context
* @param options.limit - maximum number of pending invocations at any one time
* @param options.series - boolean indicating whether to wait for a previous invocation to complete before invoking a provided function for the next own property (default: false)
* @param transform - transform function
* @param done - function to invoke upon completion
* @throws must provide valid options
*
* @example
* var stat = require( 'fs' ).stat;
*
* function getStats( file, next ) {
* stat( file, onStats );
*
* function onStats( error, data ) {
* if ( error ) {
* return next( error );
* }
* next( null, data );
* }
* }
*
* // Define a callback which handles errors:
* function done( error, out ) {
* if ( error ) {
* throw error;
* }
* console.log( out );
* }
*
* // Create a dictionary of file names:
* var files = {
* 'file1': './beep.js',
* 'file2': './boop.js'
* };
*
* var opts = {
* 'series': true
* };
*
* // Process each file in `files`:
* mapValuesAsync( files, opts, getStats, done );
*/
( obj: any, options: Options, transform: Transform, done: DoneCallback ): void;
/**
* Maps values from one object to a new object having the same keys.
*
* ## Notes
*
* - If a provided function calls the provided callback with a truthy error argument, the function suspends execution and immediately calls the `done` callback for subsequent error handling.
* - This function does **not** guarantee that execution is asynchronous. To do so, wrap the `done` callback in a function which either executes at the end of the current stack (e.g., `nextTick`) or during a subsequent turn of the event loop (e.g., `setImmediate`, `setTimeout`).
* - Iteration and insertion order are **not** guaranteed.
* - The function only operates on own properties, not inherited properties.
*
*
* @param obj - source object
* @param options - function options
* @param options.thisArg - execution context
* @param options.limit - maximum number of pending invocations at any one time
* @param options.series - boolean indicating whether to wait for a previous invocation to complete before invoking a provided function for the next own property (default: false)
* @param transform - transform function
* @param done - function to invoke upon completion
* @throws must provide valid options
*
* @example
* var stat = require( 'fs' ).stat;
*
* function getStats( file, next ) {
* stat( file, onStats );
*
* function onStats( error, data ) {
* if ( error ) {
* return next( error );
* }
* next( null, data );
* }
* }
*
* // Define a callback which handles errors:
* function done( error, out ) {
* if ( error ) {
* throw error;
* }
* console.log( out );
* }
*
* // Create a dictionary of file names:
* var files = {
* 'file1': './beep.js',
* 'file2': './boop.js'
* };
*
* // Process each file in `files`:
* mapValuesAsync( files, getStats, done );
*/
( obj: any, transform: Transform, done: DoneCallback ): void;
/**
* Returns a function to map values from one object to a new object having the same keys.
*
* ## Notes
*
* - If a provided function calls the provided callback with a truthy error argument, the function suspends execution and immediately calls the `done` callback for subsequent error handling.
* - This function does **not** guarantee that execution is asynchronous. To do so, wrap the `done` callback in a function which either executes at the end of the current stack (e.g., `nextTick`) or during a subsequent turn of the event loop (e.g., `setImmediate`, `setTimeout`).
* - Iteration and insertion order are **not** guaranteed.
* - The function only operates on own properties, not inherited properties.
*
*
* @param options - function options
* @param options.thisArg - execution context
* @param options.limit - maximum number of pending invocations at any one time
* @param options.series - boolean indicating whether to wait for a previous invocation to complete before invoking a provided function for the next own property (default: false)
* @param transform - transform function
* @throws must provide valid options
* @returns function which maps values from one object to a new object having the same keys
*
* @example
* var stat = require( 'fs' ).stat;
*
* function getStats( file, next ) {
* stat( file, onStats );
*
* function onStats( error, data ) {
* if ( error ) {
* return next( error );
* }
* next( null, data );
* }
* }
*
* var opts = {
* 'series': true
* };
*
* // Create a reusable function:
* var mapValuesAsync = factory( opts, getStats );
*
* // Create a dictionary of file names:
* var files = {
* 'file1': './beep.js',
* 'file2': './boop.js'
* };
*
* // Define a callback which handles errors:
* function done( error, out ) {
* if ( error ) {
* throw error;
* }
* console.log( out );
* }
*
* // Process each file in `files`:
* mapValuesAsync( files, done );
*/
factory( options: Options, transform: Transform ): FactoryFunction;
/**
* Returns a function to map values from one object to a new object having the same keys.
*
* ## Notes
*
* - If a provided function calls the provided callback with a truthy error argument, the function suspends execution and immediately calls the `done` callback for subsequent error handling.
* - This function does **not** guarantee that execution is asynchronous. To do so, wrap the `done` callback in a function which either executes at the end of the current stack (e.g., `nextTick`) or during a subsequent turn of the event loop (e.g., `setImmediate`, `setTimeout`).
* - Iteration and insertion order are **not** guaranteed.
* - The function only operates on own properties, not inherited properties.
*
*
* @param options - function options
* @param options.thisArg - execution context
* @param options.limit - maximum number of pending invocations at any one time
* @param options.series - boolean indicating whether to wait for a previous invocation to complete before invoking a provided function for the next own property (default: false)
* @param transform - transform function
* @throws must provide valid options
* @returns function which maps values from one object to a new object having the same keys
*
* @example
* var stat = require( 'fs' ).stat;
*
* function getStats( file, next ) {
* stat( file, onStats );
*
* function onStats( error, data ) {
* if ( error ) {
* return next( error );
* }
* next( null, data );
* }
* }
*
* // Create a reusable function:
* var mapValuesAsync = factory( getStats );
*
* // Create a dictionary of file names:
* var files = {
* 'file1': './beep.js',
* 'file2': './boop.js'
* };
*
* // Define a callback which handles errors:
* function done( error, out ) {
* if ( error ) {
* throw error;
* }
* console.log( out );
* }
*
* // Process each file in `files`:
* mapValuesAsync( files, done );
*/
factory( transform: Transform ): FactoryFunction;
}
/**
* Maps values from one object to a new object having the same keys.
*
* ## Notes
*
* - If a provided function calls the provided callback with a truthy error argument, the function suspends execution and immediately calls the `done` callback for subsequent error handling.
* - This function does **not** guarantee that execution is asynchronous. To do so, wrap the `done` callback in a function which either executes at the end of the current stack (e.g., `nextTick`) or during a subsequent turn of the event loop (e.g., `setImmediate`, `setTimeout`).
* - Iteration and insertion order are **not** guaranteed.
* - The function only operates on own properties, not inherited properties.
*
*
* @param obj - source object
* @param options - function options
* @param options.thisArg - execution context
* @param options.limit - maximum number of pending invocations at any one time
* @param options.series - boolean indicating whether to wait for a previous invocation to complete before invoking a provided function for the next own property (default: false)
* @param transform - transform function
* @param done - function to invoke upon completion
* @throws must provide valid options
*
* @example
* var stat = require( 'fs' ).stat;
*
* function getStats( file, next ) {
* stat( file, onStats );
*
* function onStats( error, data ) {
* if ( error ) {
* return next( error );
* }
* next( null, data );
* }
* }
*
* // Define a callback which handles errors:
* function done( error, out ) {
* if ( error ) {
* throw error;
* }
* console.log( out );
* }
*
* // Create a dictionary of file names:
* var files = {
* 'file1': './beep.js',
* 'file2': './boop.js'
* };
*
* var opts = {
* 'series': true
* };
*
* // Process each file in `files`:
* mapValuesAsync( files, opts, getStats, done );
*/
declare var mapValuesAsync: MapValuesAsync;
// EXPORTS //
export = mapValuesAsync;
``` | /content/code_sandbox/lib/node_modules/@stdlib/utils/async/map-values/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 3,341 |
```xml
/*
* Squidex Headless CMS
*
* @license
*/
import { booleanAttribute, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Input, numberAttribute, OnInit, Renderer2 } from '@angular/core';
import * as ProgressBar from 'progressbar.js';
import { TypedSimpleChanges } from '@app/framework/internal';
@Component({
standalone: true,
selector: 'sqx-progress-bar',
styles: [`
:host ::ng-deep svg {
vertical-align: middle
}`,
],
template: '',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProgressBarComponent implements OnInit {
private progressBar: any;
@Input()
public mode = 'Line';
@Input()
public color = '#3d7dd5';
@Input()
public trailColor = '#f4f4f4';
@Input({ transform: numberAttribute })
public trailWidth = 4;
@Input({ transform: numberAttribute })
public strokeWidth = 4;
@Input({ transform: booleanAttribute })
public showText?: boolean | null = true;
@Input({ transform: booleanAttribute })
public animated?: boolean | null = true;
@Input({ transform: numberAttribute })
public value = 0;
constructor(changeDetector: ChangeDetectorRef,
private readonly element: ElementRef,
private readonly renderer: Renderer2,
) {
changeDetector.detach();
}
public ngOnInit() {
const options = {
color: this.color,
trailColor: this.trailColor,
trailWidth: this.trailWidth,
strokeWidth: this.strokeWidth,
svgStyle: { width: '100%', height: '100%' },
};
this.renderer.setStyle(this.element.nativeElement, 'display', 'block');
if (this.mode === 'Circle') {
this.progressBar = new ProgressBar.Circle(this.element.nativeElement, options);
} else {
this.progressBar = new ProgressBar.Line(this.element.nativeElement, options);
}
this.updateValue();
}
public ngOnChanges(changes: TypedSimpleChanges<this>) {
if (this.progressBar && changes.value) {
this.updateValue();
}
}
private updateValue() {
const value = this.value;
if (this.animated) {
this.progressBar.animate(value / 100);
} else {
this.progressBar.set(value / 100);
}
if (value > 0 && this.showText) {
this.progressBar.setText(`${Math.round(value)}%`);
}
}
}
``` | /content/code_sandbox/frontend/src/app/framework/angular/forms/progress-bar.component.ts | xml | 2016-08-29T05:53:40 | 2024-08-16T17:39:38 | squidex | Squidex/squidex | 2,222 | 531 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="path_to_url"
android:shape="rectangle"
android:visible="true">
<gradient
android:angle="270"
android:startColor="#1a5b92"
android:endColor="#2c4253" />
</shape>
``` | /content/code_sandbox/app/src/main/res/drawable/weather_background_hail_night.xml | xml | 2016-02-21T04:39:19 | 2024-08-16T13:35:51 | GeometricWeather | WangDaYeeeeee/GeometricWeather | 2,420 | 75 |
```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="M7.5 4L7.5 4L7.5 5L4 5C3 5 2 6 2 7L2 9L1.5 9C1.25 9 1 9.25 1 9.5L1 10L5 10L5 9.5C5 9.25 4.75 9 4.5 9L4 9L4 7C4 7 5.67 7 7 7L7 13L4.5 13C4.25 13 4 13.25 4 13.5L4 14L12 14L12 13.5C12 13.25 11.75 13 11.5 13L9 13L9 5L9 4C9 4 11 4 11 7C11 10 14 11 14 11L14 9.5C14 9.5 12 9 12 6C12 1 8.5 1 7.5 1C7.5 1 7.5 1 7.5 1L7.5 1C6.67 1 6 1.67 6 2.5L6 2.5C6 3.33 6.67 4 7.5 4Z"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_preset_temaki_well_pump_manual.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 388 |
```xml
/* eslint-disable max-classes-per-file */
export class BaseError extends Error {
logged: boolean;
constructor(message?: string, error?: Error) {
let errMessage = message;
if (error && !message) {
errMessage = error.message;
}
super(errMessage);
// Use error param stacktrace if provided and add error class name
if (error && error.stack) {
this.stack = error.stack;
}
this.stack = this.stack.replace(/^(Error)/, `$1 (${this.constructor.name})`);
// Set logged flag to default value
this.logged = false;
}
}
export class AmbiguousSyncRequestError extends BaseError {}
export class AndroidError extends BaseError {}
export class ApiRequestError extends BaseError {}
export class ArgumentError extends BaseError {}
export class BookmarkMappingNotFoundError extends BaseError {}
export class BookmarkNotFoundError extends BaseError {}
export class ContainerChangedError extends BaseError {}
export class ContainerNotFoundError extends BaseError {}
export class DailyNewSyncLimitReachedError extends BaseError {}
export class DataOutOfSyncError extends BaseError {}
export class FailedGetNativeBookmarksError extends BaseError {}
export class FailedCreateNativeBookmarksError extends BaseError {}
export class FailedDownloadFileError extends BaseError {}
export class FailedGetDataToRestoreError extends BaseError {}
export class FailedGetPageMetadataError extends BaseError {}
export class FailedLocalStorageError extends BaseError {}
export class FailedRefreshBookmarksError extends BaseError {}
export class FailedRegisterAutoUpdatesError extends BaseError {}
export class FailedRemoveNativeBookmarksError extends BaseError {}
export class FailedRestoreDataError extends BaseError {}
export class FailedSaveBackupError extends BaseError {}
export class FailedScanError extends BaseError {}
export class FailedShareBookmarkError extends BaseError {}
export class FailedShareUrlError extends BaseError {}
export class FailedShareUrlNotSyncedError extends BaseError {}
export class FailedUpdateNativeBookmarksError extends BaseError {}
export class HttpRequestAbortedError extends BaseError {}
export class HttpRequestFailedError extends BaseError {}
export class HttpRequestTimedOutError extends BaseError {}
export class I18nError extends BaseError {}
export class IncompleteSyncInfoError extends BaseError {}
export class InvalidBookmarkIdsError extends BaseError {}
export class InvalidCredentialsError extends BaseError {}
export class InvalidServiceError extends BaseError {}
export class InvalidSyncInfoError extends BaseError {}
export class NativeBookmarkNotFoundError extends BaseError {}
export class LocalStorageNotAvailableError extends BaseError {}
export class NetworkConnectionError extends BaseError {}
export class NotAcceptingNewSyncsError extends BaseError {}
export class RequestEntityTooLargeError extends BaseError {}
export class ServiceOfflineError extends BaseError {}
export class SyncDisabledError extends BaseError {}
export class SyncFailedError extends BaseError {}
export class SyncNotFoundError extends BaseError {}
export class SyncUncommittedError extends BaseError {}
export class SyncVersionNotSupportedError extends BaseError {}
export class TooManyRequestsError extends BaseError {}
export class UnexpectedResponseDataError extends BaseError {}
export class UnsupportedApiVersionError extends BaseError {}
export class UpgradeFailedError extends BaseError {}
``` | /content/code_sandbox/src/modules/shared/errors/errors.ts | xml | 2016-05-05T20:59:25 | 2024-08-13T14:13:34 | app | xbrowsersync/app | 1,478 | 635 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<com.ldoublem.loadingviewlib.view.LVRingProgress
android:id="@+id/lv_ringp"
android:layout_width="260dp"
android:layout_height="260dp"
android:layout_marginTop="25dp"
></com.ldoublem.loadingviewlib.view.LVRingProgress>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="automatic"
android:text="automatic"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="byuser"
android:text="byuser"/>
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/layout_test.xml | xml | 2016-06-21T07:54:32 | 2024-08-07T08:00:34 | LoadingView | ldoublem/LoadingView | 2,727 | 202 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import FLOAT64_MAX_BASE10_EXPONENT_SUBNORMAL = require( './index' );
// TESTS //
// The export is a number...
{
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
FLOAT64_MAX_BASE10_EXPONENT_SUBNORMAL; // $ExpectType number
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/constants/float64/max-base10-exponent-subnormal/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 111 |
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC" customClass="LYOpenGLView">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
<simulatedScreenMetrics key="simulatedDestinationMetrics" type="retina47"/>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
``` | /content/code_sandbox/Demo04-VR全景视频播放/LearnOpenGLES/Base.lproj/Main.storyboard | xml | 2016-03-11T07:58:04 | 2024-08-16T03:42:56 | LearnOpenGLES | loyinglin/LearnOpenGLES | 1,618 | 400 |
```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="de" original="../VBScriptingResources.resx">
<body>
<trans-unit id="LogoLine1">
<source>Microsoft (R) Visual Basic Interactive Compiler version {0}</source>
<target state="translated">Microsoft (R) Visual Basic interaktive Compilerversion {0}</target>
<note />
</trans-unit>
<trans-unit id="LogoLine2">
<note />
</trans-unit>
<trans-unit id="InteractiveHelp">
<source>Usage: vbi [options] [script-file.vbx] [-- script-arguments]
If script-file is specified executes the script, otherwise launches an interactive REPL (Read Eval Print Loop).
Options:
/help Display this usage message (Short form: /?)
/version Display the version and exit
/reference:<alias>=<file> Reference metadata from the specified assembly file using the given alias (Short form: /r)
/reference:<file list> Reference metadata from the specified assembly files (Short form: /r)
/referencePath:<path list> List of paths where to look for metadata references specified as unrooted paths. (Short form: /rp)
/using:<namespace> Define global namespace using (Short form: /u)
/define:<name>=<value>,... Declare global conditional compilation symbol(s) (Short form: /d)
@<file> Read response file for more options
</source>
<target state="translated">Syntax: vbi [optionen] [script-file.vbx] [-- script-arguments]
Bei Angabe von script-file wird das Skript ausgefhrt. Andernfalls wird eine interaktive REPL (readevalprint-Loop) gestartet.
Optionen:
/help Anzeige dieser Syntaxmeldung (Kurzform: /?)
/version Anzeige der Version und Beendigung
/reference:<alias>=<datei> Verweis auf Metadaten aus der angegebenen Assemblydatei ber den angegebenen Alias (Kurzform: /r)
/reference:<dateiliste> Verweis auf Metadaten aus den angegebenen Assemblydateien (Kurzform: /r)
/referencePath:<pfadliste> Liste von Pfaden, in denen nach Metadatenverweisen gesucht wird, ohne Angabe des Stammverzeichnisses (Kurzform: /rp)
/using:<namespace> Definition eines globalen Namespace mit "using" (Kurzform: /u)
/define:<name>=<wert>,... Deklaration globaler Symbole fr die bedingte Kompilierung (Kurzform: /d)
@<datei> Lesen der Antwortdatei mit weiteren Optionen
</target>
<note />
</trans-unit>
<trans-unit id="ExceptionEscapeWithoutQuote">
<source>Cannot escape non-printable characters in Visual Basic notation unless quotes are used.</source>
<target state="translated">Nicht druckbare Zeichen knnen in der Visual Basic-Notation nur mit Escapezeichen versehen werden, wenn Anfhrungszeichen verwendet werden.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/VisualBasic/xlf/VBScriptingResources.de.xlf | xml | 2016-08-25T20:07:20 | 2024-08-13T22:23:35 | CoreWF | UiPath/CoreWF | 1,126 | 866 |
```xml
<dict>
<key>LayoutID</key>
<integer>13</integer>
<key>PathMapRef</key>
<array>
<dict>
<key>CodecID</key>
<array>
<integer>283902549</integer>
</array>
<key>Headphone</key>
<dict/>
<key>Inputs</key>
<array>
<string>Mic</string>
<string>LineIn</string>
</array>
<key>IntSpeaker</key>
<dict>
<key>DefaultVolume</key>
<integer>4293722112</integer>
<key>MaximumBootBeepValue</key>
<integer>64</integer>
<key>MuteGPIO</key>
<integer>0</integer>
<key>SignalProcessing</key>
<dict>
<key>SoftwareDSP</key>
<dict>
<key>DspFunction0</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>0</integer>
<key>DspFuncName</key>
<string>DspEqualization</string>
<key>DspFuncProcessingIndex</key>
<integer>0</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>Filter</key>
<array>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>1</integer>
<key>6</key>
<integer>1121130925</integer>
<key>7</key>
<integer>1062181913</integer>
<key>8</key>
<integer>-1051960877</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>1</integer>
<key>6</key>
<integer>1121437227</integer>
<key>7</key>
<integer>1062181913</integer>
<key>8</key>
<integer>-1052549551</integer>
</dict>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>1</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1147243075</integer>
<key>7</key>
<integer>1069052072</integer>
<key>8</key>
<integer>-1059648963</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>1</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1147243075</integer>
<key>7</key>
<integer>1069052072</integer>
<key>8</key>
<integer>-1059648963</integer>
</dict>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>2</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1153510794</integer>
<key>7</key>
<integer>1079650306</integer>
<key>8</key>
<integer>0</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>2</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1153270572</integer>
<key>7</key>
<integer>1074610652</integer>
<key>8</key>
<integer>-1062064882</integer>
</dict>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>3</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1163795438</integer>
<key>7</key>
<integer>1076603811</integer>
<key>8</key>
<integer>0</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>3</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1163927873</integer>
<key>7</key>
<integer>1076557096</integer>
<key>8</key>
<integer>-1067488498</integer>
</dict>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>4</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>5</integer>
<key>6</key>
<integer>1165447446</integer>
<key>7</key>
<integer>1093664768</integer>
<key>8</key>
<integer>-1094411354</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>4</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>5</integer>
<key>6</key>
<integer>1137180672</integer>
<key>7</key>
<integer>1093664768</integer>
<key>8</key>
<integer>-1095204569</integer>
</dict>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>5</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>1</integer>
<key>6</key>
<integer>1120722521</integer>
<key>7</key>
<integer>1060714809</integer>
<key>8</key>
<integer>-1064028699</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>5</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>1</integer>
<key>6</key>
<integer>1120926723</integer>
<key>7</key>
<integer>1060714809</integer>
<key>8</key>
<integer>-1079922904</integer>
</dict>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>6</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1125212588</integer>
<key>7</key>
<integer>1062958591</integer>
<key>8</key>
<integer>-1070587707</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>6</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1125238907</integer>
<key>7</key>
<integer>1062998322</integer>
<key>8</key>
<integer>-1071124578</integer>
</dict>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>7</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1122038312</integer>
<key>7</key>
<integer>1074440875</integer>
<key>8</key>
<integer>-1061498991</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>7</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1121924912</integer>
<key>7</key>
<integer>1074271873</integer>
<key>8</key>
<integer>-1061498991</integer>
</dict>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>8</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1128612513</integer>
<key>7</key>
<integer>1079014663</integer>
<key>8</key>
<integer>-1059382945</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>8</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1126665806</integer>
<key>7</key>
<integer>1087746943</integer>
<key>8</key>
<integer>-1063010452</integer>
</dict>
<dict>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>9</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>6</integer>
<key>6</key>
<integer>1157720978</integer>
<key>7</key>
<integer>1103101952</integer>
<key>8</key>
<integer>-1076613600</integer>
</dict>
<dict>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>9</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>6</integer>
<key>6</key>
<integer>1157720978</integer>
<key>7</key>
<integer>1103393070</integer>
<key>8</key>
<integer>-1076613600</integer>
</dict>
</array>
</dict>
<key>PatchbayInfo</key>
<dict/>
</dict>
<key>DspFunction1</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>1</integer>
<key>DspFuncName</key>
<string>DspVirtualization</string>
<key>DspFuncProcessingIndex</key>
<integer>1</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>10</key>
<integer>0</integer>
<key>11</key>
<integer>1</integer>
<key>12</key>
<integer>-1060850508</integer>
<key>13</key>
<integer>-1038329254</integer>
<key>14</key>
<integer>10</integer>
<key>15</key>
<integer>210</integer>
<key>16</key>
<integer>-1049408692</integer>
<key>17</key>
<integer>5</integer>
<key>18</key>
<integer>182</integer>
<key>19</key>
<integer>418</integer>
<key>2</key>
<integer>-1082130432</integer>
<key>20</key>
<integer>-1038976903</integer>
<key>21</key>
<integer>3</integer>
<key>22</key>
<integer>1633</integer>
<key>23</key>
<integer>4033</integer>
<key>24</key>
<integer>-1046401747</integer>
<key>25</key>
<integer>4003</integer>
<key>26</key>
<integer>9246</integer>
<key>27</key>
<integer>168</integer>
<key>28</key>
<integer>1060875180</integer>
<key>29</key>
<integer>0</integer>
<key>3</key>
<integer>-1085584568</integer>
<key>30</key>
<integer>-1048128813</integer>
<key>31</key>
<integer>982552730</integer>
<key>32</key>
<integer>16</integer>
<key>33</key>
<integer>-1063441106</integer>
<key>34</key>
<integer>1008902816</integer>
<key>35</key>
<integer>4</integer>
<key>36</key>
<integer>-1059986974</integer>
<key>37</key>
<integer>0</integer>
<key>38</key>
<integer>234</integer>
<key>39</key>
<integer>1</integer>
<key>4</key>
<integer>-1094466626</integer>
<key>40</key>
<integer>-1047912930</integer>
<key>41</key>
<integer>1022423360</integer>
<key>42</key>
<integer>0</integer>
<key>43</key>
<data>your_sha512_hash/PoLzKPoE9VliZvVAiGD1DUa692FG0PaD8kb1s7dW8Cvd1P4AH1rx9+your_sha256_hasheu8wK0EvN4bnzwcZ4o8XuerPN1Lhzk6gfk7OnQgvG5lGrzURc+8ogiRvJL8ELwRvBg8qQGUPM4QWzzNMaQ7QlzSu3iKYbsKSbK7kk/tuhTxlruJRKu6DVSwORAuiLrWfoA6Hp+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAAAAAAAACasrC7Y0/Tu/+3lLv0l7I5r0STO4dM6DtPRRM8zbj/O+Y2ijtWlU67mDwmvK2+GLyKIpu7Sp34um8TZDkTvp+7UZuaOWcGRTrf22i7D3MfPOY9aTyK8oA94CaQPc3Y2z0d9Ik+N3BQPv60hz28u6M975E8PZYjDT2eVgk9Xp1GPfiKqz3S4U49E7QoPZLzJj3+XNg8D5bCPMiRlTyuLAM9dBEcPTXIDT0m1xE9o7/NPE+Cazye/qw7Xhdjuyen1LtqMOG7/Eo9uxlBXDt1St07kpvdO/gnTjt2Fp+your_sha256_hash7lxMiOe/WVDsBH407KMBOO9ILWDn1ciO7L+CmuyDt3bue4My7DhNpu0im9jqJ+8E7SMSkOz/fcTuD/q46618ZO3WrlDvWWeQ6c5P0O7L/zjvkHyw8jTzBO4rc27wJi9C8CA22vV/your_sha256_hashn3rzvEbC8mcWGvHkexLz8tKu86dpLvOicNbzF2eK7zCAvu2TPYTpu+pw7oyjHO5aduDv60iA7afr8uq46j7sjqZK7q6Aeuxms8bjz6Ks6MH/your_sha256_hashyour_sha256_hashuvdhRtD2g/JG9bO3VvAr3dT+AB9a8ffmRvYRgtD2DIq69OpUYPa0bmb0oX4E9Cs+your_sha256_hash5Ozp0ILxuZRq81EXPvKIIkbyS/your_sha256_hashoi61n6AOh6fmTg=</data>
<key>5</key>
<integer>-1056748724</integer>
<key>6</key>
<integer>0</integer>
<key>7</key>
<integer>0</integer>
<key>8</key>
<integer>0</integer>
<key>9</key>
<integer>0</integer>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
<key>DspFunction2</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>1</integer>
<key>DspFuncName</key>
<string>DspMultibandDRC</string>
<key>DspFuncProcessingIndex</key>
<integer>1</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>Crossover</key>
<dict>
<key>4</key>
<integer>2</integer>
<key>5</key>
<integer>0</integer>
<key>6</key>
<integer>1143079818</integer>
</dict>
<key>Limiter</key>
<array>
<dict>
<key>10</key>
<integer>-1058198226</integer>
<key>11</key>
<integer>1094651663</integer>
<key>12</key>
<integer>-1047897509</integer>
<key>13</key>
<integer>1067573730</integer>
<key>14</key>
<integer>-1027604480</integer>
<key>15</key>
<integer>1065353216</integer>
<key>16</key>
<integer>1065353216</integer>
<key>17</key>
<integer>1073741824</integer>
<key>18</key>
<integer>1103811283</integer>
<key>19</key>
<integer>1086830520</integer>
<key>2</key>
<integer>1</integer>
<key>20</key>
<integer>1137180672</integer>
<key>21</key>
<integer>0</integer>
<key>22</key>
<integer>0</integer>
<key>23</key>
<integer>1</integer>
<key>3</key>
<integer>0</integer>
<key>7</key>
<integer>0</integer>
<key>8</key>
<integer>0</integer>
<key>9</key>
<integer>-1096637784</integer>
</dict>
<dict>
<key>10</key>
<integer>-1060418742</integer>
<key>11</key>
<integer>1086941546</integer>
<key>12</key>
<integer>-1047786484</integer>
<key>13</key>
<integer>1067919143</integer>
<key>14</key>
<integer>-1027604480</integer>
<key>15</key>
<integer>1065353216</integer>
<key>16</key>
<integer>1065353216</integer>
<key>17</key>
<integer>1073741824</integer>
<key>18</key>
<integer>1111814385</integer>
<key>19</key>
<integer>1101004800</integer>
<key>2</key>
<integer>2</integer>
<key>20</key>
<integer>1137180672</integer>
<key>21</key>
<integer>0</integer>
<key>22</key>
<integer>0</integer>
<key>23</key>
<integer>1</integer>
<key>3</key>
<integer>0</integer>
<key>7</key>
<integer>0</integer>
<key>8</key>
<integer>0</integer>
<key>9</key>
<integer>-1099105016</integer>
</dict>
</array>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
</dict>
</dict>
</dict>
<key>LineIn</key>
<dict>
<key>MuteGPIO</key>
<integer>1342242840</integer>
<key>SignalProcessing</key>
<dict>
<key>SoftwareDSP</key>
<dict>
<key>DspFunction0</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>0</integer>
<key>DspFuncName</key>
<string>DspNoiseReduction</string>
<key>DspFuncProcessingIndex</key>
<integer>0</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>-1073029587</integer>
<key>5</key>
<data>your_sha256_hashHMuYwrl9lcJXm4/CBhmQwuJvlMKbxJTC7qyUwtjDl8KU+ZzCnCaewsmuncK/your_sha512_hash+your_sha256_hashyour_sha256_hashfwhFzosLIZaPCwUOjwo6TosIkR6LC6vehwtrwosIdtJ/CXLmbwlSZmcKDhJXCDFGRwnV6j8JTjY/CrqGQwgqYk8INzpjCuTufwrjlocKviKPC5YqlwgdmpcKZ2aXCGiumwq95osJOIJ/Cxl+ewtWGl8KmPJPC+sSawkdHo8JWB6LCskyhwqk7pcIth6nCh4Wswk+crcK9J6zCYJWqwmVJq8K8063Cyour_sha512_hash+M0MKaftbCpcjdwm+p5sL/CfHCHcT8wrp3A8PiJAzD</data>
</dict>
<key>PatchbayInfo</key>
<dict/>
</dict>
<key>DspFunction1</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>1</integer>
<key>DspFuncName</key>
<string>DspGainStage</string>
<key>DspFuncProcessingIndex</key>
<integer>1</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>1078616770</integer>
<key>3</key>
<integer>1078616770</integer>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
<key>DspFunction2</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>2</integer>
<key>DspFuncName</key>
<string>DspEqualization</string>
<key>DspFuncProcessingIndex</key>
<integer>2</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>Filter</key>
<array>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>1</integer>
<key>6</key>
<integer>1132560510</integer>
<key>7</key>
<integer>1064190664</integer>
<key>8</key>
<integer>-1057196819</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>8</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1150544383</integer>
<key>7</key>
<integer>1068848526</integer>
<key>8</key>
<integer>-1073422534</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>15</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>0</integer>
<key>6</key>
<integer>1182094222</integer>
<key>7</key>
<integer>1063679547</integer>
<key>8</key>
<integer>-1048213171</integer>
</dict>
</array>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
<key>DspFunction3</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>3</integer>
<key>DspFuncName</key>
<string>DspMultibandDRC</string>
<key>DspFuncProcessingIndex</key>
<integer>3</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>Crossover</key>
<dict>
<key>4</key>
<integer>1</integer>
<key>5</key>
<integer>0</integer>
<key>6</key>
<integer>1128792064</integer>
</dict>
<key>Limiter</key>
<array>
<dict>
<key>10</key>
<integer>-1068807345</integer>
<key>11</key>
<integer>1097982434</integer>
<key>12</key>
<integer>-1038380141</integer>
<key>13</key>
<integer>1068906038</integer>
<key>14</key>
<integer>-1036233644</integer>
<key>15</key>
<integer>1065353216</integer>
<key>16</key>
<integer>1101004800</integer>
<key>17</key>
<integer>1101004800</integer>
<key>18</key>
<integer>1128792064</integer>
<key>19</key>
<integer>1101004800</integer>
<key>2</key>
<integer>1</integer>
<key>20</key>
<integer>1127866850</integer>
<key>21</key>
<integer>0</integer>
<key>22</key>
<integer>0</integer>
<key>23</key>
<integer>1</integer>
<key>3</key>
<integer>0</integer>
<key>7</key>
<integer>0</integer>
<key>8</key>
<integer>0</integer>
<key>9</key>
<integer>0</integer>
</dict>
</array>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>2</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>2</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
</dict>
</dict>
</dict>
<key>Mic</key>
<dict>
<key>MuteGPIO</key>
<integer>1342242843</integer>
<key>SignalProcessing</key>
<dict>
<key>SoftwareDSP</key>
<dict>
<key>DspFunction0</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>0</integer>
<key>DspFuncName</key>
<string>DspNoiseReduction</string>
<key>DspFuncProcessingIndex</key>
<integer>0</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>-1073029587</integer>
<key>5</key>
<data>your_sha256_hashHMuYwrl9lcJXm4/CBhmQwuJvlMKbxJTC7qyUwtjDl8KU+ZzCnCaewsmuncK/your_sha512_hash+your_sha256_hashyour_sha256_hashfwhFzosLIZaPCwUOjwo6TosIkR6LC6vehwtrwosIdtJ/CXLmbwlSZmcKDhJXCDFGRwnV6j8JTjY/CrqGQwgqYk8INzpjCuTufwrjlocKviKPC5YqlwgdmpcKZ2aXCGiumwq95osJOIJ/Cxl+ewtWGl8KmPJPC+sSawkdHo8JWB6LCskyhwqk7pcIth6nCh4Wswk+crcK9J6zCYJWqwmVJq8K8063Cyour_sha512_hash+M0MKaftbCpcjdwm+p5sL/CfHCHcT8wrp3A8PiJAzD</data>
</dict>
<key>PatchbayInfo</key>
<dict/>
</dict>
<key>DspFunction1</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>1</integer>
<key>DspFuncName</key>
<string>DspGainStage</string>
<key>DspFuncProcessingIndex</key>
<integer>1</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>1078616770</integer>
<key>3</key>
<integer>1078616770</integer>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
<key>DspFunction2</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>2</integer>
<key>DspFuncName</key>
<string>DspEqualization</string>
<key>DspFuncProcessingIndex</key>
<integer>2</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>Filter</key>
<array>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>1</integer>
<key>6</key>
<integer>1132560510</integer>
<key>7</key>
<integer>1064190664</integer>
<key>8</key>
<integer>-1057196819</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>8</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1150544383</integer>
<key>7</key>
<integer>1068848526</integer>
<key>8</key>
<integer>-1073422534</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>15</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>0</integer>
<key>6</key>
<integer>1182094222</integer>
<key>7</key>
<integer>1063679547</integer>
<key>8</key>
<integer>-1048213171</integer>
</dict>
</array>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
<key>DspFunction3</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>3</integer>
<key>DspFuncName</key>
<string>DspMultibandDRC</string>
<key>DspFuncProcessingIndex</key>
<integer>3</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>Crossover</key>
<dict>
<key>4</key>
<integer>1</integer>
<key>5</key>
<integer>0</integer>
<key>6</key>
<integer>1128792064</integer>
</dict>
<key>Limiter</key>
<array>
<dict>
<key>10</key>
<integer>-1068807345</integer>
<key>11</key>
<integer>1097982434</integer>
<key>12</key>
<integer>-1038380141</integer>
<key>13</key>
<integer>1068906038</integer>
<key>14</key>
<integer>-1036233644</integer>
<key>15</key>
<integer>1065353216</integer>
<key>16</key>
<integer>1101004800</integer>
<key>17</key>
<integer>1101004800</integer>
<key>18</key>
<integer>1128792064</integer>
<key>19</key>
<integer>1101004800</integer>
<key>2</key>
<integer>1</integer>
<key>20</key>
<integer>1127866850</integer>
<key>21</key>
<integer>0</integer>
<key>22</key>
<integer>0</integer>
<key>23</key>
<integer>1</integer>
<key>3</key>
<integer>0</integer>
<key>7</key>
<integer>0</integer>
<key>8</key>
<integer>0</integer>
<key>9</key>
<integer>0</integer>
</dict>
</array>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>2</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>2</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
</dict>
</dict>
</dict>
<key>Outputs</key>
<array>
<string>Headphone</string>
<string>IntSpeaker</string>
</array>
<key>PathMapID</key>
<integer>255</integer>
</dict>
</array>
</dict>
``` | /content/code_sandbox/Resources/ALC255/layout13.xml | xml | 2016-03-07T20:45:58 | 2024-08-14T08:57:03 | AppleALC | acidanthera/AppleALC | 3,420 | 11,679 |
```xml
import * as React from 'react';
// @ts-ignore
import { Persona, IPersonaSharedProps } from 'office-ui-fabric-react/lib/Persona';
// @ts-ignore
import { IRenderFunction } from 'office-ui-fabric-react/lib/Utilities';
const renderCoin: IRenderFunction<IPersonaSharedProps> = (props: IPersonaSharedProps | undefined) => {
return <div>Foo</div>;
};
export const RenderPersona = (props: any) => {
return (
<div>
<Persona onRenderCoin={renderCoin} primaryText={'PersonaName'}>
Persona
</Persona>
{/* include self closing persona check */}
<Persona primaryText={'PersonaName'} onRenderCoin={renderCoin} />
</div>
);
};
``` | /content/code_sandbox/packages/codemods/src/codeMods/tests/mock/persona/mPersonaProps.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 169 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.Core" Version="3.7.11.14" />
<PackageReference Include="AWSSDK.DynamoDBv2" Version="3.7.3.46" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="moviedata.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
``` | /content/code_sandbox/dotnetv3/dynamodb/scenarios/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario/PartiQL_Basics_Scenario.csproj | xml | 2016-08-18T19:06:57 | 2024-08-16T18:59:44 | aws-doc-sdk-examples | awsdocs/aws-doc-sdk-examples | 9,298 | 181 |
```xml
import { ViewColumn, ViewEntity } from "../../../../src"
@ViewEntity({
expression: `
select * from test_entity -- V1 simlate view change with comment
`,
})
export class ViewB {
@ViewColumn()
id: number
@ViewColumn()
type: string
}
``` | /content/code_sandbox/test/github-issues/7586/entity/ViewB.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 66 |
```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.
-->
<launch>
<param name="/use_sim_time" value="true" />
<param name="robot_description"
textfile="$(find cartographer_ros)/urdf/backpack_2d.urdf" />
<node name="robot_state_publisher" pkg="robot_state_publisher"
type="robot_state_publisher" />
<node name="cartographer_grpc_server" pkg="cartographer_ros"
type="cartographer_grpc_server.sh" args="
-configuration_directory $(find cartographer_ros)/configuration_files
-configuration_basename backpack_2d_server.lua">
</node>
<node name="cartographer_grpc_node" pkg="cartographer_ros"
type="cartographer_grpc_node" args="
-client_id CLIENT_ID
-configuration_directory $(find cartographer_ros)/configuration_files
-configuration_basename backpack_2d.lua"
output="screen">
<remap from="echoes" to="horizontal_laser_2d" />
</node>
<node name="playbag" pkg="rosbag" type="play"
args="--clock $(arg bag_filename)" />
<node name="rviz" pkg="rviz" type="rviz" required="true"
args="-d $(find cartographer_ros)/configuration_files/demo_2d.rviz" />
</launch>
``` | /content/code_sandbox/cartographer_ros/launch/grpc_demo_backpack_2d.launch | xml | 2016-08-03T10:43:23 | 2024-08-15T23:40:22 | cartographer_ros | cartographer-project/cartographer_ros | 1,628 | 320 |
```xml
export * from './OverlayDrawerSurface';
export * from './OverlayDrawerSurface.types';
``` | /content/code_sandbox/packages/react-components/react-drawer/library/src/components/OverlayDrawer/OverlayDrawerSurface/index.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 18 |
```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<CodeAnalysisRuleSet />
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<CodeAnalysisRuleSet />
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Bot.Builder.Community.Dialogs.FormFlow" Version="4.3.45" />
<PackageReference Include="log4net" Version="2.0.8" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.Bot.Builder.Dialogs" Version="4.4.4" />
<PackageReference Include="Microsoft.Bot.Builder.Integration.AspNet.Core" Version="4.4.3" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.1" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/Migration/MigrationV3V4/CSharp/ContosoHelpdeskChatBot-V4NetCore/ContosoHelpdeskChatBot/ContosoHelpdeskChatBot.csproj | xml | 2016-09-20T16:17:28 | 2024-08-16T02:44:00 | BotBuilder-Samples | microsoft/BotBuilder-Samples | 4,323 | 256 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"path_to_url">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
<property name="hibernate.connection.username">pankaj</property>
<property name="hibernate.connection.password">pankaj123</property>
<!-- Connection Pool Size -->
<property name="hibernate.connection.pool_size">1</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Outputs the SQL queries, should be disabled in Production -->
<property name="hibernate.show_sql">true</property>
<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- mapping file, we can use Bean annotations too -->
<mapping resource="employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
``` | /content/code_sandbox/Hibernate/HibernateExample/src/main/resources/hibernate.cfg.xml | xml | 2016-05-02T05:43:21 | 2024-08-16T06:51:39 | journaldev | WebJournal/journaldev | 1,314 | 373 |
```xml
/*
* path_to_url
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
*/
import { expect } from 'chai';
import { AttributesManagerFactory } from '../../lib/attributes/AttributesManagerFactory';
import { JsonProvider } from '../mocks/JsonProvider';
import { MockPersistenceAdapter } from '../mocks/persistence/MockPersistenceAdapter';
describe('AttributesManagerFactory', () => {
it('should throw an error when RequestEnvelope is null or undefined', () => {
try {
AttributesManagerFactory.init({requestEnvelope : null});
} catch (error) {
expect(error.name).eq('AskSdk.AttributesManagerFactory Error');
expect(error.message).eq('RequestEnvelope cannot be null or undefined!');
return;
}
throw new Error('should have thrown an error');
});
it('should be able to get session attributes from in session request envelope', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.session.attributes = {mockKey : 'mockValue'};
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
expect(defaultAttributesManager.getSessionAttributes()).deep.equal({mockKey : 'mockValue'});
});
it('should be able to get default session attributes from new session request envelope', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
expect(defaultAttributesManager.getSessionAttributes()).deep.equal({});
});
it('should throw an error when trying to get session attributes from out of session request envelope', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.session = undefined;
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
defaultAttributesManager.getSessionAttributes();
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot get SessionAttributes from out of session request!');
return;
}
throw new Error('should have thrown an error!');
});
it('should get default attributes when db has no attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : new MockPersistenceAdapter(),
requestEnvelope,
});
await defaultAttributesManager.deletePersistentAttributes();
expect(await defaultAttributesManager.getPersistentAttributes(true, {
key_1: 'v1', /* eslint-disable-line camelcase */
})).deep.equal({
key_1 : 'v1', /* eslint-disable-line camelcase */
});
});
it('should be able to get persistent attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : new MockPersistenceAdapter(),
requestEnvelope,
});
expect(await defaultAttributesManager.getPersistentAttributes()).deep.equal({
key_1 : 'v1', /* eslint-disable-line camelcase */
key_2 : 'v2', /* eslint-disable-line camelcase */
state : 'mockState',
});
});
it('should throw an error when trying to get persistent attributes without persistence adapter', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
await defaultAttributesManager.getPersistentAttributes();
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot get PersistentAttributes without PersistenceManager');
return;
}
throw new Error('should have thrown an error!');
});
it('should be able to get initial request attributes', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
expect(defaultAttributesManager.getRequestAttributes()).deep.equal({});
});
it('should be able to set session attributes', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.session.attributes = {mockKey : 'mockValue'};
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
expect(defaultAttributesManager.getSessionAttributes()).deep.equal({mockKey : 'mockValue'});
defaultAttributesManager.setSessionAttributes({updatedKey : 'UpdatedValue'});
expect(defaultAttributesManager.getSessionAttributes()).deep.equal({updatedKey : 'UpdatedValue'});
});
it('should throw an error when trying to set session attributes to out of session request envelope', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.session = undefined;
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
defaultAttributesManager.setSessionAttributes({key : 'value'});
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot set SessionAttributes to out of session request!');
return;
}
throw new Error('should have thrown an error!');
});
it('should be able to set persistent attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : new MockPersistenceAdapter(),
requestEnvelope,
});
defaultAttributesManager.setPersistentAttributes({key : 'value'});
expect(await defaultAttributesManager.getPersistentAttributes()).deep.equal({key : 'value'});
});
it('should throw an error when trying to set persistent attributes without persistence adapter', () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
defaultAttributesManager.setPersistentAttributes({key : 'value'});
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot set PersistentAttributes without persistence adapter!');
return;
}
throw new Error('should have thrown an error!');
});
it('should be able to delete persistent attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const mockPersistenceAdapter = new MockPersistenceAdapter();
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
expect(await defaultAttributesManager.getPersistentAttributes()).deep.equal({
key_1 : 'v1', /* eslint-disable-line camelcase */
key_2 : 'v2', /* eslint-disable-line camelcase */
state : 'mockState',
});
await defaultAttributesManager.deletePersistentAttributes();
expect(await defaultAttributesManager.getPersistentAttributes()).deep.equal({});
expect(mockPersistenceAdapter.getCounter).eq(2);
});
it('should throw an error when trying to delete persistent attributes without persistence adapter', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
await defaultAttributesManager.deletePersistentAttributes();
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot delete PersistentAttributes without persistence adapter!');
return;
}
throw new Error('should have thrown an error!');
});
it('should be able to set request attributes', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
defaultAttributesManager.setRequestAttributes({key : 'value'});
expect(defaultAttributesManager.getRequestAttributes()).deep.equal({key : 'value'});
});
it('should be able to savePersistentAttributes persistent attributes to persistence layer', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
defaultAttributesManager.setPersistentAttributes({mockKey : 'mockValue'});
await defaultAttributesManager.savePersistentAttributes();
expect(await mockPersistenceAdapter.getAttributes(requestEnvelope)).deep.equal({mockKey : 'mockValue'});
});
it('should thrown an error when trying to save persistent attributes without persistence adapter', async () => {
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({requestEnvelope});
try {
await defaultAttributesManager.savePersistentAttributes();
} catch (err) {
expect(err.name).equal('AskSdk.AttributesManager Error');
expect(err.message).equal('Cannot save PersistentAttributes without persistence adapter!');
return;
}
throw new Error('should have thrown an error!');
});
it('should do nothing if persistentAttributes has not been changed', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
await defaultAttributesManager.savePersistentAttributes();
expect(await mockPersistenceAdapter.getAttributes(requestEnvelope)).deep.equal({
key_1 : 'v1', /* eslint-disable-line camelcase */
key_2 : 'v2', /* eslint-disable-line camelcase */
state : 'mockState',
});
expect(mockPersistenceAdapter.getCounter).equal(1);
expect(mockPersistenceAdapter.saveCounter).equal(0);
});
it('should make only 1 getAttributes call during multiple getPersistentAttributes by default', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
await defaultAttributesManager.getPersistentAttributes();
await defaultAttributesManager.getPersistentAttributes();
await defaultAttributesManager.getPersistentAttributes();
await defaultAttributesManager.getPersistentAttributes();
expect(mockPersistenceAdapter.getCounter).equal(1);
expect(mockPersistenceAdapter.saveCounter).equal(0);
});
it('should make as many getAttributes calls as getPersistentAttributes calls when useSessionCache is false', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
await defaultAttributesManager.getPersistentAttributes(false);
await defaultAttributesManager.getPersistentAttributes(false);
await defaultAttributesManager.getPersistentAttributes(false);
await defaultAttributesManager.getPersistentAttributes(false);
expect(mockPersistenceAdapter.getCounter).equal(4);
expect(mockPersistenceAdapter.saveCounter).equal(0);
});
it('should not make saveAttributes call until savePersistentAttributes is called', async () => {
const mockPersistenceAdapter = new MockPersistenceAdapter();
const requestEnvelope = JsonProvider.requestEnvelope();
requestEnvelope.context.System.user.userId = 'userId';
const defaultAttributesManager = AttributesManagerFactory.init({
persistenceAdapter : mockPersistenceAdapter,
requestEnvelope,
});
await defaultAttributesManager.setPersistentAttributes({});
await defaultAttributesManager.setPersistentAttributes({});
await defaultAttributesManager.setPersistentAttributes({});
await defaultAttributesManager.setPersistentAttributes({});
expect(mockPersistenceAdapter.getCounter).equal(0);
expect(mockPersistenceAdapter.saveCounter).equal(0);
await defaultAttributesManager.savePersistentAttributes();
expect(mockPersistenceAdapter.saveCounter).equal(1);
});
});
``` | /content/code_sandbox/ask-sdk-core/tst/attributes/AttributesManagerFactory.spec.ts | xml | 2016-06-24T06:26:05 | 2024-08-14T12:39:19 | alexa-skills-kit-sdk-for-nodejs | alexa/alexa-skills-kit-sdk-for-nodejs | 3,118 | 2,549 |
```xml
import { Observable } from "rxjs";
import { UserId } from "../../types/guid";
import { DerivedStateDependencies } from "../../types/state";
import { DeriveDefinition } from "./derive-definition";
import { DerivedState } from "./derived-state";
import { GlobalState } from "./global-state";
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- used in docs
import { GlobalStateProvider } from "./global-state.provider";
import { KeyDefinition } from "./key-definition";
import { UserKeyDefinition } from "./user-key-definition";
import { ActiveUserState, SingleUserState } from "./user-state";
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- used in docs
import { ActiveUserStateProvider, SingleUserStateProvider } from "./user-state.provider";
/** Convenience wrapper class for {@link ActiveUserStateProvider}, {@link SingleUserStateProvider},
* and {@link GlobalStateProvider}.
*/
export abstract class StateProvider {
/** @see{@link ActiveUserStateProvider.activeUserId$} */
abstract activeUserId$: Observable<UserId | undefined>;
/**
* Gets a state observable for a given key and userId.
*
* @remarks If userId is falsy the observable returned will attempt to point to the currently active user _and not update if the active user changes_.
* This is different to how `getActive` works and more similar to `getUser` for whatever user happens to be active at the time of the call.
* If no user happens to be active at the time this method is called with a falsy userId then this observable will not emit a value until
* a user becomes active. If you are not confident a user is active at the time this method is called, you may want to pipe a call to `timeout`
* or instead call {@link getUserStateOrDefault$} and supply a value you would rather have given in the case of no passed in userId and no active user.
*
* @param keyDefinition - The key definition for the state you want to get.
* @param userId - The userId for which you want the state for. If not provided, the state for the currently active user will be returned.
*/
abstract getUserState$<T>(keyDefinition: UserKeyDefinition<T>, userId?: UserId): Observable<T>;
/**
* Gets a state observable for a given key and userId
*
* @remarks If userId is falsy the observable return will first attempt to point to the currently active user but will not follow subsequent active user changes,
* if there is no immediately available active user, then it will fallback to returning a default value in an observable that immediately completes.
*
* @param keyDefinition - The key definition for the state you want to get.
* @param config.userId - The userId for which you want the state for. If not provided, the state for the currently active user will be returned.
* @param config.defaultValue - The default value that should be wrapped in an observable if no active user is immediately available and no truthy userId is passed in.
*/
abstract getUserStateOrDefault$<T>(
keyDefinition: UserKeyDefinition<T>,
config: { userId: UserId | undefined; defaultValue?: T },
): Observable<T>;
/**
* Sets the state for a given key and userId.
*
* @overload
* @param keyDefinition - The key definition for the state you want to set.
* @param value - The value to set the state to.
* @param userId - The userId for which you want to set the state for. If not provided, the state for the currently active user will be set.
*/
abstract setUserState<T>(
keyDefinition: UserKeyDefinition<T>,
value: T,
userId?: UserId,
): Promise<[UserId, T]>;
/** @see{@link ActiveUserStateProvider.get} */
abstract getActive<T>(userKeyDefinition: UserKeyDefinition<T>): ActiveUserState<T>;
/** @see{@link SingleUserStateProvider.get} */
abstract getUser<T>(userId: UserId, userKeyDefinition: UserKeyDefinition<T>): SingleUserState<T>;
/** @see{@link GlobalStateProvider.get} */
abstract getGlobal<T>(keyDefinition: KeyDefinition<T>): GlobalState<T>;
abstract getDerived<TFrom, TTo, TDeps extends DerivedStateDependencies>(
parentState$: Observable<TFrom>,
deriveDefinition: DeriveDefinition<TFrom, TTo, TDeps>,
dependencies: TDeps,
): DerivedState<TTo>;
}
``` | /content/code_sandbox/libs/common/src/platform/state/state.provider.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 953 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="path_to_url">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="debug|x64">
<Configuration>debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="checked|x64">
<Configuration>checked</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="profile|x64">
<Configuration>profile</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release|x64">
<Configuration>release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{D18EB5F3-84D9-FD36-27C0-555ADB086FD3}</ProjectGuid>
<RootNamespace>LowLevelParticles</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='checked|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='profile|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v141</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='checked|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='profile|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug|x64'">
<OutDir>./../../../Lib/vc15win64\</OutDir>
<IntDir>./x64/LowLevelParticles/debug\</IntDir>
<TargetExt>.lib</TargetExt>
<TargetName>$(ProjectName)DEBUG</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<BasicRuntimeChecks>UninitializedLocalUsageCheck</BasicRuntimeChecks>
<AdditionalOptions>/GR- /GF /MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4623 /wd4626 /wd5027 /wd4987 /wd5038 /wd5045 /wd4548 /Zi /d2Zi+</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>./../../PhysXGpu/include;./../../Common/include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../../../PxShared/src/pvd/include;./../../../Include;./../../../Include/common;./../../../Include/geometry;./../../../Include/GeomUtils;./../../Common/src;./../../LowLevelParticles/include;./../../LowLevelParticles/src;./../../LowLevel/API/include;./../../LowLevel/common/include/utils;./../../GeomUtils/src;./../../GeomUtils/src/convex;./../../GeomUtils/src/hf;./../../GeomUtils/src/mesh;./../../GeomUtils/headers;./../../../../Externals/nvToolsExt/1/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PX_PHYSX_STATIC_LIB;_DEBUG;PX_DEBUG=1;PX_CHECKED=1;PX_NVTX=1;PX_SUPPORT_PVD=1;PX_PHYSX_DLL_NAME_POSTFIX=DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Lib>
<AdditionalDependencies>./../../../../Externals/nvToolsExt/1/lib/x64/nvToolsExt64_1.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)DEBUG.lib</OutputFile>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<TargetMachine>MachineX64</TargetMachine>
</Lib>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='checked|x64'">
<OutDir>./../../../Lib/vc15win64\</OutDir>
<IntDir>./x64/LowLevelParticles/checked\</IntDir>
<TargetExt>.lib</TargetExt>
<TargetName>$(ProjectName)CHECKED</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='checked|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<AdditionalOptions>/GR- /GF /MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4623 /wd4626 /wd5027 /wd4987 /wd5038 /wd5045 /wd4548 /d2Zi+</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>./../../PhysXGpu/include;./../../Common/include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../../../PxShared/src/pvd/include;./../../../Include;./../../../Include/common;./../../../Include/geometry;./../../../Include/GeomUtils;./../../Common/src;./../../LowLevelParticles/include;./../../LowLevelParticles/src;./../../LowLevel/API/include;./../../LowLevel/common/include/utils;./../../GeomUtils/src;./../../GeomUtils/src/convex;./../../GeomUtils/src/hf;./../../GeomUtils/src/mesh;./../../GeomUtils/headers;./../../../../Externals/nvToolsExt/1/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PX_PHYSX_STATIC_LIB;NDEBUG;PX_CHECKED=1;PX_NVTX=1;PX_SUPPORT_PVD=1;PX_PHYSX_DLL_NAME_POSTFIX=CHECKED;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Lib>
<AdditionalDependencies>./../../../../Externals/nvToolsExt/1/lib/x64/nvToolsExt64_1.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)CHECKED.lib</OutputFile>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<TargetMachine>MachineX64</TargetMachine>
</Lib>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='profile|x64'">
<OutDir>./../../../Lib/vc15win64\</OutDir>
<IntDir>./x64/LowLevelParticles/profile\</IntDir>
<TargetExt>.lib</TargetExt>
<TargetName>$(ProjectName)PROFILE</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='profile|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<AdditionalOptions>/GR- /GF /MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4623 /wd4626 /wd5027 /wd4987 /wd5038 /wd5045 /wd4548 /d2Zi+</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>./../../PhysXGpu/include;./../../Common/include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../../../PxShared/src/pvd/include;./../../../Include;./../../../Include/common;./../../../Include/geometry;./../../../Include/GeomUtils;./../../Common/src;./../../LowLevelParticles/include;./../../LowLevelParticles/src;./../../LowLevel/API/include;./../../LowLevel/common/include/utils;./../../GeomUtils/src;./../../GeomUtils/src/convex;./../../GeomUtils/src/hf;./../../GeomUtils/src/mesh;./../../GeomUtils/headers;./../../../../Externals/nvToolsExt/1/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PX_PHYSX_STATIC_LIB;NDEBUG;PX_PROFILE=1;PX_NVTX=1;PX_SUPPORT_PVD=1;PX_PHYSX_DLL_NAME_POSTFIX=PROFILE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Lib>
<AdditionalOptions>/INCREMENTAL:NO</AdditionalOptions>
<AdditionalDependencies>./../../../../Externals/nvToolsExt/1/lib/x64/nvToolsExt64_1.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)PROFILE.lib</OutputFile>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<TargetMachine>MachineX64</TargetMachine>
</Lib>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release|x64'">
<OutDir>./../../../Lib/vc15win64\</OutDir>
<IntDir>./x64/LowLevelParticles/release\</IntDir>
<TargetExt>.lib</TargetExt>
<TargetName>$(ProjectName)</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release|x64'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<AdditionalOptions>/GR- /GF /MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4623 /wd4626 /wd5027 /wd4987 /wd5038 /wd5045 /wd4548 /d2Zi+</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>./../../PhysXGpu/include;./../../Common/include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../../../PxShared/src/pvd/include;./../../../Include;./../../../Include/common;./../../../Include/geometry;./../../../Include/GeomUtils;./../../Common/src;./../../LowLevelParticles/include;./../../LowLevelParticles/src;./../../LowLevel/API/include;./../../LowLevel/common/include/utils;./../../GeomUtils/src;./../../GeomUtils/src/convex;./../../GeomUtils/src/hf;./../../GeomUtils/src/mesh;./../../GeomUtils/headers;./../../../../Externals/nvToolsExt/1/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PX_PHYSX_STATIC_LIB;NDEBUG;PX_SUPPORT_PVD=0;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Lib>
<AdditionalOptions>/INCREMENTAL:NO</AdditionalOptions>
<AdditionalDependencies>./../../../../Externals/nvToolsExt/1/lib/x64/nvToolsExt64_1.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName).lib</OutputFile>
<AdditionalLibraryDirectories>%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<TargetMachine>MachineX64</TargetMachine>
</Lib>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
</ProjectReference>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\..\LowLevelParticles\include\PtBodyTransformVault.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\include\PtContext.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\include\PtGridCellVector.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\include\PtParticle.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\include\PtParticleContactManagerStream.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\include\PtParticleData.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\include\PtParticleShape.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\include\PtParticleSystemCore.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\include\PtParticleSystemFlags.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\include\PtParticleSystemSim.h">
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\LowLevelParticles\src\gpu\PtRigidBodyAccessGpu.h">
</ClInclude>
<ClCompile Include="..\..\LowLevelParticles\src\gpu\PtRigidBodyAccessGpu.cpp">
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\LowLevelParticles\src\PtBatcher.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtCollision.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtCollisionData.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtCollisionHelper.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtCollisionMethods.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtCollisionParameters.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtConfig.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtConstants.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtContextCpu.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtDynamicHelper.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtDynamics.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtDynamicsKernels.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtDynamicsParameters.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtDynamicsTempBuffers.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtHeightFieldAabbTest.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtPacketSections.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtParticleCell.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtParticleOpcodeCache.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtParticleShapeCpu.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtParticleSystemSimCpu.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtSpatialHash.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtSpatialHashHelper.h">
</ClInclude>
<ClInclude Include="..\..\LowLevelParticles\src\PtTwoWayData.h">
</ClInclude>
<ClCompile Include="..\..\LowLevelParticles\src\PtBatcher.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtBodyTransformVault.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtCollision.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtCollisionBox.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtCollisionCapsule.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtCollisionConvex.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtCollisionMesh.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtCollisionPlane.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtCollisionSphere.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtContextCpu.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtDynamics.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtParticleData.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtParticleShapeCpu.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtParticleSystemSimCpu.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtSpatialHash.cpp">
</ClCompile>
<ClCompile Include="..\..\LowLevelParticles\src\PtSpatialLocalHash.cpp">
</ClCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets"></ImportGroup>
</Project>
``` | /content/code_sandbox/PhysX_3.4/Source/compiler/vc15win64/LowLevelParticles.vcxproj | xml | 2016-10-12T16:34:31 | 2024-08-16T09:40:38 | PhysX-3.4 | NVIDIAGameWorks/PhysX-3.4 | 2,343 | 5,402 |
```xml
import {MusicSheet} from "../MusicSheet";
import {SourceMeasure} from "../VoiceData/SourceMeasure";
import {Fraction} from "../../Common/DataObjects/Fraction";
import {InstrumentReader} from "./InstrumentReader";
import {IXmlElement} from "../../Common/FileIO/Xml";
import {Instrument} from "../Instrument";
import {ITextTranslation} from "../Interfaces/ITextTranslation";
import {MusicSheetReadingException} from "../Exceptions";
import log from "loglevel";
import {IXmlAttribute} from "../../Common/FileIO/Xml";
import {RhythmInstruction} from "../VoiceData/Instructions/RhythmInstruction";
import {RhythmSymbolEnum} from "../VoiceData/Instructions/RhythmInstruction";
import {SourceStaffEntry} from "../VoiceData/SourceStaffEntry";
import {VoiceEntry} from "../VoiceData/VoiceEntry";
import {InstrumentalGroup} from "../InstrumentalGroup";
import {SubInstrument} from "../SubInstrument";
import {MidiInstrument} from "../VoiceData/Instructions/ClefInstruction";
import {AbstractNotationInstruction} from "../VoiceData/Instructions/AbstractNotationInstruction";
import {Label} from "../Label";
import {MusicSymbolModuleFactory} from "./MusicSymbolModuleFactory";
import {IAfterSheetReadingModule} from "../Interfaces/IAfterSheetReadingModule";
import {RepetitionInstructionReader} from "./MusicSymbolModules/RepetitionInstructionReader";
import {RepetitionCalculator} from "./MusicSymbolModules/RepetitionCalculator";
import {EngravingRules} from "../Graphical/EngravingRules";
import { ReaderPluginManager } from "./ReaderPluginManager";
import { TextAlignmentEnum } from "../../Common/Enums/TextAlignment";
export class MusicSheetReader /*implements IMusicSheetReader*/ {
constructor(afterSheetReadingModules: IAfterSheetReadingModule[] = undefined, rules: EngravingRules = new EngravingRules()) {
if (!afterSheetReadingModules) {
this.afterSheetReadingModules = [];
} else {
this.afterSheetReadingModules = afterSheetReadingModules;
}
this.repetitionInstructionReader = MusicSymbolModuleFactory.createRepetitionInstructionReader();
this.repetitionCalculator = MusicSymbolModuleFactory.createRepetitionCalculator();
this.rules = rules;
}
private repetitionInstructionReader: RepetitionInstructionReader;
private repetitionCalculator: RepetitionCalculator;
private afterSheetReadingModules: IAfterSheetReadingModule[];
private musicSheet: MusicSheet;
private completeNumberOfStaves: number = 0;
private currentMeasure: SourceMeasure;
private previousMeasure: SourceMeasure;
private currentFraction: Fraction;
private pluginManager: ReaderPluginManager = new ReaderPluginManager();
public rules: EngravingRules;
public get PluginManager(): ReaderPluginManager {
return this.pluginManager;
}
public get CompleteNumberOfStaves(): number {
return this.completeNumberOfStaves;
}
private static doCalculationsAfterDurationHasBeenSet(instrumentReaders: InstrumentReader[]): void {
for (const instrumentReader of instrumentReaders) {
instrumentReader.doCalculationsAfterDurationHasBeenSet();
}
}
/**
* Read a music XML file and saves the values in the MusicSheet class.
* @param root
* @param path
* @returns {MusicSheet}
*/
public createMusicSheet(root: IXmlElement, path: string): MusicSheet {
try {
return this._createMusicSheet(root, path);
} catch (e) {
log.error("MusicSheetReader.CreateMusicSheet", e);
return undefined;
}
}
private _removeFromArray(list: any[], elem: any): void {
const i: number = list.indexOf(elem);
if (i !== -1) {
list.splice(i, 1);
}
}
// Trim from a string also newlines
private trimString(str: string): string {
return str.replace(/^\s+|\s+$/g, "");
}
private _lastElement<T>(list: T[]): T {
return list[list.length - 1];
}
//public SetPhonicScoreInterface(phonicScoreInterface: IPhonicScoreInterface): void {
// this.phonicScoreInterface = phonicScoreInterface;
//}
//public ReadMusicSheetParameters(sheetObject: MusicSheetParameterObject, root: IXmlElement, path: string): MusicSheetParameterObject {
// this.musicSheet = new MusicSheet();
// if (root) {
// this.pushSheetLabels(root, path);
// if (this.musicSheet.Title) {
// sheetObject.Title = this.musicSheet.Title.text;
// }
// if (this.musicSheet.Composer) {
// sheetObject.Composer = this.musicSheet.Composer.text;
// }
// if (this.musicSheet.Lyricist) {
// sheetObject.Lyricist = this.musicSheet.Lyricist.text;
// }
// let partlistNode: IXmlElement = root.element("part-list");
// let partList: IXmlElement[] = partlistNode.elements();
// this.createInstrumentGroups(partList);
// for (let idx: number = 0, len: number = this.musicSheet.Instruments.length; idx < len; ++idx) {
// let instr: Instrument = this.musicSheet.Instruments[idx];
// sheetObject.InstrumentList.push(__init(new MusicSheetParameterObject.LibrarySheetInstrument(), { name: instr.name }));
// }
// }
// return sheetObject;
//}
private _createMusicSheet(root: IXmlElement, path: string): MusicSheet {
const instrumentReaders: InstrumentReader[] = [];
let sourceMeasureCounter: number = 0;
this.musicSheet = new MusicSheet();
this.musicSheet.Path = path;
this.musicSheet.Rules = this.rules;
const globalWidthAttr: IXmlAttribute = root.attribute("osmdMeasureWidthFactor");
// custom xml attribute, similar to osmdWidthFactor for individual measures
if (globalWidthAttr) {
const globalWidthValue: number = Number.parseFloat(globalWidthAttr.value);
if (typeof globalWidthValue === "number" && !isNaN(globalWidthValue)) {
this.musicSheet.MeasureWidthFactor = globalWidthValue;
} else {
log.info("xml parse: osmdMeasureWidthFactor invalid");
}
}
if (!root) {
throw new MusicSheetReadingException("Undefined root element");
}
this.pushSheetLabels(root, path);
const partlistNode: IXmlElement = root.element("part-list");
if (!partlistNode) {
throw new MusicSheetReadingException("Undefined partListNode");
}
const partInst: IXmlElement[] = root.elements("part");
const partList: IXmlElement[] = partlistNode.elements();
this.initializeReading(partList, partInst, instrumentReaders);
let couldReadMeasure: boolean = true;
this.currentFraction = new Fraction(0, 1);
let octavePlusOneEncoding: boolean = false; // GuitarPro and Sibelius give octaves -1 apparently
let encoding: IXmlElement = root.element("identification");
if (encoding) {
encoding = encoding.element("encoding");
}
if (encoding) {
encoding = encoding.element("software");
}
if (encoding !== undefined && (encoding.value === "Guitar Pro 5")) { //|| encoding.value.startsWith("Sibelius")
octavePlusOneEncoding = true;
}
while (couldReadMeasure) {
// TODO changing this.rules.PartAndSystemAfterFinalBarline requires a reload of the piece for measure numbers to be updated
if (this.currentMeasure !== undefined && this.currentMeasure.HasEndLine && this.rules.NewPartAndSystemAfterFinalBarline) {
sourceMeasureCounter = 0;
}
this.currentMeasure = new SourceMeasure(this.completeNumberOfStaves, this.musicSheet.Rules);
for (const instrumentReader of instrumentReaders) {
try {
couldReadMeasure = couldReadMeasure && instrumentReader.readNextXmlMeasure(
this.currentMeasure, this.currentFraction, octavePlusOneEncoding);
} catch (e) {
const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/InstrumentError", "Error while reading instruments.");
throw new MusicSheetReadingException(errorMsg, e);
}
}
if (couldReadMeasure) {
this.musicSheet.addMeasure(this.currentMeasure);
this.checkIfRhythmInstructionsAreSetAndEqual(instrumentReaders);
this.checkSourceMeasureForNullEntries();
sourceMeasureCounter = this.setSourceMeasureDuration(instrumentReaders, sourceMeasureCounter);
MusicSheetReader.doCalculationsAfterDurationHasBeenSet(instrumentReaders);
this.currentMeasure.AbsoluteTimestamp = this.currentFraction.clone();
this.musicSheet.SheetErrors.finalizeMeasure(this.currentMeasure.MeasureNumber);
this.currentFraction.Add(this.currentMeasure.Duration);
this.previousMeasure = this.currentMeasure;
}
}
if (this.repetitionInstructionReader) {
this.repetitionInstructionReader.removeRedundantInstructions();
if (this.repetitionCalculator) {
this.repetitionCalculator.calculateRepetitions(this.musicSheet, this.repetitionInstructionReader.repetitionInstructions);
}
}
this.musicSheet.checkForInstrumentWithNoVoice();
this.musicSheet.fillStaffList();
//this.musicSheet.DefaultStartTempoInBpm = this.musicSheet.SheetPlaybackSetting.BeatsPerMinute;
for (let idx: number = 0, len: number = this.afterSheetReadingModules.length; idx < len; ++idx) {
const afterSheetReadingModule: IAfterSheetReadingModule = this.afterSheetReadingModules[idx];
afterSheetReadingModule.calculate(this.musicSheet);
}
//this.musicSheet.DefaultStartTempoInBpm = this.musicSheet.SourceMeasures[0].TempoInBPM;
this.musicSheet.userStartTempoInBPM = this.musicSheet.userStartTempoInBPM || this.musicSheet.DefaultStartTempoInBpm;
return this.musicSheet;
}
private initializeReading(partList: IXmlElement[], partInst: IXmlElement[], instrumentReaders: InstrumentReader[]): void {
const instrumentDict: { [_: string]: Instrument } = this.createInstrumentGroups(partList);
this.completeNumberOfStaves = this.getCompleteNumberOfStavesFromXml(partInst);
if (partInst.length !== 0) {
this.repetitionInstructionReader.MusicSheet = this.musicSheet;
this.currentFraction = new Fraction(0, 1);
this.currentMeasure = undefined;
this.previousMeasure = undefined;
}
let counter: number = 0;
for (const node of partInst) {
const idNode: IXmlAttribute = node.attribute("id");
if (idNode) {
const currentInstrument: Instrument = instrumentDict[idNode.value];
const xmlMeasureList: IXmlElement[] = node.elements("measure");
let instrumentNumberOfStaves: number = 1;
try {
instrumentNumberOfStaves = this.getInstrumentNumberOfStavesFromXml(node);
} catch (err) {
const errorMsg: string = ITextTranslation.translateText(
"ReaderErrorMessages/InstrumentStavesNumberError",
"Invalid number of staves at instrument: "
);
this.musicSheet.SheetErrors.push(errorMsg + currentInstrument.Name);
continue;
}
currentInstrument.createStaves(instrumentNumberOfStaves);
instrumentReaders.push(new InstrumentReader(this.pluginManager, this.repetitionInstructionReader, xmlMeasureList, currentInstrument));
if (this.repetitionInstructionReader) {
this.repetitionInstructionReader.xmlMeasureList[counter] = xmlMeasureList;
}
counter++;
}
}
}
/**
* Check if all (should there be any apart from the first Measure) [[RhythmInstruction]]s in the [[SourceMeasure]] are the same.
*
* If not, then the max [[RhythmInstruction]] (Fraction) is set to all staves.
* Also, if it happens to have the same [[RhythmInstruction]]s in RealValue but given in Symbol AND Fraction, then the Fraction prevails.
* @param instrumentReaders
*/
private checkIfRhythmInstructionsAreSetAndEqual(instrumentReaders: InstrumentReader[]): void {
const rhythmInstructions: RhythmInstruction[] = [];
for (let i: number = 0; i < this.completeNumberOfStaves; i++) {
if (this.currentMeasure.FirstInstructionsStaffEntries[i]) {
const last: AbstractNotationInstruction = this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions[
this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions.length - 1
];
if (last instanceof RhythmInstruction) {
rhythmInstructions.push(<RhythmInstruction>last);
}
}
}
let maxRhythmValue: number = 0.0;
let index: number = -1;
for (let idx: number = 0, len: number = rhythmInstructions.length; idx < len; ++idx) {
const rhythmInstruction: RhythmInstruction = rhythmInstructions[idx];
if (rhythmInstruction.Rhythm.RealValue > maxRhythmValue) {
if (this.areRhythmInstructionsMixed(rhythmInstructions) && rhythmInstruction.SymbolEnum !== RhythmSymbolEnum.NONE) {
continue;
}
maxRhythmValue = rhythmInstruction.Rhythm.RealValue;
index = rhythmInstructions.indexOf(rhythmInstruction);
}
}
if (rhythmInstructions.length > 0 && rhythmInstructions.length < this.completeNumberOfStaves) {
const rhythmInstruction: RhythmInstruction = rhythmInstructions[index].clone();
for (let i: number = 0; i < this.completeNumberOfStaves; i++) {
if (
this.currentMeasure.FirstInstructionsStaffEntries[i] !== undefined &&
!(this._lastElement(this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions) instanceof RhythmInstruction)
) {
this.currentMeasure.FirstInstructionsStaffEntries[i].removeAllInstructionsOfTypeRhythmInstruction();
this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions.push(rhythmInstruction.clone());
}
if (!this.currentMeasure.FirstInstructionsStaffEntries[i]) {
this.currentMeasure.FirstInstructionsStaffEntries[i] = new SourceStaffEntry(undefined, undefined);
this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions.push(rhythmInstruction.clone());
}
}
for (let idx: number = 0, len: number = instrumentReaders.length; idx < len; ++idx) {
const instrumentReader: InstrumentReader = instrumentReaders[idx];
instrumentReader.ActiveRhythm = rhythmInstruction;
}
}
if (rhythmInstructions.length === 0 && this.currentMeasure === this.musicSheet.SourceMeasures[0]) {
const rhythmInstruction: RhythmInstruction = new RhythmInstruction(new Fraction(4, 4, 0, false), RhythmSymbolEnum.NONE);
for (let i: number = 0; i < this.completeNumberOfStaves; i++) {
if (!this.currentMeasure.FirstInstructionsStaffEntries[i]) {
this.currentMeasure.FirstInstructionsStaffEntries[i] = new SourceStaffEntry(undefined, undefined);
} else {
this.currentMeasure.FirstInstructionsStaffEntries[i].removeAllInstructionsOfTypeRhythmInstruction();
}
this.currentMeasure.FirstInstructionsStaffEntries[i].Instructions.push(rhythmInstruction);
}
for (let idx: number = 0, len: number = instrumentReaders.length; idx < len; ++idx) {
const instrumentReader: InstrumentReader = instrumentReaders[idx];
instrumentReader.ActiveRhythm = rhythmInstruction;
}
}
for (let idx: number = 0, len: number = rhythmInstructions.length; idx < len; ++idx) {
const rhythmInstruction: RhythmInstruction = rhythmInstructions[idx];
if (rhythmInstruction.Rhythm.RealValue < maxRhythmValue) {
if (this._lastElement(
this.currentMeasure.FirstInstructionsStaffEntries[rhythmInstructions.indexOf(rhythmInstruction)].Instructions
) instanceof RhythmInstruction) {
// TODO Test correctness
const instrs: AbstractNotationInstruction[] =
this.currentMeasure.FirstInstructionsStaffEntries[rhythmInstructions.indexOf(rhythmInstruction)].Instructions;
instrs[instrs.length - 1] = rhythmInstructions[index].clone();
}
}
if (
Math.abs(rhythmInstruction.Rhythm.RealValue - maxRhythmValue) < 0.000001 &&
rhythmInstruction.SymbolEnum !== RhythmSymbolEnum.NONE &&
this.areRhythmInstructionsMixed(rhythmInstructions)
) {
rhythmInstruction.SymbolEnum = RhythmSymbolEnum.NONE;
}
}
}
/**
* True in case of 4/4 and COMMON TIME (or 2/2 and CUT TIME)
* @param rhythmInstructions
* @returns {boolean}
*/
private areRhythmInstructionsMixed(rhythmInstructions: RhythmInstruction[]): boolean {
for (let i: number = 1; i < rhythmInstructions.length; i++) {
if (
Math.abs(rhythmInstructions[i].Rhythm.RealValue - rhythmInstructions[0].Rhythm.RealValue) < 0.000001 &&
rhythmInstructions[i].SymbolEnum !== rhythmInstructions[0].SymbolEnum
) {
return true;
}
}
return false;
}
/**
* Set the [[Measure]]'s duration taking into account the longest [[Instrument]] duration and the active Rhythm read from XML.
* @param instrumentReaders
* @param sourceMeasureCounter
* @returns {number}
*/
private setSourceMeasureDuration(instrumentReaders: InstrumentReader[], sourceMeasureCounter: number): number {
let activeRhythm: Fraction = new Fraction(0, 1);
const instrumentsMaxTieNoteFractions: Fraction[] = [];
for (const instrumentReader of instrumentReaders) {
instrumentsMaxTieNoteFractions.push(instrumentReader.MaxTieNoteFraction);
const activeRythmMeasure: Fraction = instrumentReader.ActiveRhythm.Rhythm;
if (activeRhythm.lt(activeRythmMeasure)) {
activeRhythm = new Fraction(activeRythmMeasure.Numerator, activeRythmMeasure.Denominator, 0, false);
}
}
const instrumentsDurations: Fraction[] = this.currentMeasure.calculateInstrumentsDuration(this.musicSheet, instrumentsMaxTieNoteFractions);
let maxInstrumentDuration: Fraction = new Fraction(0, 1);
for (const instrumentsDuration of instrumentsDurations) {
if (maxInstrumentDuration.lt(instrumentsDuration)) {
maxInstrumentDuration = instrumentsDuration;
}
}
if (Fraction.Equal(maxInstrumentDuration, activeRhythm)) {
this.checkFractionsForEquivalence(maxInstrumentDuration, activeRhythm);
} else {
if (maxInstrumentDuration.lt(activeRhythm)) {
maxInstrumentDuration = this.currentMeasure.reverseCheck(this.musicSheet, maxInstrumentDuration);
this.checkFractionsForEquivalence(maxInstrumentDuration, activeRhythm);
}
}
this.currentMeasure.ImplicitMeasure = this.checkIfMeasureIsImplicit(maxInstrumentDuration, activeRhythm);
if (!this.currentMeasure.ImplicitMeasure || sourceMeasureCounter > 0) {
sourceMeasureCounter++;
// for a starting pickup measure (measure number 0), we shouldn't increment,
// but we need to for any implicit measure afterwards, otherwise we'll have the same measure number twice.
}
this.currentMeasure.Duration = maxInstrumentDuration; // can be 1/1 in a 4/4 time signature
// if (this.currentMeasure.Duration.Numerator === 0) {
// this.currentMeasure.Duration = activeRhythm; // might be related to #1073
// }
this.currentMeasure.ActiveTimeSignature = activeRhythm;
this.currentMeasure.MeasureNumber = sourceMeasureCounter;
for (let i: number = 0; i < instrumentsDurations.length; i++) {
const instrumentsDuration: Fraction = instrumentsDurations[i];
if (
(this.currentMeasure.ImplicitMeasure && instrumentsDuration !== maxInstrumentDuration) ||
!Fraction.Equal(instrumentsDuration, activeRhythm) &&
!this.allInstrumentsHaveSameDuration(instrumentsDurations, maxInstrumentDuration)
) {
const firstStaffIndexOfInstrument: number = this.musicSheet.getGlobalStaffIndexOfFirstStaff(this.musicSheet.Instruments[i]);
for (let staffIndex: number = 0; staffIndex < this.musicSheet.Instruments[i].Staves.length; staffIndex++) {
if (!this.graphicalMeasureIsEmpty(firstStaffIndexOfInstrument + staffIndex)) {
this.currentMeasure.setErrorInGraphicalMeasure(firstStaffIndexOfInstrument + staffIndex, true);
const errorMsg: string = ITextTranslation.translateText("ReaderErrorMessages/MissingNotesError",
"Given Notes don't correspond to measure duration.");
this.musicSheet.SheetErrors.pushMeasureError(errorMsg);
}
}
}
}
return sourceMeasureCounter;
}
/**
* Check the Fractions for Equivalence and if so, sets maxInstrumentDuration's members accordingly.
* *
* Example: if maxInstrumentDuration = 1/1 and sourceMeasureDuration = 4/4, maxInstrumentDuration becomes 4/4.
* @param maxInstrumentDuration
* @param activeRhythm
*/
private checkFractionsForEquivalence(maxInstrumentDuration: Fraction, activeRhythm: Fraction): void {
if (activeRhythm.Denominator > maxInstrumentDuration.Denominator) {
const factor: number = activeRhythm.Denominator / maxInstrumentDuration.Denominator;
maxInstrumentDuration.expand(factor);
}
}
/**
* Handle the case of an implicit [[SourceMeasure]].
* @param maxInstrumentDuration
* @param activeRhythm
* @returns {boolean}
*/
private checkIfMeasureIsImplicit(maxInstrumentDuration: Fraction, activeRhythm: Fraction): boolean {
if (!this.previousMeasure && maxInstrumentDuration.lt(activeRhythm)) {
return true;
}
if (this.previousMeasure) {
return Fraction.plus(this.previousMeasure.Duration, maxInstrumentDuration).Equals(activeRhythm);
}
return false;
}
/**
* Check the Duration of all the given Instruments.
* @param instrumentsDurations
* @param maxInstrumentDuration
* @returns {boolean}
*/
private allInstrumentsHaveSameDuration(instrumentsDurations: Fraction[], maxInstrumentDuration: Fraction): boolean {
let counter: number = 0;
for (let idx: number = 0, len: number = instrumentsDurations.length; idx < len; ++idx) {
const instrumentsDuration: Fraction = instrumentsDurations[idx];
if (instrumentsDuration.Equals(maxInstrumentDuration)) {
counter++;
}
}
return (counter === instrumentsDurations.length && maxInstrumentDuration !== new Fraction(0, 1));
}
private graphicalMeasureIsEmpty(index: number): boolean {
let counter: number = 0;
for (let i: number = 0; i < this.currentMeasure.VerticalSourceStaffEntryContainers.length; i++) {
if (!this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries[index]) {
counter++;
}
}
return (counter === this.currentMeasure.VerticalSourceStaffEntryContainers.length);
}
/**
* Check a [[SourceMeasure]] for possible empty / undefined entries ([[VoiceEntry]], [[SourceStaffEntry]], VerticalContainer)
* (caused from TieAlgorithm removing EndTieNote) and removes them if completely empty / null
*/
private checkSourceMeasureForNullEntries(): void {
for (let i: number = this.currentMeasure.VerticalSourceStaffEntryContainers.length - 1; i >= 0; i--) {
for (let j: number = this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries.length - 1; j >= 0; j--) {
const sourceStaffEntry: SourceStaffEntry = this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries[j];
if (sourceStaffEntry) {
for (let k: number = sourceStaffEntry.VoiceEntries.length - 1; k >= 0; k--) {
const voiceEntry: VoiceEntry = sourceStaffEntry.VoiceEntries[k];
if (voiceEntry.Notes.length === 0) {
this._removeFromArray(voiceEntry.ParentVoice.VoiceEntries, voiceEntry);
this._removeFromArray(sourceStaffEntry.VoiceEntries, voiceEntry);
}
}
}
if (sourceStaffEntry !== undefined && sourceStaffEntry.VoiceEntries.length === 0 && sourceStaffEntry.ChordContainers.length === 0) {
this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries[j] = undefined;
}
}
}
for (let i: number = this.currentMeasure.VerticalSourceStaffEntryContainers.length - 1; i >= 0; i--) {
let counter: number = 0;
for (let idx: number = 0, len: number = this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries.length; idx < len; ++idx) {
const sourceStaffEntry: SourceStaffEntry = this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries[idx];
if (!sourceStaffEntry) {
counter++;
}
}
if (counter === this.currentMeasure.VerticalSourceStaffEntryContainers[i].StaffEntries.length) {
this._removeFromArray(this.currentMeasure.VerticalSourceStaffEntryContainers, this.currentMeasure.VerticalSourceStaffEntryContainers[i]);
}
}
}
/**
* Read the XML file and creates the main sheet Labels.
* @param root
* @param filePath
*/
private pushSheetLabels(root: IXmlElement, filePath: string): void {
this.readComposer(root);
this.readTitle(root);
try {
if (!this.musicSheet.Title || !this.musicSheet.Composer || !this.musicSheet.Subtitle) {
this.readTitleAndComposerFromCredits(root); // this can also throw an error
}
} catch (ex) {
log.info("MusicSheetReader.pushSheetLabels", "readTitleAndComposerFromCredits", ex);
}
try {
if (!this.musicSheet.Title) {
const barI: number = Math.max(
0, filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")
);
const filename: string = filePath.substr(barI);
const filenameSplits: string[] = filename.split(".", 1);
this.musicSheet.Title = new Label(filenameSplits[0]);
}
} catch (ex) {
log.info("MusicSheetReader.pushSheetLabels", "read title from file name", ex);
}
}
// Checks whether _elem_ has an attribute with value _val_.
private presentAttrsWithValue(elem: IXmlElement, val: string): boolean {
for (const attr of elem.attributes()) {
if (attr.value === val) {
return true;
}
}
return false;
}
private readComposer(root: IXmlElement): void {
const identificationNode: IXmlElement = root.element("identification");
if (identificationNode) {
const creators: IXmlElement[] = identificationNode.elements("creator");
for (let idx: number = 0, len: number = creators.length; idx < len; ++idx) {
const creator: IXmlElement = creators[idx];
if (creator.hasAttributes) {
if (this.presentAttrsWithValue(creator, "composer")) {
this.musicSheet.Composer = new Label(this.trimString(creator.value));
continue;
}
if (this.presentAttrsWithValue(creator, "lyricist") || this.presentAttrsWithValue(creator, "poet")) {
this.musicSheet.Lyricist = new Label(this.trimString(creator.value));
}
}
}
}
}
const idElements: IXmlElement[] = root.elements("identification");
if(idElements.length > 0){
const idElement: IXmlElement = idElements[0];
const rightElements: IXmlElement[] = idElement.elements("rights");
if(rightElements.length > 0){
for(let idx: number = 0, len: number = rightElements.length; idx < len; ++idx){
const rightElement: IXmlElement = rightElements[idx];
if(rightElement.value){
break;
}
}
}
}
}
private readTitleAndComposerFromCredits(root: IXmlElement): void {
if (this.rules.SheetComposerSubtitleUseLegacyParsing) {
this.readTitleAndComposerFromCreditsLegacy(root);
return;
}
const systemYCoordinates: number = this.computeSystemYCoordinates(root);
if (systemYCoordinates === 0) {
return;
}
// let largestTitleCreditSize: number = 1;
let finalTitle: string = undefined;
// let largestCreditYInfo: number = 0;
let finalSubtitle: string = undefined;
// let possibleTitle: string = undefined;
let finalComposer: string = undefined;
const creditElements: IXmlElement[] = root.elements("credit");
for (let idx: number = 0, len: number = creditElements.length; idx < len; ++idx) {
const credit: IXmlElement = creditElements[idx];
if (!credit.attribute("page")) {
return;
}
if (credit.attribute("page").value === "1") {
let creditChildren: IXmlElement[] = undefined;
if (credit) {
let isSubtitle: boolean = false;
let isComposer: boolean = false;
const typeChild: IXmlElement = credit.element("credit-type");
if (typeChild?.value === "subtitle") {
isSubtitle = true;
} else if (typeChild?.value === "composer") {
isComposer = true;
}
let isSubtitleOrComposer: boolean = isSubtitle || isComposer;
creditChildren = credit.elements("credit-words");
for (const creditChild of creditChildren) {
const creditChildValue: string = creditChild.value?.trim();
continue; // this seems to be a MuseScore default, useless
}
const creditJustify: string = creditChild.attribute("justify")?.value;
if (creditJustify === "right") {
isComposer = true;
isSubtitleOrComposer = true;
} else if (creditJustify === "center" && finalTitle) {
isSubtitle = true;
isSubtitleOrComposer = true;
}
const creditY: string = creditChild.attribute("default-y")?.value;
// eslint-disable-next-line no-null/no-null
const creditYGiven: boolean = creditY !== undefined && creditY !== null;
const creditYInfo: number = creditYGiven ? parseFloat(creditY) : Number.MIN_VALUE;
if ((creditYGiven && creditYInfo > systemYCoordinates) || isSubtitleOrComposer) {
if (!finalTitle && !isSubtitleOrComposer) {
// only take largest font size label
// const creditSize: string = creditChild.attribute("font-size")?.value;
// if (creditSize) {
// const titleCreditSizeInt: number = parseFloat(creditSize);
// if (largestTitleCreditSize < titleCreditSizeInt) {
// largestTitleCreditSize = titleCreditSizeInt;
// finalTitle = creditChild.value;
// }
// }
finalTitle = creditChildValue;
// if (!finalTitle) {
// finalTitle = creditChild.value;
// } else {
// finalTitle += "\n" + creditChild.value;
// }
} else if (isComposer || creditJustify === "right") {
if (!finalComposer) {
finalComposer = creditChildValue;
} else {
finalComposer += "\n" + creditChildValue;
}
} else if (isSubtitle || creditJustify !== "right" && creditJustify !== "left") {
// if (largestCreditYInfo < creditYInfo) {
// largestCreditYInfo = creditYInfo;
// if (possibleTitle) {
// finalSubtitle = possibleTitle;
// possibleTitle = creditChild.value;
// } else {
// possibleTitle = creditChild.value;
// }
// } else {
if (finalSubtitle) {
finalSubtitle += "\n" + creditChildValue;
} else {
finalSubtitle = creditChildValue;
}
// }
} else if (creditJustify === "left") {
if (!this.musicSheet.Lyricist) {
this.musicSheet.Lyricist = new Label(creditChildValue);
}
break;
}
}
}
}
}
}
if (!this.musicSheet.Title && finalTitle) {
this.musicSheet.Title = new Label(this.trimString(finalTitle));
}
if (!this.musicSheet.Subtitle && finalSubtitle) {
this.musicSheet.Subtitle = new Label(this.trimString(finalSubtitle));
}
if (finalComposer) {
let overrideSheetComposer: boolean = false;
if (!this.musicSheet.Composer) {
overrideSheetComposer = true;
} else {
// check if we have more lines in existing composer label
// we should only take the existing label if it has less lines,
// since the credit labels are more likely to be the rendering intention than the metadata
const creditComposerLines: number = (finalComposer.match("\n") ?? []).length + 1;
const sheetComposerLines: number = (this.musicSheet.Composer.text.match("\n") ?? []).length + 1;
if (creditComposerLines >= sheetComposerLines) {
overrideSheetComposer = true;
}
}
if (overrideSheetComposer) {
this.musicSheet.Composer = new Label(this.trimString(finalComposer));
}
}
}
/** @deprecated Old OSMD < 1.8.6 way of parsing composer + subtitles,
* ignores multiline composer + subtitles, uses XML identification tags instead.
* Will probably be removed soon.
*/
private readTitleAndComposerFromCreditsLegacy(root: IXmlElement): void {
const systemYCoordinates: number = this.computeSystemYCoordinates(root);
if (systemYCoordinates === 0) {
return;
}
let largestTitleCreditSize: number = 1;
let finalTitle: string = undefined;
let largestCreditYInfo: number = 0;
let finalSubtitle: string = undefined;
let possibleTitle: string = undefined;
const creditElements: IXmlElement[] = root.elements("credit");
for (let idx: number = 0, len: number = creditElements.length; idx < len; ++idx) {
const credit: IXmlElement = creditElements[idx];
if (!credit.attribute("page")) {
return;
}
if (credit.attribute("page").value === "1") {
let creditChild: IXmlElement = undefined;
if (credit) {
creditChild = credit.element("credit-words");
if (!creditChild.attribute("justify")) {
break;
}
const creditJustify: string = creditChild.attribute("justify")?.value;
const creditY: string = creditChild.attribute("default-y")?.value;
// eslint-disable-next-line no-null/no-null
const creditYGiven: boolean = creditY !== undefined && creditY !== null;
const creditYInfo: number = creditYGiven ? parseFloat(creditY) : Number.MIN_VALUE;
let isSubtitle: boolean = false;
const typeChild: IXmlElement = credit.element("credit-type");
if (typeChild?.value === "subtitle") {
isSubtitle = true;
}
if ((creditYGiven && creditYInfo > systemYCoordinates) || isSubtitle) {
if (!this.musicSheet.Title && !isSubtitle) {
const creditSize: string = creditChild.attribute("font-size")?.value;
if (creditSize) {
const titleCreditSizeInt: number = parseFloat(creditSize);
if (largestTitleCreditSize < titleCreditSizeInt) {
largestTitleCreditSize = titleCreditSizeInt;
finalTitle = creditChild.value;
}
}
}
if (!this.musicSheet.Subtitle) {
if (creditJustify !== "right" && creditJustify !== "left" || isSubtitle) {
if (largestCreditYInfo < creditYInfo) {
largestCreditYInfo = creditYInfo;
if (possibleTitle) {
finalSubtitle = possibleTitle;
possibleTitle = creditChild.value;
} else {
possibleTitle = creditChild.value;
}
} else {
if (finalSubtitle) {
finalSubtitle += "\n" + creditChild.value;
} else {
finalSubtitle = creditChild.value;
}
}
}
}
switch (creditJustify) {
case "right":
if (!this.musicSheet.Composer) {
this.musicSheet.Composer = new Label(this.trimString(creditChild.value));
}
break;
case "left":
if (!this.musicSheet.Lyricist) {
this.musicSheet.Lyricist = new Label(this.trimString(creditChild.value));
}
break;
default:
break;
}
}
}
}
}
if (!this.musicSheet.Title && finalTitle) {
this.musicSheet.Title = new Label(this.trimString(finalTitle));
}
if (!this.musicSheet.Subtitle && finalSubtitle) {
this.musicSheet.Subtitle = new Label(this.trimString(finalSubtitle));
}
}
private computeSystemYCoordinates(root: IXmlElement): number {
if (!root.element("defaults")) {
return 0;
}
let paperHeight: number = 0;
let topSystemDistance: number = 0;
try {
const defi: string = root.element("defaults").element("page-layout").element("page-height").value;
paperHeight = parseFloat(defi);
} catch (e) {
log.info("MusicSheetReader.computeSystemYCoordinates(): couldn't find page height, not reading title/composer.");
return 0;
}
let found: boolean = false;
const parts: IXmlElement[] = root.elements("part");
for (let idx: number = 0, len: number = parts.length; idx < len; ++idx) {
const measures: IXmlElement[] = parts[idx].elements("measure");
for (let idx2: number = 0, len2: number = measures.length; idx2 < len2; ++idx2) {
const measure: IXmlElement = measures[idx2];
if (measure.element("print")) {
const systemLayouts: IXmlElement[] = measure.element("print").elements("system-layout");
for (let idx3: number = 0, len3: number = systemLayouts.length; idx3 < len3; ++idx3) {
const syslab: IXmlElement = systemLayouts[idx3];
if (syslab.element("top-system-distance")) {
const topSystemDistanceString: string = syslab.element("top-system-distance").value;
topSystemDistance = parseFloat(topSystemDistanceString);
found = true;
break;
}
}
break;
}
}
if (found) {
break;
}
}
if (root.element("defaults").element("system-layout")) {
const syslay: IXmlElement = root.element("defaults").element("system-layout");
if (syslay.element("top-system-distance")) {
const topSystemDistanceString: string = root.element("defaults").element("system-layout").element("top-system-distance").value;
topSystemDistance = parseFloat(topSystemDistanceString);
}
}
if (topSystemDistance === 0) {
return 0;
}
return paperHeight - topSystemDistance;
}
private readTitle(root: IXmlElement): void {
const titleNode: IXmlElement = root.element("work");
let titleNodeChild: IXmlElement = undefined;
if (titleNode) {
titleNodeChild = titleNode.element("work-title");
if (titleNodeChild && titleNodeChild.value) {
this.musicSheet.Title = new Label(this.trimString(titleNodeChild.value));
}
}
const movementNode: IXmlElement = root.element("movement-title");
let finalSubTitle: string = "";
if (movementNode) {
if (!this.musicSheet.Title) {
this.musicSheet.Title = new Label(this.trimString(movementNode.value));
} else {
finalSubTitle = this.trimString(movementNode.value);
}
}
if (titleNode) {
const subtitleNodeChild: IXmlElement = titleNode.element("work-number");
if (subtitleNodeChild) {
const workNumber: string = subtitleNodeChild.value;
if (workNumber) {
if (finalSubTitle === "") {
finalSubTitle = workNumber;
} else {
finalSubTitle = finalSubTitle + ", " + workNumber;
}
}
}
}
if (finalSubTitle
) {
this.musicSheet.Subtitle = new Label(finalSubTitle);
}
}
/**
* Build the [[InstrumentalGroup]]s and [[Instrument]]s.
* @param entryList
* @returns {{}}
*/
private createInstrumentGroups(entryList: IXmlElement[]): { [_: string]: Instrument } {
let instrumentId: number = 0;
const instrumentDict: { [_: string]: Instrument } = {};
let currentGroup: InstrumentalGroup;
try {
const entryArray: IXmlElement[] = entryList;
for (let idx: number = 0, len: number = entryArray.length; idx < len; ++idx) {
const node: IXmlElement = entryArray[idx];
if (node.name === "score-part") {
const instrIdString: string = node.attribute("id").value;
const instrument: Instrument = new Instrument(instrumentId, instrIdString, this.musicSheet, currentGroup);
instrumentId++;
const partElements: IXmlElement[] = node.elements();
for (let idx2: number = 0, len2: number = partElements.length; idx2 < len2; ++idx2) {
const partElement: IXmlElement = partElements[idx2];
try {
if (partElement.name === "part-name") {
instrument.Name = partElement.value;
if (partElement.attribute("print-object") &&
partElement.attribute("print-object").value === "no") {
instrument.NameLabel.print = false;
}
} else if (partElement.name === "part-abbreviation") {
instrument.PartAbbreviation = partElement.value;
} else if (partElement.name === "score-instrument") {
const subInstrument: SubInstrument = new SubInstrument(instrument);
subInstrument.idString = partElement.firstAttribute.value;
instrument.SubInstruments.push(subInstrument);
const subElement: IXmlElement = partElement.element("instrument-name");
if (subElement) {
subInstrument.name = subElement.value;
subInstrument.setMidiInstrument(subElement.value);
}
} else if (partElement.name === "midi-instrument") {
let subInstrument: SubInstrument = instrument.getSubInstrument(partElement.firstAttribute.value);
for (let idx3: number = 0, len3: number = instrument.SubInstruments.length; idx3 < len3; ++idx3) {
const subInstr: SubInstrument = instrument.SubInstruments[idx3];
if (subInstr.idString === partElement.value) {
subInstrument = subInstr;
break;
}
}
const instrumentElements: IXmlElement[] = partElement.elements();
for (let idx3: number = 0, len3: number = instrumentElements.length; idx3 < len3; ++idx3) {
const instrumentElement: IXmlElement = instrumentElements[idx3];
try {
if (instrumentElement.name === "midi-channel") {
if (parseInt(instrumentElement.value, 10) === 10) {
instrument.MidiInstrumentId = MidiInstrument.Percussion;
}
} else if (instrumentElement.name === "midi-program") {
if (instrument.SubInstruments.length > 0 && instrument.MidiInstrumentId !== MidiInstrument.Percussion) {
subInstrument.midiInstrumentID = <MidiInstrument>Math.max(0, parseInt(instrumentElement.value, 10) - 1);
}
} else if (instrumentElement.name === "midi-unpitched") {
subInstrument.fixedKey = Math.max(0, parseInt(instrumentElement.value, 10));
} else if (instrumentElement.name === "volume") {
try {
const result: number = parseFloat(instrumentElement.value);
subInstrument.volume = result / 127.0;
} catch (ex) {
log.debug("ExpressionReader.readExpressionParameters", "read volume", ex);
}
} else if (instrumentElement.name === "pan") {
try {
const result: number = parseFloat(instrumentElement.value);
subInstrument.pan = result / 64.0;
} catch (ex) {
log.debug("ExpressionReader.readExpressionParameters", "read pan", ex);
}
}
} catch (ex) {
log.info("MusicSheetReader.createInstrumentGroups midi settings: ", ex);
}
}
}
} catch (ex) {
log.info("MusicSheetReader.createInstrumentGroups: ", ex);
}
}
if (instrument.SubInstruments.length === 0) {
const subInstrument: SubInstrument = new SubInstrument(instrument);
instrument.SubInstruments.push(subInstrument);
}
instrumentDict[instrIdString] = instrument;
if (currentGroup) {
currentGroup.InstrumentalGroups.push(instrument);
this.musicSheet.Instruments.push(instrument);
} else {
this.musicSheet.InstrumentalGroups.push(instrument);
this.musicSheet.Instruments.push(instrument);
}
} else {
if ((node.name === "part-group") && (node.attribute("type").value === "start")) {
const iG: InstrumentalGroup = new InstrumentalGroup("group", this.musicSheet, currentGroup);
if (currentGroup) {
currentGroup.InstrumentalGroups.push(iG);
} else {
this.musicSheet.InstrumentalGroups.push(iG);
}
currentGroup = iG;
} else {
if ((node.name === "part-group") && (node.attribute("type").value === "stop")) {
if (currentGroup) {
if (currentGroup.InstrumentalGroups.length === 1) {
const instr: InstrumentalGroup = currentGroup.InstrumentalGroups[0];
if (currentGroup.Parent) {
currentGroup.Parent.InstrumentalGroups.push(instr);
this._removeFromArray(currentGroup.Parent.InstrumentalGroups, currentGroup);
} else {
this.musicSheet.InstrumentalGroups.push(instr);
this._removeFromArray(this.musicSheet.InstrumentalGroups, currentGroup);
}
}
currentGroup = currentGroup.Parent;
}
}
}
}
}
} catch (e) {
const errorMsg: string = ITextTranslation.translateText(
"ReaderErrorMessages/InstrumentError", "Error while reading Instruments"
);
throw new MusicSheetReadingException(errorMsg, e);
}
for (let idx: number = 0, len: number = this.musicSheet.Instruments.length; idx < len; ++idx) {
const instrument: Instrument = this.musicSheet.Instruments[idx];
if (!instrument.Name) {
instrument.Name = "Instr. " + instrument.IdString;
}
}
return instrumentDict;
}
/**
* Read from each xmlInstrumentPart the first xmlMeasure in order to find out the [[Instrument]]'s number of Staves
* @param partInst
* @returns {number} - Complete number of Staves for all Instruments.
*/
private getCompleteNumberOfStavesFromXml(partInst: IXmlElement[]): number {
let num: number = 0;
for (const partNode of partInst) {
const xmlMeasureList: IXmlElement[] = partNode.elements("measure");
if (xmlMeasureList.length > 0) {
const xmlMeasure: IXmlElement = xmlMeasureList[0];
if (xmlMeasure) {
let stavesNode: IXmlElement = xmlMeasure.element("attributes");
if (stavesNode) {
stavesNode = stavesNode.element("staves");
}
if (!stavesNode) {
num++;
} else {
num += parseInt(stavesNode.value, 10);
}
}
}
}
if (isNaN(num) || num <= 0) {
const errorMsg: string = ITextTranslation.translateText(
"ReaderErrorMessages/StaffError", "Invalid number of staves."
);
throw new MusicSheetReadingException(errorMsg);
}
return num;
}
/**
* Read from XML for a single [[Instrument]] the first xmlMeasure in order to find out the Instrument's number of Staves.
* @param partNode
* @returns {number}
*/
private getInstrumentNumberOfStavesFromXml(partNode: IXmlElement): number {
let num: number = 0;
const xmlMeasure: IXmlElement = partNode.element("measure");
if (xmlMeasure) {
const attributes: IXmlElement = xmlMeasure.element("attributes");
let staves: IXmlElement = undefined;
if (attributes) {
staves = attributes.element("staves");
}
if (!attributes || !staves) {
num = 1;
} else {
num = parseInt(staves.value, 10);
}
}
if (isNaN(num) || num <= 0) {
const errorMsg: string = ITextTranslation.translateText(
"ReaderErrorMessages/StaffError", "Invalid number of Staves."
);
throw new MusicSheetReadingException(errorMsg);
}
return num;
}
}
``` | /content/code_sandbox/src/MusicalScore/ScoreIO/MusicSheetReader.ts | xml | 2016-02-08T15:47:01 | 2024-08-16T17:49:53 | opensheetmusicdisplay | opensheetmusicdisplay/opensheetmusicdisplay | 1,416 | 10,735 |
```xml
/*
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
export class NotFoundError extends Error {}
``` | /content/code_sandbox/elements/lisk-tree/src/error.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 93 |
```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 custom Popper.js modifiers
* @see path_to_url#custom-modifiers
*/
import type { Modifier } from "@popperjs/core";
// tslint:disable object-literal-sort-keys
// adapted from path_to_url
export const matchReferenceWidthModifier: Modifier<"matchReferenceWidth", any> = {
enabled: true,
name: "matchReferenceWidth",
phase: "beforeWrite",
requires: ["computeStyles"],
fn: ({ state }) => {
state.styles.popper.width = `${state.rects.reference.width}px`;
},
effect: ({ state }) => {
const referenceWidth = state.elements.reference.getBoundingClientRect().width;
state.elements.popper.style.width = `${referenceWidth}px`;
},
};
``` | /content/code_sandbox/packages/core/src/components/popover/customModifiers.ts | xml | 2016-10-25T21:17:50 | 2024-08-16T15:14:48 | blueprint | palantir/blueprint | 20,593 | 196 |
```xml
<RelativeLayout xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AlertActivity" >
<Button
android:id="@+id/one_button_alert"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="25dip"
android:layout_marginLeft="20dip"
android:text="Single Button Alert" />
<Button
android:id="@+id/two_button_alert"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@id/one_button_alert"
android:layout_marginLeft="20dip"
android:text="Two Buttons Alert" />
<Button
android:id="@+id/three_button_alert"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@id/two_button_alert"
android:layout_marginLeft="20dip"
android:text="Three Buttons Alert" />
</RelativeLayout>
``` | /content/code_sandbox/Android/AlertDialog/app/src/main/res/layout/activity_alert.xml | xml | 2016-05-02T05:43:21 | 2024-08-16T06:51:39 | journaldev | WebJournal/journaldev | 1,314 | 277 |
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "path_to_url">
<mapper namespace="cn.abel.user.dao.RoleDao">
<resultMap id="roleMap" type="cn.abel.user.models.Role">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="roleLevel" column="role_level"/>
<result property="description" column="description"/>
</resultMap>
<sql id="queryCondition">
<where>
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="roleLevel != null and roleLevel != ''">
and role_level = #{roleLevel}
</if>
<if test="description != null and description != ''">
and description = #{description}
</if>
</where>
</sql>
<select id="getByMap" parameterType="map" resultMap="roleMap">
SELECT * FROM role
<include refid="queryCondition" />
</select>
<select id="getById" parameterType="int" resultMap="roleMap">
SELECT * FROM role WHERE id =#{id}
</select>
<insert id="create" parameterType="cn.abel.user.models.Role">
<selectKey resultType="int" order="AFTER" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO role(
id,
name,
role_level,
description
)VALUES(
#{id},
#{name},
#{roleLevel},
#{description}
)
</insert>
<update id="update" parameterType="cn.abel.user.models.Role">
UPDATE role SET
name = #{name},
role_level = #{roleLevel},
description = #{description}
WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM role WHERE id = #{id}
</delete>
</mapper>
``` | /content/code_sandbox/springboot-dubbo/abel-user-provider/src/main/resources/mapper/RoleDaoMapper.xml | xml | 2016-11-07T02:13:31 | 2024-08-16T08:17:57 | springBoot | 527515025/springBoot | 6,488 | 522 |
```xml
import type { ChangeEvent, FormEvent } from 'react';
import { useMemo, useState } from 'react';
import { getUnixTime } from 'date-fns';
import { c, msgid } from 'ttag';
import { Button } from '@proton/atoms/Button';
import type { ModalProps } from '@proton/components';
import {
Alert,
InputFieldTwo,
Label,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
PasswordInputTwo,
Toggle,
useConfirmActionModal,
useModalTwoStatic,
useToggle,
} from '@proton/components';
import { useLoading } from '@proton/hooks';
import { MAX_SHARED_URL_PASSWORD_LENGTH } from '@proton/shared/lib/drive/constants';
import clsx from '@proton/utils/clsx';
import { ExpirationTimeDatePicker } from './PublicSharing';
interface Props {
initialExpiration: number | null;
customPassword: string;
isDeleting?: boolean;
stopSharing: () => Promise<void>;
onSaveLinkClick: (
password?: string,
duration?: number | null
) => Promise<void | (unknown & { expirationTime: number | null })>;
modificationDisabled: boolean;
confirmationMessage: string;
havePublicSharedLink: boolean;
isShareUrlEnabled: boolean;
}
const SharingSettingsModal = ({
customPassword,
initialExpiration,
onSaveLinkClick,
isDeleting,
stopSharing,
modificationDisabled,
confirmationMessage,
havePublicSharedLink,
isShareUrlEnabled,
...modalProps
}: Props & ModalProps) => {
const [password, setPassword] = useState(customPassword);
const [expiration, setExpiration] = useState(initialExpiration);
const [confirmActionModal, showConfirmActionModal] = useConfirmActionModal();
const [isSubmitting, withSubmitting] = useLoading();
const { state: passwordEnabled, toggle: togglePasswordEnabled } = useToggle(!!customPassword);
const { state: expirationEnabled, toggle: toggleExpiration } = useToggle(!!initialExpiration);
const isFormDirty = useMemo(() => {
// If initialExpiration or customPassword is empty, that means it was disabled
const expirationChanged = expiration !== initialExpiration || expirationEnabled !== !!initialExpiration;
const passwordChanged = password !== customPassword || passwordEnabled !== !!customPassword;
return Boolean(expirationChanged || passwordChanged);
}, [password, customPassword, passwordEnabled, expiration, initialExpiration, expirationEnabled]);
const handleClose = () => {
if (!isFormDirty) {
modalProps.onClose?.();
return;
}
void showConfirmActionModal({
title: c('Title').t`Discard changes?`,
submitText: c('Title').t`Discard`,
message: c('Info').t`You will lose all unsaved changes.`,
onSubmit: async () => modalProps.onClose?.(),
canUndo: true,
});
};
const handleStopSharing = async () => {
void showConfirmActionModal({
title: c('Title').t`Stop sharing?`,
submitText: c('Action').t`Stop sharing`,
message: confirmationMessage,
canUndo: true, // Just to hide the message
onSubmit: stopSharing,
});
};
const isPasswordInvalid = password.length > MAX_SHARED_URL_PASSWORD_LENGTH;
const isSaveDisabled = !isFormDirty || isDeleting || isPasswordInvalid;
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
const newCustomPassword = !passwordEnabled || !password ? '' : password;
const newExpiration = !expirationEnabled || !expiration ? null : expiration;
const newDuration = newExpiration ? newExpiration - getUnixTime(Date.now()) : null;
// Instead of blocking user action, we just save the form without sending a request
// For exemple if the user toggled the password field but don't put any password, we just don't do anything.
// This make the UX smoother
const needUpdate = newCustomPassword !== customPassword || newExpiration !== initialExpiration;
if (needUpdate) {
await withSubmitting(onSaveLinkClick(newCustomPassword, newDuration));
}
modalProps.onClose?.();
};
return (
<>
<ModalTwo
as="form"
size="large"
onSubmit={handleSubmit}
{...modalProps}
onClose={handleClose}
fullscreenOnMobile
>
<ModalTwoHeader title={c('Title').t`Settings`} />
<ModalTwoContent>
{!isShareUrlEnabled ? (
<>
{havePublicSharedLink && modificationDisabled && (
<Alert type="warning">
{c('Info')
.t`This link was created with old Drive version and can not be modified. Delete this link and create a new one to change the settings.`}
</Alert>
)}
<div
className="flex flex-column justify-space-between gap-2 md:items-center md:gap-0 md:flex-row md:h-custom md:items-center "
style={{ '--h-custom': '2.25rem' }}
data-testid="sharing-modal-settings-expirationSection"
>
<Label
htmlFor="expirationDateInputId"
className={clsx(
'flex flex-column p-0 text-semibold',
!havePublicSharedLink && 'opacity-30'
)}
>
{c('Label').t`Set expiration date`}
<span className="color-weak text-normal">{c('Label')
.t`Public link expiration date`}</span>
</Label>
<div className="flex items-center justify-space-between gap-2 ">
<ExpirationTimeDatePicker
className="w-custom max-w-custom"
containerProps={{
style: { '--w-custom': '12.5rem', '--max-w-custom': '12.5rem' },
}}
id="expirationDateInputId"
disabled={!expirationEnabled}
allowTime={false}
expiration={expiration}
handleExpirationChange={setExpiration}
placeholder={c('Placeholder').t`Set date`}
data-testid="expiration-data-input"
/>
<Toggle
disabled={!havePublicSharedLink}
id="toggleExpiration"
checked={expirationEnabled}
onChange={toggleExpiration}
/>
</div>
</div>
<div
className="mt-5 flex flex-column justify-space-between gap-2 md:flex-row md:gap-0 md:items-center md:h-custom w-auto md:flex-nowrap md:items-center"
style={{ '--h-custom': '2.25rem' }}
data-testid="sharing-modal-settings-passwordSection"
>
<Label
className={clsx(
'flex flex-column p-0 text-semibold',
!havePublicSharedLink && 'opacity-30'
)}
htmlFor="sharing-modal-password"
>
{c('Label').t`Set link password`}
<span className="color-weak text-normal">{c('Label').t`Public link password`}</span>
</Label>
<div className="flex items-center justify-space-between gap-2 md:flex-nowrap">
<InputFieldTwo
disabled={!passwordEnabled}
dense
className="items-center"
rootClassName="flex items-center justify-end pr-0 w-custom"
rootStyle={{ '--w-custom': '12.5rem' }}
id="sharing-modal-password"
as={PasswordInputTwo}
data-testid="password-input"
label={false}
autoComplete="new-password"
value={password}
onInput={(e: ChangeEvent<HTMLInputElement>) => {
setPassword(e.target.value);
}}
error={
isPasswordInvalid &&
c('Info').ngettext(
msgid`Max ${MAX_SHARED_URL_PASSWORD_LENGTH} character`,
`Max ${MAX_SHARED_URL_PASSWORD_LENGTH} characters`,
MAX_SHARED_URL_PASSWORD_LENGTH
)
}
placeholder={c('Placeholder').t`Choose password`}
/>
<Toggle
id="togglePassword"
disabled={!havePublicSharedLink}
checked={passwordEnabled}
onChange={togglePasswordEnabled}
/>
</div>
</div>
<hr className="my-5" />
</>
) : null}
<div
className="flex flex-nowrap justify-space-between items-center"
data-testid="share-modal-settings-deleteShareSection"
>
<div className="flex flex-column flex-1 p-0" data-testid="delete-share-text">
<span className="text-semibold">{c('Label').t`Stop sharing`}</span>
<span className="color-weak">{c('Label')
.t`Erase this link and remove everyone with access`}</span>
</div>
<Button
className="flex items-center"
shape="ghost"
color="danger"
onClick={handleStopSharing}
data-testid="delete-share-button"
>{c('Action').t`Stop sharing`}</Button>
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button onClick={handleClose}>{c('Action').t`Back`}</Button>
<Button disabled={isSaveDisabled} loading={isSubmitting} color="norm" type="submit">{c('Action')
.t`Save changes`}</Button>
</ModalTwoFooter>
</ModalTwo>
{confirmActionModal}
</>
);
};
export default SharingSettingsModal;
export const useLinkSharingSettingsModal = () => {
return useModalTwoStatic(SharingSettingsModal);
};
``` | /content/code_sandbox/applications/drive/src/app/components/modals/ShareLinkModal/ShareLinkSettingsModal.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 2,043 |
```xml
import { METRICS_MAX_JAIL } from '../constants';
import type IMetricsApi from './types/IMetricsApi';
import type IMetricsRequestService from './types/IMetricsRequestService';
import type MetricsRequest from './types/MetricsRequest';
interface BatchOptions {
frequency: number;
size: number;
}
class MetricsRequestService implements IMetricsRequestService {
public api: IMetricsApi;
private _reportMetrics: boolean;
private _requestQueue: MetricsRequest[];
private _batch?: BatchOptions;
private _jailMax: number;
private _jailCount: number;
private _intervalId: ReturnType<typeof setInterval> | null;
constructor(
api: IMetricsApi,
{
reportMetrics,
batch,
jailMax,
}: {
reportMetrics: boolean;
batch?: BatchOptions;
jailMax?: number;
}
) {
this.api = api;
this._reportMetrics = reportMetrics;
this._batch = (() => {
if (batch === undefined) {
return;
}
if (batch.frequency <= 0 || batch.size <= 0) {
return;
}
return batch;
})();
this._requestQueue = [];
this._intervalId = null;
this._jailMax = (() => {
if (jailMax === undefined) {
return METRICS_MAX_JAIL;
}
if (jailMax <= 0) {
return METRICS_MAX_JAIL;
}
return jailMax;
})();
this._jailCount = 0;
}
public startBatchingProcess() {
if (this._intervalId !== null || this._batch === undefined) {
return;
}
// Very nave progressive backoff
const frequencyWithIncrementalBackoff = (this._jailCount + 1) * this._batch.frequency;
this._intervalId = setInterval(() => {
this.processNextBatch();
}, frequencyWithIncrementalBackoff);
}
public stopBatchingProcess() {
if (this._intervalId === null) {
return;
}
clearInterval(this._intervalId);
this._intervalId = null;
}
public async processAllRequests() {
if (this._requestQueue.length === 0) {
return;
}
const itemsToProcess = this._requestQueue;
this.clearQueue();
try {
await this.makeRequest(itemsToProcess);
} catch (error) {
this.resetBatchingProcess();
}
}
public clearQueue() {
this._requestQueue = [];
}
public setReportMetrics(reportMetrics: boolean) {
this._reportMetrics = reportMetrics;
}
public report(request: MetricsRequest) {
if (!this._reportMetrics) {
return;
}
if (this._batch === undefined) {
void this.makeRequest([request]).catch(() => {});
return;
}
if (this._intervalId === null) {
this.startBatchingProcess();
}
this._requestQueue.push(request);
}
private async processNextBatch() {
if (this._batch === undefined) {
return;
}
const itemsToProcess = this._requestQueue.splice(0, this._batch.size);
if (itemsToProcess.length === 0) {
this.stopBatchingProcess();
return;
}
try {
await this.makeRequest(itemsToProcess);
} catch (error) {
this.resetBatchingProcess();
}
}
private async makeRequest(metrics: MetricsRequest[]) {
if (this.isJailed()) {
return;
}
try {
await this.api.fetch('api/data/v1/metrics', {
method: 'post',
body: JSON.stringify({ Metrics: metrics }),
});
if (this._requestQueue.length === 0) {
this.resetJailCount();
}
} catch (error) {
this.incrementJailCount();
throw error;
}
}
private resetBatchingProcess() {
this.stopBatchingProcess();
this.startBatchingProcess();
}
private isJailed = () => {
return this._jailCount >= this._jailMax;
};
private resetJailCount = () => {
this._jailCount = 0;
};
private incrementJailCount = () => {
this._jailCount += 1;
};
}
export default MetricsRequestService;
``` | /content/code_sandbox/packages/metrics/lib/MetricsRequestService.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 959 |
```xml
import { CommonModule } from '@angular/common';
import { Component, Input, NgModule } from '@angular/core';
import { SharedModule } from 'primeng/api';
/**
* InputGroupAddon displays text, icon, buttons and other content can be grouped next to an input.
* @group Components
*/
@Component({
selector: 'p-inputGroupAddon',
template: `
<div [attr.data-pc-name]="'inputgroupaddon'" [ngClass]="styleClass" [ngStyle]="style">
<ng-content></ng-content>
</div>
`,
host: {
class: 'p-element p-inputgroup-addon'
}
})
export class InputGroupAddon {
/**
* Inline style of the element.
* @group Props
*/
@Input() style: { [klass: string]: any } | null | undefined;
/**
* Class of the element.
* @group Props
*/
@Input() styleClass: string | undefined;
}
@NgModule({
imports: [CommonModule],
exports: [InputGroupAddon, SharedModule],
declarations: [InputGroupAddon]
})
export class InputGroupAddonModule {}
``` | /content/code_sandbox/src/app/components/inputgroupaddon/inputgroupaddon.ts | xml | 2016-01-16T09:23:28 | 2024-08-16T19:58:20 | primeng | primefaces/primeng | 9,969 | 241 |
```xml
import * as React from 'react';
import type { BasePickerProps } from '../picker/interface';
import type { PickerColumnItem } from '../picker-view/interface';
export interface BaseSelectProps extends Omit<BasePickerProps, 'visible'> {
placeholder?: string;
displayRender?: (data?: PickerColumnItem[]) => React.ReactNode;
}
``` | /content/code_sandbox/packages/zarm/src/select/interface.ts | xml | 2016-07-13T11:45:37 | 2024-08-12T19:23:48 | zarm | ZhongAnTech/zarm | 1,707 | 71 |
```xml
/**
* Finds the mean of a set of numbers
* @throws {Error} if array is empty
*/
export default function mean(arr: number[]): number;
export default function mean(...arr: number[]): number;
``` | /content/code_sandbox/packages/array-mean/index.d.ts | xml | 2016-06-26T02:04:54 | 2024-08-15T00:08:43 | just | angus-c/just | 5,974 | 45 |
```xml
import { InferAttributes, InferCreationAttributes } from "sequelize";
import {
DataType,
BelongsTo,
ForeignKey,
Column,
Table,
} from "sequelize-typescript";
import Document from "./Document";
import User from "./User";
import IdModel from "./base/IdModel";
import Fix from "./decorators/Fix";
@Table({ tableName: "backlinks", modelName: "backlink" })
@Fix
class Backlink extends IdModel<
InferAttributes<Backlink>,
Partial<InferCreationAttributes<Backlink>>
> {
@BelongsTo(() => User, "userId")
user: User;
@ForeignKey(() => User)
@Column(DataType.UUID)
userId: string;
@BelongsTo(() => Document, "documentId")
document: Document;
@ForeignKey(() => Document)
@Column(DataType.UUID)
documentId: string;
@BelongsTo(() => Document, "reverseDocumentId")
reverseDocument: Document;
@ForeignKey(() => Document)
@Column(DataType.UUID)
reverseDocumentId: string;
}
export default Backlink;
``` | /content/code_sandbox/server/models/Backlink.ts | xml | 2016-05-22T21:31:47 | 2024-08-16T19:57:22 | outline | outline/outline | 26,751 | 229 |
```xml
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at path_to_url
*/
import {ChangeDetectionStrategy, Component} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {MatButtonModule} from '@angular/material/button';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatRadioModule} from '@angular/material/radio';
import {MatTooltip} from '@angular/material/tooltip';
@Component({
selector: 'radio-demo',
templateUrl: 'radio-demo.html',
styleUrl: 'radio-demo.css',
standalone: true,
imports: [
CommonModule,
MatRadioModule,
FormsModule,
MatButtonModule,
MatCheckboxModule,
MatTooltip,
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RadioDemo {
isAlignEnd = false;
isDisabled = false;
isRequired = false;
disabledInteractive = true;
favoriteSeason = 'Autumn';
seasonOptions = ['Winter', 'Spring', 'Summer', 'Autumn'];
}
``` | /content/code_sandbox/src/dev-app/radio/radio-demo.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 244 |
```xml
import { WebPartContext } from '@microsoft/sp-webpart-base';
import { ClientMode } from './ClientMode';
export interface IGraphConsumerProps {
clientMode: ClientMode;
context: WebPartContext;
}
``` | /content/code_sandbox/tutorials/api-scopes/src/webparts/graphConsumer/components/IGraphConsumerProps.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 48 |
```xml
import { Component, Output, EventEmitter } from '@angular/core';
import { InfiniteScrollModule } from "ngx-infinite-scroll";
@Component({
selector: 'modal',
templateUrl: './modal.html',
standalone: true,
imports: [InfiniteScrollModule]
})
export class ModalComponent {
@Output() onClose = new EventEmitter();
array: number[] = [];
sum = 100;
modalIsOpen = '';
modalTitle = 'scroll to update';
modalBody = modalText;
modalScrollDistance = 2;
modalScrollThrottle = 50;
constructor() {
for (let i = 0; i < this.sum; ++i) {
this.array.push(i);
}
this.open();
}
onScrollDown() {
console.log('scrolled!!');
// add another 20 items
const start = this.sum;
this.sum += 20;
for (let i = start; i < this.sum; ++i) {
this.array.push(i);
}
}
onModalScrollDown() {
this.modalTitle = 'updated on ' + new Date().toString();
this.modalBody += modalText;
}
open() {
this.modalIsOpen = 'in modal-open';
}
close() {
this.modalIsOpen = '';
this.modalBody = modalText;
this.onClose.emit();
}
}
var modalText = `Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.
Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.
Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.`;
``` | /content/code_sandbox/projects/demo/src/app/modal/modal.component.ts | xml | 2016-02-05T09:19:39 | 2024-08-15T16:17:38 | ngx-infinite-scroll | orizens/ngx-infinite-scroll | 1,231 | 713 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
path_to_url
Unless required by applicable law or agreed to in writing,
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
specific language governing permissions and limitations
-->
<!DOCTYPE concept PUBLIC "-//OASIS//DTD DITA Concept//EN" "concept.dtd">
<concept id="float">
<title>FLOAT Data Type</title>
<titlealts audience="PDF"><navtitle>FLOAT</navtitle></titlealts>
<prolog>
<metadata>
<data name="Category" value="Impala"/>
<data name="Category" value="Impala Data Types"/>
<data name="Category" value="SQL"/>
<data name="Category" value="Data Analysts"/>
<data name="Category" value="Developers"/>
<data name="Category" value="Schemas"/>
</metadata>
</prolog>
<conbody>
<p>
A single precision floating-point data type used in <codeph>CREATE TABLE</codeph> and <codeph>ALTER
TABLE</codeph> statements.
</p>
<p conref="../shared/impala_common.xml#common/syntax_blurb"/>
<p>
In the column definition of a <codeph>CREATE TABLE</codeph> statement:
</p>
<codeblock><varname>column_name</varname> FLOAT</codeblock>
<p>
<b>Range:</b> 1.40129846432481707e-45 .. 3.40282346638528860e+38, positive or negative
</p>
<p>
<b>Precision:</b> 6 to 9 significant digits, depending on usage. The number of significant digits does
not depend on the position of the decimal point.
</p>
<p>
<b>Representation:</b> The values are stored in 4 bytes, using
<xref href="path_to_url" scope="external" format="html">IEEE 754 Single Precision Binary Floating Point</xref> format.
</p>
<p>
<b>Conversions:</b> Impala automatically converts <codeph>FLOAT</codeph> to more precise
<codeph>DOUBLE</codeph> values, but not the other way around. You can use <codeph>CAST()</codeph> to convert
<codeph>FLOAT</codeph> values to <codeph>TINYINT</codeph>, <codeph>SMALLINT</codeph>, <codeph>INT</codeph>,
<codeph>BIGINT</codeph>, <codeph>STRING</codeph>, <codeph>TIMESTAMP</codeph>, or <codeph>BOOLEAN</codeph>.
You can use exponential notation in <codeph>FLOAT</codeph> literals or when casting from
<codeph>STRING</codeph>, for example <codeph>1.0e6</codeph> to represent one million.
<ph conref="../shared/impala_common.xml#common/cast_int_to_timestamp"/>
</p>
<p conref="../shared/impala_common.xml#common/usage_notes_blurb"/>
<!--Below conref'd content fixes IMPALA-3603-->
<p conref="../shared/impala_common.xml#common/how_impala_handles_nan_values"/>
<codeblock>
SELECT CAST('nan' AS FLOAT)=CAST('nan' AS FLOAT);
</codeblock>
<p conref="../shared/impala_common.xml#common/example_blurb"/>
<codeblock>CREATE TABLE t1 (x FLOAT);
SELECT CAST(1000.5 AS FLOAT);
</codeblock>
<p conref="../shared/impala_common.xml#common/partitioning_imprecise"/>
<p conref="../shared/impala_common.xml#common/hbase_ok"/>
<p conref="../shared/impala_common.xml#common/parquet_ok"/>
<p conref="../shared/impala_common.xml#common/text_bulky"/>
<!-- <p conref="../shared/impala_common.xml#common/compatibility_blurb"/> -->
<p conref="../shared/impala_common.xml#common/internals_4_bytes"/>
<!-- <p conref="../shared/impala_common.xml#common/added_in_20"/> -->
<p conref="../shared/impala_common.xml#common/column_stats_constant"/>
<p conref="../shared/impala_common.xml#common/restrictions_blurb"/>
<!-- This conref appears under SUM(), AVG(), FLOAT, and DOUBLE topics. -->
<p conref="../shared/impala_common.xml#common/sum_double"/>
<p conref="../shared/impala_common.xml#common/float_double_decimal_caveat"/>
<p conref="../shared/impala_common.xml#common/kudu_blurb"/>
<p conref="../shared/impala_common.xml#common/kudu_non_pk_data_type"/>
<p conref="../shared/impala_common.xml#common/related_info"/>
<p>
<xref href="impala_literals.xml#numeric_literals"/>, <xref href="impala_math_functions.xml#math_functions"/>,
<xref href="impala_double.xml#double"/>
</p>
</conbody>
</concept>
``` | /content/code_sandbox/docs/topics/impala_float.xml | xml | 2016-04-13T07:00:08 | 2024-08-16T10:10:44 | impala | apache/impala | 1,115 | 1,192 |
```xml
import type { IStorageProvider } from '@unleash/proxy-client-react';
import saveWhitelistedFlagInCookies from './UnleashCookiesProvider';
export default class ProtonUnleashStorageProvider implements IStorageProvider {
private prefix = 'unleash:repository';
public async save(name: string, data: any) {
const repo = JSON.stringify(data);
const key = `${this.prefix}:${name}`;
try {
saveWhitelistedFlagInCookies(data);
window.localStorage.setItem(key, repo);
} catch (e) {}
}
public get(name: string) {
try {
const key = `${this.prefix}:${name}`;
const data = window.localStorage.getItem(key);
return data ? JSON.parse(data) : undefined;
} catch (e) {}
}
}
``` | /content/code_sandbox/packages/unleash/storage/UnleashStorageProvider.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 172 |
```xml
import {
IntermediateModerationPhase,
IntermediatePhaseResult,
} from "coral-server/services/comments/pipeline";
import {
GQLCOMMENT_STATUS,
GQLTAG,
} from "coral-server/graph/schema/__generated__/types";
export const approveExpertAnswers: IntermediateModerationPhase = ({
tags,
}): IntermediatePhaseResult | void => {
// If the comment doesn't have the expert tag, then do nothing!
if (!tags.includes(GQLTAG.EXPERT)) {
return;
}
return { status: GQLCOMMENT_STATUS.APPROVED };
};
``` | /content/code_sandbox/server/src/core/server/services/comments/pipeline/phases/approveExpertAnswers.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 121 |
```xml
/**
* @file App logger
* @module utils/logger
* @author Surmon <path_to_url
*/
// MARK: keep chalk v4.x
// path_to_url
import chalk from 'chalk'
const renderTime = () => {
const now = new Date()
return `[${now.toLocaleDateString()} ${now.toLocaleTimeString()}]`
}
const renderScope = (scope: string) => {
return chalk.green.underline(scope)
}
const renderMessage = (color: chalk.Chalk, messages: any[]) => {
return messages.map((m) => (typeof m === 'string' ? color(m) : m))
}
interface LoggerRenderOptions {
consoler: (...messages: any[]) => void
label: string
color: chalk.Chalk
scope?: string
time?: boolean
}
const renderLogger = (options: LoggerRenderOptions) => {
return (...messages: any) => {
const logs: any[] = []
logs.push(options.label)
if (options.time) {
logs.push(renderTime())
}
if (options.scope) {
logs.push(renderScope(options.scope))
}
return options.consoler(...logs, ...renderMessage(options.color, messages))
}
}
export interface LoggerOptions {
scope?: string
time?: boolean
}
export const createLogger = (opts?: LoggerOptions) => ({
// levels
log: renderLogger({ label: '', consoler: console.log, color: chalk.cyanBright, ...opts }),
info: renderLogger({ label: '', consoler: console.info, color: chalk.greenBright, ...opts }),
warn: renderLogger({ label: '', consoler: console.warn, color: chalk.yellowBright, ...opts }),
error: renderLogger({ label: '', consoler: console.error, color: chalk.redBright, ...opts }),
debug: renderLogger({ label: '', consoler: console.debug, color: chalk.cyanBright, ...opts }),
// aliases
success: renderLogger({ label: '', consoler: console.log, color: chalk.greenBright, ...opts }),
failure: renderLogger({ label: '', consoler: console.warn, color: chalk.redBright, ...opts })
})
export default createLogger()
``` | /content/code_sandbox/src/utils/logger.ts | xml | 2016-02-13T08:16:02 | 2024-08-12T08:34:20 | nodepress | surmon-china/nodepress | 1,421 | 475 |
```xml
import {gql} from '@shopify/hydrogen';
import type {HydrogenApiRouteOptions, HydrogenRequest} from '@shopify/hydrogen';
import {ProductConnection} from '@shopify/hydrogen/storefront-api-types';
import {PRODUCT_CARD_FRAGMENT} from '~/lib/fragments';
export async function api(
_request: HydrogenRequest,
{queryShop}: HydrogenApiRouteOptions,
) {
const {
data: {products},
} = await queryShop<{
products: ProductConnection;
}>({
query: TOP_PRODUCTS_QUERY,
variables: {
count: 4,
},
});
return products.nodes;
}
const TOP_PRODUCTS_QUERY = gql`
${PRODUCT_CARD_FRAGMENT}
query topProducts(
$count: Int
$countryCode: CountryCode
$languageCode: LanguageCode
) @inContext(country: $countryCode, language: $languageCode) {
products(first: $count, sortKey: BEST_SELLING) {
nodes {
...ProductCard
}
}
}
`;
``` | /content/code_sandbox/packages/hydrogen/test/fixtures/demo-store-ts/src/routes/api/bestSellers.server.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 233 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#e2e2e2" />
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#f9f9f9"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:text="Windows "
android:textColor="#777"
android:textSize="14sp" />
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#e2e2e2" />
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#f9f9f9"
android:gravity="center"
android:text="header\n\nheader"
android:textColor="#2BA245"
android:textSize="12sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#ffffff"
android:gravity="center"
android:text="We are in ScrollView"
android:textColor="#cccccc" />
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#f9f9f9" />
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#ffffff" />
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#f9f9f9" />
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#ffffff" />
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#f9f9f9" />
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#ffffff" />
</LinearLayout>
``` | /content/code_sandbox/demo/src/main/res/layout/content_demo12.xml | xml | 2016-03-28T09:07:07 | 2024-08-15T05:22:18 | SpringView | liaoinstan/SpringView | 1,935 | 513 |
```xml
<manifest xmlns:android="path_to_url" package="com.sina.util.dnscache">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application android:allowBackup="true" android:label="@string/app_name"
android:supportsRtl="true">
</application>
</manifest>
``` | /content/code_sandbox/httpdns/src/main/AndroidManifest.xml | xml | 2016-08-08T13:25:41 | 2024-08-15T07:21:04 | H-Viewer | PureDark/H-Viewer | 1,738 | 162 |
```xml
/**
*/
import type { Config } from 'jest'
// TODO: find a way to consolidate this in one place, with webpack.common.js
const ignorePatterns = [
'@buttercup/fetch',
'@juliushaertl',
'@mdi/svg',
'@nextcloud/files',
'@nextcloud/upload',
'@nextcloud/vue',
'ansi-regex',
'camelcase',
'char-regex',
'hot-patcher',
'is-svg',
'layerr',
'mime',
'p-cancelable',
'p-limit',
'p-queue',
'p-timeout',
'splitpanes',
'string-length',
'strip-ansi',
'tributejs',
'unist-.+',
'url-join',
'vue-material-design-icons',
'webdav',
'yocto-queue',
]
const config: Config = {
testMatch: ['<rootDir>/**/*.(spec|test).(ts|js)'],
clearMocks: true,
setupFilesAfterEnv: [
'<rootDir>/__tests__/jest-setup.ts',
'<rootDir>/__tests__/mock-window.js',
],
testEnvironment: 'jest-environment-jsdom',
preset: 'ts-jest/presets/js-with-ts',
roots: [
'<rootDir>/__mocks__',
'<rootDir>/__tests__',
'<rootDir>/apps',
'<rootDir>/core',
],
transform: {
// process `*.js` files with `babel-jest`
'^.+\\.c?js$': 'babel-jest',
'^.+\\.vue$': '@vue/vue2-jest',
'^.+\\.ts$': ['ts-jest', {
// @see path_to_url
tsconfig: './__tests__/tsconfig.json',
}],
},
transformIgnorePatterns: [
'node_modules/(?!(' + ignorePatterns.join('|') + ')/)',
],
// Allow mocking svg files
moduleNameMapper: {
'^.+\\.svg(\\?raw)?$': '<rootDir>/__mocks__/svg.js',
'\\.s?css$': '<rootDir>/__mocks__/css.js',
},
modulePathIgnorePatterns: [
'<rootDir>/apps2/',
'<rootDir>/apps-extra/',
],
}
export default config
``` | /content/code_sandbox/jest.config.ts | xml | 2016-06-02T07:44:14 | 2024-08-16T18:23:54 | server | nextcloud/server | 26,415 | 530 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
import {Report, SingleReportConfiguration} from 'types';
import {Spec} from 'immutability-helper';
import CountTargetInput from './CountTargetInput';
import DurationTargetInput from './DurationTargetInput';
interface TargetSelectionProps {
report: Report<'process'> | Report<'decision'>;
onChange: (change: Spec<SingleReportConfiguration>) => void;
hideBaseLine?: boolean;
}
export default function TargetSelection({report, onChange, hideBaseLine}: TargetSelectionProps) {
const {configuration, view} = report.data;
const targetValue = configuration.targetValue;
const isPercentageReport = view?.properties.includes('percentage');
const countOperation =
view?.properties.includes('frequency') ||
isPercentageReport ||
(view && 'entity' in view && view.entity === 'variable');
if (countOperation) {
return (
<CountTargetInput
baseline={targetValue.countProgress.baseline}
target={targetValue.countProgress.target}
isBelow={targetValue.countProgress.isBelow}
disabled={!targetValue.active}
isPercentageReport={isPercentageReport}
hideBaseLine={hideBaseLine}
onChange={(type, value) =>
onChange({targetValue: {countProgress: {[type]: {$set: value}}}})
}
/>
);
} else {
return (
<DurationTargetInput
baseline={targetValue.durationProgress.baseline}
target={targetValue.durationProgress.target}
disabled={!targetValue.active}
hideBaseLine={hideBaseLine}
onChange={(type, subType, value) =>
onChange({targetValue: {durationProgress: {[type]: {[subType]: {$set: value}}}}})
}
/>
);
}
}
``` | /content/code_sandbox/optimize/client/src/modules/components/TargetSelection/TargetSelection.tsx | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 395 |
```xml
// luma.gl
/* eslint-disable max-len */
import test from 'tape-promise/tape';
import {getTestDevices} from '@luma.gl/test-utils';
import {Framebuffer} from '@luma.gl/core';
const TEST_CASES = [
{
title: 'Default attachments',
getOpts: device => ({}),
pass: false
},
{
title: 'No attachments',
getOpts: device => ({attachments: {}}),
pass: false
},
{
title: 'Autocreated Depth Renderbuffer + Color Texture',
getOpts: device => ({
colorAttachments: ['rgba8unorm'],
depthStencilAttachment: 'depth16unorm'
}),
pass: true
}
/*
{
title: 'Supplied Depth Renderbuffer + Color Texture',
getOpts: (device) => ({
colorAttachments: [device.createTexture()],
depthStencilAttachment: device.createTexture({format: 'depth16unorm'})
}),
pass: true
},
{
title: 'Simple Stencil Renderbuffer + Color Texture',
getOpts: (gl) => ({
attachments: {
colorAttachment0: webglDevice.createTexture(gl),
depthStencilAttachment: webglDevice.createTexture({format: 'stencil8'})
}
}),
pass: true
},
{
title: 'Combined Depth/Stencil Renderbuffer + Color Texture',
getOpts: (gl) => ({
attachments: {
colorAttachment0: webglDevice.createTexture(gl),
depthStencilAttachment: webglDevice.createTexture({format: 'depth24plus'})
}
}),
pass: true
}
*/
// {
// features: FEATURES.MULTIPLE_RENDER_TARGETS,
// getOpts(gl) {
// attachments: {
// [GL.COLOR_ATTACHMENT0]: webglDevice.createTexture(gl),
// [GL.COLOR_ARTTACHMENT1]: webglDevice.createTexture(gl),
// [GL.DEPTH]: webglDevice.createRenderbuffer(gl)
// }
// },
// pass: true
// }
];
test('WebGLDevice.createFramebuffer()', async t => {
for (const testDevice of await getTestDevices()) {
t.throws(() => testDevice.createFramebuffer({}), 'Framebuffer without attachment fails');
const framebuffer = testDevice.createFramebuffer({
colorAttachments: ['rgba8unorm'],
depthStencilAttachment: 'depth16unorm'
});
t.ok(framebuffer instanceof Framebuffer, 'Framebuffer with attachment');
framebuffer.destroy();
t.ok(framebuffer instanceof Framebuffer, 'Framebuffer delete successful');
framebuffer.destroy();
t.ok(framebuffer instanceof Framebuffer, 'Framebuffer repeated delete successful');
}
t.end();
});
test('WebGLFramebuffer create and resize attachments', async t => {
for (const testDevice of await getTestDevices()) {
for (const tc of TEST_CASES) {
let props;
t.doesNotThrow(() => {
props = tc.getOpts(testDevice);
}, `Framebuffer options constructed for "${tc.title}"`);
const testFramebufferOpts = () => {
const framebuffer = testDevice.createFramebuffer(props);
framebuffer.resize({width: 1000, height: 1000});
t.equals(framebuffer.width, 1000, 'Framebuffer width updated correctly on resize');
t.equals(framebuffer.height, 1000, 'Framebuffer height updated correctly on resize');
framebuffer.resize({width: 100, height: 100});
t.equals(framebuffer.width, 100, 'Framebuffer width updated correctly on resize');
t.equals(framebuffer.height, 100, 'Framebuffer height updated correctly on resize');
framebuffer.destroy(); // {recursive: true}
};
if (tc.pass) {
t.doesNotThrow(
testFramebufferOpts,
`${testDevice.id}.createFramebuffer() success as expected for "${tc.title}"`
);
} else {
t.throws(
testFramebufferOpts,
`${testDevice.id}.createFramebuffer() failure as expected for "${tc.title}"`
);
}
}
}
t.end();
});
test('WebGLFramebuffer resize', async t => {
for (const testDevice of await getTestDevices()) {
const framebuffer = testDevice.createFramebuffer({
colorAttachments: ['rgba8unorm'],
depthStencilAttachment: 'depth16unorm'
});
framebuffer.resize({width: 2, height: 2});
t.equals(framebuffer.width, 2, 'Framebuffer width updated correctly on resize');
t.equals(framebuffer.height, 2, 'Framebuffer height updated correctly on resize');
if (testDevice.type === 'webgl') {
testDevice.beginRenderPass({
framebuffer,
clearColor: [1, 0, 0, 1]
});
const pixels = testDevice.readPixelsToArrayWebGL(framebuffer);
t.deepEqual(
pixels,
// @prettier-ignore
[255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255],
'Framebuffer pixel colors are set correctly'
);
}
framebuffer.delete();
}
t.end();
});
/*
test.skip('Framebuffer#getDefaultFramebuffer', (t) => {
const framebuffer = webglDevice.getDefaultCanvasContext().getCurrentFramebuffer();
t.ok(framebuffer instanceof Framebuffer, 'getDefaultFramebuffer successful');
t.throws(
() => framebuffer.resize(1000, 1000),
'defaultFramebuffer.resize({width, height}) throws'
);
t.end();
});
*/
/*
import {TEXTURE_FORMATS} from '@luma.gl/webgl/texture-formats';
const RGB_TO = {
[GL.UNSIGNED_BYTE]: (r, g, b) => [r * 256, g * 256, b * 256],
[GL.UNSIGNED_SHORT_5_6_5]: (r, g, b) => r * 32 << 11 + g * 64 << 6 + b * 32
};
// const RGB_FROM = {
// [GL.UNSIGNED_BYTE]: v => [v[0] / 256, v[1] / 256, v[2] / 256],
// [GL.UNSIGNED_SHORT_5_6_5]: v => [v >> 11 / 32, v >> 6 % 64 / 64, v % 32 * 32]
// };
const DATA = [1, 0.5, 0.25, 0.125];
const TEXTURE_DATA = {
[GL.UNSIGNED_BYTE]: webglDevice.createUint8Array(RGB_TO[GL.UNSIGNED_BYTE](DATA)),
[GL.UNSIGNED_SHORT_5_6_5]: webglDevice.createUint16Array(RGB_TO[GL.UNSIGNED_SHORT_5_6_5](DATA))
};
const DEFAULT_TEXTURE_DATA = webglDevice.createUint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
test('WebGL2#Framebuffer texture attach and read', t => {
const {gl2} = fixture;
const framebuffer = webglDevice.createFramebuffer(gl2, {depth: true, width: 1, height: 1, check: false});
for (let format in TEXTURE_FORMATS) {
const textureFormat = TEXTURE_FORMATS[format];
const {dataFormat, types, compressed} = textureFormat;
format = Number(format);
if (Texture2D.isSupported(gl2, {format}) && !compressed) {
let texture;
for (const type of types) {
// texture = webglDevice.createTexture(gl2, Object.assign({format, dataFormat, type}));
// t.equals(texture.format, format,
// `Texture2D({format: ${getKey(format)}, type: ${getKey(type)}, dataFormat: ${getKey(dataFormat)}) created`);
// texture.destroy()
const data = TEXTURE_DATA[type] || DEFAULT_TEXTURE_DATA;
texture = webglDevice.createTexture(gl2, {format, dataFormat, type, data, width: 1, height: 1});
t.equals(texture.format, format,
`Texture2D({format: ${getKey(format)}, type: ${getKey(type)}, dataFormat: ${getKey(dataFormat)}) created`);
framebuffer.attach({
[GL.COLOR_ATTACHMENT0]: texture
});
t.doesNotThrow(
() => framebuffer.checkStatus(),
'Framebuffer is attachment complete'
);
let pixels;
t.doesNotThrow(
() => {
pixels = radPixelsToArray(framebuffer);
},
'Framebuffer.readPixels returned'
);
t.ok(pixels, 'Received pixels');
texture.destroy();
}
}
}
t.end();
});
*/
``` | /content/code_sandbox/modules/core/test/adapter/resources/framebuffer.spec.ts | xml | 2016-01-25T09:41:59 | 2024-08-16T10:03:05 | luma.gl | visgl/luma.gl | 2,280 | 1,941 |
```xml
class C {
foo: string;
thing() { }
static other() { }
}
class D extends C {
bar: string;
}
var d: D;
var r = d.foo;
var r2 = d.bar;
var r3 = d.thing();
var r4 = D.other();
class C2<T> {
foo: T;
thing(x: T) { }
static other<T>(x: T) { }
}
class D2<T> extends C2<T> {
bar: string;
}
var d2: D2<string>;
var r5 = d2.foo;
var r6 = d2.bar;
var r7 = d2.thing('');
var r8 = D2.other(1);
``` | /content/code_sandbox/tests/format/typescript/conformance/classes/classDeclarations/classHeritageSpecification/classExtendingClass.ts | xml | 2016-11-29T17:13:37 | 2024-08-16T17:29:57 | prettier | prettier/prettier | 48,913 | 156 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
<testsuite name="tensorflow/python/kernel_tests/xent_op_test" tests="1" failures="0" errors="0">
<testcase name="tensorflow/python/kernel_tests/xent_op_test" status="run"></testcase>
</testsuite>
</testsuites>
``` | /content/code_sandbox/testlogs/python3/2016_07_17/tensorflow/python/kernel_tests/xent_op_test/test.xml | xml | 2016-03-12T06:26:47 | 2024-08-12T19:21:52 | tensorflow-on-raspberry-pi | samjabrahams/tensorflow-on-raspberry-pi | 2,242 | 79 |
```xml
/**
* Generic interface for simple, reliable remote function and method invocation.
*/
export interface TransportClient {
invoke(functionName: string, encodedReq: string): Promise<string>;
}
export type EncodedRequestHandler = (encodedReq: string) => Promise<string>;
export interface TransportServer {
registerInvokeHandler(
functionName: string,
handler: EncodedRequestHandler
): void;
}
``` | /content/code_sandbox/packages/reltab/src/remote/Transport.ts | xml | 2016-10-24T18:59:04 | 2024-08-16T16:29:52 | tad | antonycourtney/tad | 3,125 | 82 |
```xml
export * from './components/MessageBarGroup/index';
``` | /content/code_sandbox/packages/react-components/react-message-bar/library/src/MessageBarGroup.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 12 |
```xml
import { commonTypes, commonInputs, commonFilters } from './common';
export const types = `
type Voucher @key(fields: "_id") @cacheControl(maxAge: 3) {
${commonTypes}
status: String
bonusInfo: JSON
}
type VoucherMain {
list: [Voucher]
totalCount: Int
}
`;
export const queries = `
vouchersMain(${commonFilters}): VoucherMain
vouchers(${commonFilters}): [Voucher]
voucherDetail(_id: String!): Voucher
`;
const VoucherDoc = `
${commonInputs}
status: String
`;
export const mutations = `
vouchersAdd(${VoucherDoc}): Voucher
vouchersEdit(_id: String!, ${VoucherDoc}): Voucher
vouchersRemove(_ids: [String]): JSON
buyVoucher(campaignId: String, ownerType: String, ownerId: String, count: Int): Voucher
`;
``` | /content/code_sandbox/packages/plugin-loyalties-api/src/graphql/schema/voucher.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 207 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
import {createIncident, createSequenceFlows} from 'modules/testUtils';
const mockIncidents = {
count: 1,
incidents: [
createIncident({
errorType: {
name: 'Condition error',
id: 'CONDITION_ERROR',
},
flowNodeId: 'Service5678',
}),
],
errorTypes: [
{
id: 'Condition error',
name: 'Condition error',
count: 1,
},
],
flowNodes: [
{
id: 'Service5678',
name: 'Do something',
count: 1,
},
],
};
const mockSequenceFlows = createSequenceFlows();
export {mockIncidents, mockSequenceFlows};
``` | /content/code_sandbox/operate/client/src/App/ProcessInstance/TopPanel/index.setup.ts | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 186 |
```xml
declare interface IWebChatWebPartStrings {
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
DomainFieldLabel: string;
PropertyPaneDescription: string;
TokenFieldLabel: string;
}
declare module 'WebChatWebPartStrings' {
const strings: IWebChatWebPartStrings;
export = strings;
}
``` | /content/code_sandbox/samples/01.getting-started/l.sharepoint-web-part/src/spfx/src/webparts/webChat/loc/mystrings.d.ts | xml | 2016-07-07T23:16:57 | 2024-08-16T00:12:37 | BotFramework-WebChat | microsoft/BotFramework-WebChat | 1,567 | 105 |
```xml
import spawnAsync from '@expo/spawn-async';
import { type ExpoConfig } from 'expo/config';
import { type ModPlatform } from 'expo/config-plugins';
import fs from 'fs/promises';
import path from 'path';
import { directoryExistsAsync } from './dir';
import { resolveFromExpoCli } from './resolveFromExpoCli';
/**
* Generates native projects for the given platforms.
* This step is similar to the `expo prebuild` command but removes some validation.
* @return The checksum of the template used to generate the native projects.
*/
export async function generateNativeProjectsAsync(
projectRoot: string,
exp: ExpoConfig,
options: {
/** List of platforms to prebuild. */
platforms: ModPlatform[];
/** URL or file path to the prebuild template. */
template?: string;
/** Directory to write the template to before copying into the project. */
templateDirectory: string;
}
): Promise<string> {
const { configureProjectAsync } = require(
resolveFromExpoCli(projectRoot, 'build/src/prebuild/configureProjectAsync')
);
const { resolveTemplateOption } = require(
resolveFromExpoCli(projectRoot, 'build/src/prebuild/resolveOptions')
);
const { cloneTemplateAndCopyToProjectAsync } = require(
resolveFromExpoCli(projectRoot, 'build/src/prebuild/updateFromTemplate')
);
// Create native projects from template.
const { templateChecksum } = await cloneTemplateAndCopyToProjectAsync({
exp,
projectRoot,
template: options.template != null ? resolveTemplateOption(options.template) : undefined,
templateDirectory: options.templateDirectory,
platforms: options.platforms,
});
// Apply config-plugins to native projects.
await configureProjectAsync(projectRoot, {
platforms: options.platforms,
exp,
});
// Install CocoaPods is a must on ios because some changes are happening in the `pod install` stage.
// That would minimize the diff between the native projects.
if (options.platforms.includes('ios')) {
const { installCocoaPodsAsync } = require(
resolveFromExpoCli(projectRoot, 'build/src/utils/cocoapods')
) as typeof import('@expo/cli/src/utils/cocoapods');
await installCocoaPodsAsync(projectRoot);
}
return templateChecksum;
}
/**
* Sanity check for the native project before attempting to run patch-project.
*/
export async function platformSanityCheckAsync({
exp,
projectRoot,
platform,
}: {
exp: ExpoConfig;
projectRoot: string;
platform: ModPlatform;
}): Promise<void> {
// Check platform directory exists and is not empty.
const platformDir = path.join(projectRoot, platform);
if (!(await directoryExistsAsync(platformDir))) {
throw new Error(`Platform directory does not exist: ${platformDir}`);
}
const files = await fs.readdir(platformDir);
if (files.length === 0) {
throw new Error(`Platform directory is empty: ${platformDir}`);
}
// Check package and bundle identifier are defined.
if (platform === 'android' && !exp.android?.package) {
throw new Error(
`android.package is not defined in your app config. Please define it before running this command.`
);
}
if (platform === 'ios' && !exp.ios?.bundleIdentifier) {
throw new Error(
`ios.bundleIdentifier is not defined in your app config. Please define it before running this command.`
);
}
// Check if git is installed.
try {
await spawnAsync('git', ['--version'], { stdio: 'ignore' });
} catch (e: any) {
if (e.code === 'ENOENT') {
e.message += `\nGit is required to run this command. Install Git and try again.`;
}
throw e;
}
}
``` | /content/code_sandbox/packages/patch-project/src/cli/generateNativeProjects.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 839 |
```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.
-->
<manifest xmlns:android="path_to_url"
xmlns:tools="path_to_url">
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
``` | /content/code_sandbox/vertexai/app/src/main/AndroidManifest.xml | xml | 2016-04-26T17:13:27 | 2024-08-16T18:37:58 | quickstart-android | firebase/quickstart-android | 8,797 | 242 |
```xml
<?xml version="1.0" encoding="utf-8"?><!--
~ Meizhi & Gank.io
~
~ 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.
~
~ along with this program. If not, see <path_to_url
~
-->
<set xmlns:android="path_to_url">
<alpha
android:duration="1000"
android:fromAlpha="0"
android:interpolator="@android:anim/decelerate_interpolator"
android:toAlpha="1.0" />
</set>
``` | /content/code_sandbox/app/src/main/res/anim/fade_in.xml | xml | 2016-05-09T05:55:34 | 2024-07-26T07:43:48 | T-MVP | north2016/T-MVP | 2,709 | 184 |
```xml
import React from 'react';
type IconProps = React.SVGProps<SVGSVGElement>;
export declare const IcListNumbers: (props: IconProps) => React.JSX.Element;
export {};
``` | /content/code_sandbox/packages/icons/lib/icListNumbers.d.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 43 |
```xml
<resources xmlns:tools="path_to_url">
<!-- app. -->
<string name="app_name">Vreme</string>
<string name="geometric_weather">Geo Vreme</string>
<!-- keyword. -->
<string name="current_location">Sedanja lokacija</string>
<string name="default_location">Privzeta lokacija</string>
<string name="live">Trenutno</string>
<string name="today">Danes</string>
<string name="refresh_at">Osvei ob</string>
<string name="precipitation">Padavine</string>
<string name="maxi_temp">podnevi</string>
<string name="mini_temp">ponoi</string>
<string name="time">as</string>
<string name="day">dnevni as</string>
<string name="night">noni as</string>
<string name="wind">Veter</string>
<string name="sensible_temp">Senzibilna temp</string>
<string name="humidity">Vlanost</string>
<string name="uv_index">UV indeks</string>
<string name="forecast">Napoved</string>
<string name="briefings">Povzetek</string>
<string name="daytime">Podnevi</string>
<string name="nighttime">Ponoi</string>
<string name="publish_at">Objavi ob</string>
<string name="feels_like">Obuti se</string>
<string name="follow_system">Sledi sistemu</string>
<string name="background_information">Informacije iz ozadja</string>
<string name="pressure">Atmosferski tlak</string>
<string name="visibility">Vidnost</string>
<string name="dew_point">Toka rose</string>
<string name="get_more">Ve</string>
<string name="get_more_store">Ve iz trgovine</string>
<string name="get_more_github">Ve iz GitHuba</string>
<string name="refresh">Osvei</string>
<string name="of_clock">:00</string>
<string name="yesterday">vr</string>
<string name="tomorrow">jtr</string>
<string name="week">teden</string>
<string name="week_1">Pon</string>
<string name="week_2">Tor</string>
<string name="week_3">Sre</string>
<string name="week_4">et</string>
<string name="week_5">Pet</string>
<string name="week_6">Sob</string>
<string name="week_7">Ned</string>
<string name="wind_0">Mirno</string>
<string name="wind_1">Lahen zrak</string>
<string name="wind_2">Lahen vetri</string>
<string name="wind_3">Neen vetri</string>
<string name="wind_4">Zmeren Vetri</string>
<string name="wind_5">Sve vetri</string>
<string name="wind_6">Moen vetri</string>
<string name="wind_7">Konkreten vetri</string>
<string name="wind_8">Veter</string>
<string name="wind_9">Moen veter</string>
<string name="wind_10">Nevihta</string>
<string name="wind_11">Silovita nevihta</string>
<string name="wind_12">Hurikan/Tajfun</string>
<string name="aqi_1">Sve zrak</string>
<string name="aqi_2">ist zrak</string>
<string name="aqi_3">Rahlo onesnaen</string>
<string name="aqi_4">Zmerno onesnaen</string>
<string name="aqi_5">Hudo onesnaenje</string>
<string name="aqi_6">Zelo hudo onesnaenje</string>
<string name="phase_new">Mlada luna</string>
<string name="phase_waxing_crescent">Nastajajoi polmesec</string>
<string name="phase_first">Prva etrina</string>
<string name="phase_waxing_gibbous">Nastajajoa polna luna</string>
<string name="phase_full">Polna luna</string>
<string name="phase_waning_gibbous">Izginjajoa polna luna</string>
<string name="phase_third">Tretja etrtina</string>
<string name="phase_waning_crescent">Izginjajoi polmesec</string>
<string name="daily_overview">Dnevna napoved</string>
<string name="hourly_overview">Urna napoved</string>
<string name="air_quality">Kvaliteta zraka</string>
<string name="life_details">Podrobnosti</string>
<string name="sunrise_sunset">Sonce & luna</string>
<string name="next">NASLEDNJI</string>
<string name="done">KONNANO</string>
<string name="cancel" tools:ignore="ButtonCase">PREKLII</string>
<string name="on">Omogoeno</string>
<string name="off">Onemogoeno</string>
<string name="go_to_set">NASTAVI</string>
<string name="help">POMO</string>
<string name="learn_more">NAUI SE VE</string>
<string name="about_app">O applikaciji</string>
<string name="introduce">predstavi</string>
<string name="email">E-mail</string>
<string name="donate">Doniraj</string>
<string name="gitHub">GitHub</string>
<string name="translator">Prevajalci</string>
<string name="thanks">Hvala</string>
<string name="alipay">Alipay</string>
<string name="wechat">Wechat</string>
<string name="date_format_short">M-d</string>
<string name="date_format_long">MMM d</string>
<string name="date_format_widget_short">EEE, MMM d</string>
<string name="date_format_widget_long">EEEE, MMM d</string>
<string name="date_format_widget_oreo_style">EEEE, MMM d</string>
<!-- feedback. -->
<string name="feedback_request_permission">Dovoljenja</string>
<string name="feedback_request_location">Lokacija</string>
<string name="feedback_request_location_in_background">Lokacija v ozadju</string>
<string name="feedback_request_location_permission_success">Pridobitev dovoljenja za lokacijo je uspela</string>
<string name="feedback_request_location_permission_failed">Pridobitev dovoljenja za lokacijo ni uspela</string>
<string name="feedback_location_failed">Pridobivanje lokacije ni bilo uspeno</string>
<string name="feedback_get_weather_failed">Podatki o vremenu niso na voljo</string>
<string name="feedback_location_help_title">Ni mo najti natanne lokacije?</string>
<string name="feedback_check_location_permission">Preverite dovoljenja lokacije</string>
<string name="feedback_enable_location_information">Omogoite dovoljenja lokacije</string>
<string name="feedback_select_location_provider">Izberite nain pridobivanja lokacije</string>
<string name="feedback_view_style">Nain pogleda</string>
<string name="feedback_show_widget_card">Barva ozadja</string>
<string name="feedback_show_widget_card_alpha">Transparentnost</string>
<string name="feedback_hide_subtitle">Skrij podnapis</string>
<string name="feedback_subtitle_data">Vsedina podnapisov</string>
<string name="feedback_black_text">Barva besedila</string>
<string name="feedback_text_size">Velikost besedila</string>
<string name="feedback_clock_font">Stil ure</string>
<string name="feedback_custom_subtitle_explanation">Tukaj lahko vstavite kar hoete. Prosim bodite pozorni na dolino besedila. e elite navesti podatke o vremenu, prosim uporabite simbol $, se bo nanaal na ustrezen vremenski podatek. \n\n, \"trenutno vreme = $cw$\" bo prikazano kot \"trenutno vreme = ist dan\".</string>
<string name="feedback_live_wallpaper_weather_kind">Vreme</string>
<string name="feedback_live_wallpaper_day_night_type">as</string>
<string name="feedback_click_toggle">Kliknite za graf, e elite spremeniti pogled podatkov</string>
<string name="feedback_no_data">NI PODATKOV</string>
<string name="feedback_collect_failed">Ta lokacija e obstaja</string>
<string name="feedback_collect_succeed">Lokacije je bila uspeno dodana</string>
<string name="feedback_delete_succeed">Lokacija je bila uspeno odstranjena</string>
<string name="feedback_location_list_cannot_be_null">Lokacija ne sme biti prazna</string>
<string name="feedback_search_location">Ii lokacijo</string>
<string name="feedback_not_yet_location">Nobena lokacije e ni bila najdena </string>
<string name="feedback_search_nothing">Nobena lokacija ni bila najdena</string>
<string name="feedback_initializing">Zaenjam</string>
<string name="feedback_refresh_notification_after_back">Spremembe bodo v veljavi, ko se vrnete na domai zaslon</string>
<string name="feedback_refresh_notification_now">Osvei zdaj</string>
<string name="feedback_refresh_ui_after_refresh">Spremembe bodo veljanje ob posodobitvi podatkov</string>
<string name="feedback_restart">Spremembe bodo veljavne po ponovnem zaognu</string>
<string name="feedback_readd_location">Prosim ponovno dodajte lokacije</string>
<string name="feedback_readd_location_after_changing_source">Prosim ponovno dadajte lokacije po spremembi vira podatkov</string>
<string name="feedback_running_in_background">Tee v ozadju za redne posodobitve</string>
<string name="feedback_updating_weather_data">Posodabljanje podatkov o vremenu</string>
<string name="feedback_updated_in_background">Posodobljeno v ozadju</string>
<string name="feedback_cannot_start_live_wallpaper_activity">Predogleda ivega ozadja ni bilo mogoe zaeti.</string>
<string name="feedback_unusable_geocoder">Ta naprava ne vsebuje veljavnega geokoderja. Doloanje lokacije je bilo nastavljeno na Baidu Location.</string>
<string name="feedback_about_geocoder">Geokoder je komponenta, ki pretvori rezultate o lokaciji iz geografskih koordinat v sledei foramt, npr. \'XX mesto, YY provinca \'. V odsotnosti te komponente je mogoe vremenske podatke s pomojo AccuWeather pridobiti z uporabo nativnega API kot primarnega oskrbnika z lokacijo.</string>
<!-- action -->
<string name="action_alert">Opozorilo</string>
<string name="action_manage">Urejaj</string>
<string name="action_search">Ii</string>
<string name="action_settings">Nastavitve</string>
<string name="action_preview">Predogled</string>
<string name="action_about">O tem</string>
<string name="action_appStore">Trgovina aplikacij</string>
<!-- widget -->
<string name="widget_day">Dnevno</string>
<string name="widget_week">Tedensko</string>
<string name="widget_day_week">Dnevno + Tedensko</string>
<string name="widget_clock_day_horizontal">Ura + Dnevno (vodoravno)</string>
<string name="widget_clock_day_details">Ura + Dnevno (podrobnosti)</string>
<string name="widget_clock_day_vertical">Ura + Dnevno (navpino)</string>
<string name="widget_clock_day_week">Ura + Dnevno + Tedensko</string>
<string name="widget_text">Besedilo</string>
<string name="widget_trend_daily">Dnevni trend</string>
<string name="widget_trend_hourly">Urni trendi</string>
<string name="wait_refresh">v akanju</string>
<string name="ellipsis"></string>
<!-- settings -->
<string name="settings_category_basic">Osnove</string>
<string name="settings_title_background_free">Brez ozadja</string>
<string name="settings_summary_background_free_on">Omogoeno\ne se pripomoki in obvestila ne posodobijo samodejno, prosim onemogoite to monost.</string>
<string name="settings_summary_background_free_off">Onemogoeno\ne ne elite elite,da procesi potekajo v ozadju, prosim omogoite to monost.</string>
<string name="settings_title_live_wallpaper">ivo ozadje</string>
<string name="settings_summary_live_wallpaper">Nastavi materilano aniimacijo vremena kot ivo ozadje</string>
<string name="settings_title_service_provider">Ponudnik storitev</string>
<string name="settings_summary_service_provider">Izberite ponudnika vremenskih in lokacijskih storitev</string>
<string name="settings_title_location_service">Dejavnost lokacija</string>
<string name="settings_title_dark_mode">Temen nain</string>
<string name="settings_title_ui_style">Stil uporabnikega vmesnika</string>
<string name="settings_title_icon_provider">Paket ikon</string>
<string name="settings_title_appearance">Izgled</string>
<string name="settings_summary_appearance">Stil uporabnikega vmesnika, vrstni red vremenski podatkov, jezik</string>
<string name="settings_title_card_display">Prikazani vremenski podatki</string>
<string name="settings_title_card_order">Vrstni red vremenskih podatkov</string>
<string name="settings_title_gravity_sensor_switch">Senzor gravitacije</string>
<string name="settings_language">Jezik</string>
<string name="settings_title_unit">Enote</string>
<string name="settings_summary_unit">Nastavi enoto za vremenske podatke</string>
<string name="settings_title_refresh_rate">Samodejen as posodabljanja</string>
<string name="settings_title_alert_notification_switch">Polji opozorilno obvestilo</string>
<string name="settings_title_permanent_service">Stalen proces</string>
<string name="settings_category_forecast">Vremenska napoved</string>
<string name="settings_title_forecast_today">Vremenska napoved za danes</string>
<string name="settings_title_forecast_today_time">as napovedi vremena za danes</string>
<string name="settings_title_forecast_tomorrow">Vremenska napoved za jutri</string>
<string name="settings_title_forecast_tomorrow_time">as napovedi vremena za jutri</string>
<string name="settings_category_widget">Pripomoe</string>
<string name="settings_title_minimal_icon">Minimalistine ikone</string>
<string name="settings_title_click_widget_to_refresh">Osvei obvestilo s klikom</string>
<string name="settings_category_notification">Obvestilo</string>
<string name="settings_title_notification">Polji obvestilo</string>
<string name="settings_title_notification_style">Stil obvesila</string>
<string name="settings_title_notification_temp_icon">Temperatura kot ikona v statusni vrstici</string>
<string name="settings_title_notification_color">Barva obvestila</string>
<string name="settings_title_notification_custom_color">Poljubna barva obvestila</string>
<string name="settings_title_notification_text_color">Barva besedila</string>
<string name="settings_title_notification_background">Barva ozadja</string>
<string name="settings_notification_background_off">Sledi sistemu</string>
<string name="settings_title_notification_can_be_cleared">Je lahko odstranjeno</string>
<string name="settings_notification_can_be_cleared_on">Je lahko odstranjeno s potegom</string>
<string name="settings_notification_can_be_cleared_off">Ne more biti odstranjeno</string>
<string name="settings_title_notification_hide_icon">Skrij ikono obvestila</string>
<string name="settings_notification_hide_icon_on">Skrij</string>
<string name="settings_notification_hide_icon_off">Pokai</string>
<string name="settings_title_notification_hide_in_lockScreen">Skrij na zaslonu zaklepanja</string>
<string name="settings_notification_hide_in_lockScreen_on">Skrij (potrebno odpreti v sistemskih nastavitvah)</string>
<string name="settings_notification_hide_in_lockScreen_off">Pokai</string>
<string name="settings_title_notification_hide_big_view">Razirjen pogled</string>
<string name="settings_notification_hide_big_view_on">Skrij</string>
<string name="settings_notification_hide_big_view_off">Pokai</string>
</resources>
``` | /content/code_sandbox/app/src/main/res/values-sl-rSI/strings.xml | xml | 2016-02-21T04:39:19 | 2024-08-16T13:35:51 | GeometricWeather | WangDaYeeeeee/GeometricWeather | 2,420 | 4,208 |
```xml
<manifest xmlns:android="path_to_url"
package="brian.com.datatool" />
``` | /content/code_sandbox/android/GT_APP/datatool/src/main/AndroidManifest.xml | xml | 2016-01-13T10:29:55 | 2024-08-13T06:40:00 | GT | Tencent/GT | 4,384 | 22 |
```xml
<!-- drawable/information-outline.xml -->
<vector xmlns:android="path_to_url"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="?attr/colorOnPrimaryContainer" android:pathData="M11,9H13V7H11M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M11,17H13V11H11V17Z" />
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_about.xml | xml | 2016-02-21T04:39:19 | 2024-08-16T13:35:51 | GeometricWeather | WangDaYeeeeee/GeometricWeather | 2,420 | 223 |
```xml
import * as useConfigModule from '@proton/components/hooks/useConfig';
import { APPS, CLIENT_TYPES } from '@proton/shared/lib/constants';
import type { ProtonConfig } from '@proton/shared/lib/interfaces';
export const mockUseConfig = (value?: Partial<ProtonConfig>) => {
const spy = vi.spyOn(useConfigModule, 'default');
spy.mockReturnValue({
CLIENT_TYPE: CLIENT_TYPES.MAIL,
CLIENT_SECRET: 'string',
APP_VERSION: '0.0.999999',
APP_NAME: APPS.PROTONMAIL,
API_URL: '',
LOCALES: {},
DATE_VERSION: '',
COMMIT: '',
BRANCH: '',
SENTRY_DSN: '',
VERSION_PATH: '',
...value,
});
return spy;
};
``` | /content/code_sandbox/packages/testing/lib/vitest/mockUseConfig.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 169 |
```xml
import { AccountsServer } from '@accounts/server';
import { type MutationResolvers } from '../models';
export const Mutation: MutationResolvers = {
authenticate: async (_, args, ctx) => {
const { serviceName, params } = args;
const { injector, infos } = ctx;
const authenticated = await injector
.get(AccountsServer)
.loginWithService(serviceName, params, infos);
return authenticated;
},
verifyAuthentication: async (_, args, ctx) => {
const { serviceName, params } = args;
const { injector, infos } = ctx;
const authenticated = await injector
.get(AccountsServer)
.authenticateWithService(serviceName, params, infos);
return authenticated;
},
impersonate: async (_, args, ctx) => {
const { accessToken, impersonated } = args;
const { injector, infos } = ctx;
const impersonateRes = await injector.get(AccountsServer).impersonate(
accessToken,
{
userId: impersonated.userId!,
username: impersonated.username!,
email: impersonated.email!,
},
infos
);
// So ctx.user can be used in subsequent queries / mutations
if (impersonateRes && impersonateRes.user && impersonateRes.tokens) {
ctx.user = impersonateRes.user;
ctx.authToken = impersonateRes.tokens.accessToken;
}
return impersonateRes;
},
logout: async (_, __, context) => {
const { authToken, injector } = context;
if (authToken) {
await injector.get(AccountsServer).logout(authToken);
}
return null;
},
refreshTokens: async (_, args, ctx) => {
const { accessToken, refreshToken } = args;
const { injector, infos } = ctx;
const refreshedSession = await injector
.get(AccountsServer)
.refreshTokens(accessToken, refreshToken, infos);
return refreshedSession;
},
};
``` | /content/code_sandbox/modules/module-core/src/resolvers/mutation.ts | xml | 2016-10-07T01:43:23 | 2024-07-14T11:57:08 | accounts | accounts-js/accounts | 1,492 | 418 |
```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 {
beginAdd,
botHashGenerated,
newNotification,
open as openEditorDocument,
BotAction,
BotActionType,
BotConfigWithPathPayload,
SharedConstants,
} from '@bfemulator/app-shared';
import {
CommandServiceImpl,
CommandServiceInstance,
ConversationService,
StartConversationParams,
uniqueIdv4,
User,
isLocalHostUrl,
} from '@bfemulator/sdk-shared';
import { call, ForkEffect, put, select, takeEvery, takeLatest } from 'redux-saga/effects';
import { ActiveBotHelper } from '../../ui/helpers/activeBotHelper';
import { generateHash } from '../helpers/botHelpers';
import { RootState } from '../store';
import { throwErrorFromResponse } from '../utils/throwErrorFromResponse';
import { SharedSagas } from './sharedSagas';
import { ChatSagas } from './chatSagas';
const getServerUrl = (state: RootState): string => {
return state.clientAwareSettings.serverUrl;
};
const getCustomUserGUID = (state: RootState): string => {
return state.framework.userGUID;
};
export class BotSagas {
@CommandServiceInstance()
private static commandService: CommandServiceImpl;
public static *browseForBot(): IterableIterator<any> {
yield call([ActiveBotHelper, ActiveBotHelper.confirmAndOpenBotFromFile]);
}
public static *generateHashForActiveBot(action: BotAction<BotConfigWithPathPayload>): IterableIterator<any> {
const { bot } = action.payload;
const generatedHash = yield call(generateHash, bot);
yield put(botHashGenerated(generatedHash));
}
public static *openBotViaFilePath(action: BotAction<string>) {
try {
yield call([ActiveBotHelper, ActiveBotHelper.confirmAndOpenBotFromFile], action.payload);
} catch (e) {
const errorNotification = beginAdd(
newNotification(`An Error occurred opening the bot at ${action.payload}: ${e}`)
);
yield put(errorNotification);
}
}
public static *openBotViaUrl(
action: BotAction<StartConversationParams & { isFromBotFile?: boolean }>
): IterableIterator<any> {
const customUserId = yield select(getCustomUserGUID);
const user = {
id: customUserId || uniqueIdv4(), // use custom id or generate new one
name: 'User',
role: 'user',
};
const serverUrl = yield select(getServerUrl);
const payload = {
botUrl: action.payload.endpoint,
channelServiceType: action.payload.channelService,
members: [user],
mode: action.payload.mode,
msaAppId: action.payload.appId,
msaPassword: action.payload.appPassword,
msaTenantId: action.payload.tenantId,
};
let res: Response = yield call([ConversationService, ConversationService.startConversation], serverUrl, payload);
if (!res.ok) {
yield* throwErrorFromResponse('Error occurred while starting a new conversation', res);
}
const {
conversationId,
endpointId,
members,
}: { conversationId: string; endpointId: string; members: User[] } = yield res.json();
const documentId = `${conversationId}`;
// trigger chat saga that will populate the chat object in the store
yield ChatSagas.bootstrapChat({
conversationId,
documentId,
endpointId,
mode: action.payload.mode,
msaAppId: action.payload.appId,
msaPassword: action.payload.appPassword,
randomSeed: action.payload.randomSeed,
randomValue: action.payload.randomValue,
speechKey: action.payload.speechKey,
speechRegion: action.payload.speechRegion,
user,
msaTenantId: action.payload.tenantId,
});
// add a document to the store so the livechat tab is rendered
const { CONTENT_TYPE_DEBUG, CONTENT_TYPE_LIVE_CHAT } = SharedConstants.ContentTypes;
yield put(
openEditorDocument({
contentType: action.payload.mode === 'debug' ? CONTENT_TYPE_DEBUG : CONTENT_TYPE_LIVE_CHAT,
documentId,
isGlobal: false,
})
);
// call emulator to report proper status to chat panel (listening / ngrok)
res = yield ConversationService.sendInitialLogReport(serverUrl, conversationId, action.payload.endpoint);
if (!res.ok) {
yield* throwErrorFromResponse('Error occurred while sending the initial log report', res);
}
// send CU or debug INSPECT message
if (!(action.payload.speechKey && action.payload.speechRegion)) {
res = yield ChatSagas.sendInitialActivities({
conversationId,
members,
mode: action.payload.mode,
randomSeed: action.payload.randomSeed,
randomValue: action.payload.randomValue,
});
if (!res.ok) {
yield* throwErrorFromResponse('Error occurred while sending the initial activity', res);
}
}
// remember the endpoint
yield call(
[BotSagas.commandService, BotSagas.commandService.remoteCall],
SharedConstants.Commands.Settings.SaveBotUrl,
action.payload.endpoint
);
// telemetry
if (!action.payload.isFromBotFile) {
BotSagas.commandService
.remoteCall(SharedConstants.Commands.Telemetry.TrackEvent, 'bot_open', {
numOfServices: 0,
source: 'url',
})
.catch(_ => void 0);
}
BotSagas.commandService
.remoteCall(SharedConstants.Commands.Telemetry.TrackEvent, 'livechat_open', {
isDebug: action.payload.mode === 'debug',
isGov: action.payload.channelService === 'azureusgovernment',
isRemote: !isLocalHostUrl(action.payload.endpoint),
})
.catch(_ => void 0);
}
}
export function* botSagas(): IterableIterator<ForkEffect> {
yield takeEvery(BotActionType.browse, BotSagas.browseForBot);
yield takeEvery(BotActionType.openViaUrl, BotSagas.openBotViaUrl);
yield takeEvery(BotActionType.openViaFilePath, BotSagas.openBotViaFilePath);
yield takeEvery(BotActionType.setActive, BotSagas.generateHashForActiveBot);
yield takeLatest(
[BotActionType.setActive, BotActionType.load, BotActionType.close],
SharedSagas.refreshConversationMenu
);
}
``` | /content/code_sandbox/packages/app/client/src/state/sagas/botSagas.ts | xml | 2016-11-11T23:15:09 | 2024-08-16T12:45:29 | BotFramework-Emulator | microsoft/BotFramework-Emulator | 1,803 | 1,621 |
```xml
import type { Meta, StoryObj } from '@storybook/vue3';
import { ComponentA } from './ts-named-export/component';
const meta = {
component: ComponentA,
tags: ['autodocs'],
} satisfies Meta<typeof ComponentA>;
type Story = StoryObj<typeof meta>;
export default meta;
export const Default: Story = {
args: {
size: 'large',
backgroundColor: 'blue',
},
};
``` | /content/code_sandbox/code/renderers/vue3/template/stories_vue3-vite-default-ts/component-meta/TsNameExport.stories.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 91 |
```xml
declare interface ISuggestedTeamMembersWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'SuggestedTeamMembersWebPartStrings' {
const strings: ISuggestedTeamMembersWebPartStrings;
export = strings;
}
``` | /content/code_sandbox/samples/react-teams-tab-suggested-members/src/webparts/suggestedTeamMembers/loc/mystrings.d.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 62 |
```xml
<?xml version="1.0" encoding="utf-8" ?>
<page version="1.0">
<section layout="row">
<section id="section:box1">
<content>
<hit relevance="1.0" source="news">
<id>news-1</id>
</hit>
<hit relevance="0.5" source="news">
<id>news-2</id>
</hit>
<hit relevance="0.3333333333333333" source="news">
<id>news-3</id>
</hit>
</content>
</section>
<section id="section:box2">
<content>
<hit relevance="1.0" source="web">
<id>web-1</id>
</hit>
<hit relevance="0.5" source="web">
<id>web-2</id>
</hit>
<hit relevance="0.3333333333333333" source="web">
<id>web-3</id>
</hit>
</content>
</section>
</section>
<section layout="row">
<section id="section:box3">
<content>
<hit relevance="1.0" source="blog">
<id>blog-1</id>
</hit>
<hit relevance="0.5" source="blog">
<id>blog-2</id>
</hit>
<hit relevance="0.3333333333333333" source="blog">
<id>blog-3</id>
</hit>
</content>
</section>
<section id="section:box4">
<content>
<hit relevance="1.0" source="images">
<id>images-1</id>
</hit>
<hit relevance="0.5" source="images">
<id>images-2</id>
</hit>
<hit relevance="0.3333333333333333" source="images">
<id>images-3</id>
</hit>
</content>
</section>
</section>
</page>
``` | /content/code_sandbox/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesResult.xml | xml | 2016-06-03T20:54:20 | 2024-08-16T15:32:01 | vespa | vespa-engine/vespa | 5,524 | 481 |
```xml
import { Component } from '@angular/core';
import { Code } from '@domain/code';
@Component({
selector: 'builtin-themes-doc',
template: `
<app-docsectiontext>
<p>
PrimeNG ships with various free themes to choose from. The list below states all the available themes in the npm distribution with import paths. For a live preview, use the configurator
<span class="border-round inline-flex border-1 w-2rem h-2rem p-0 align-items-center justify-content-center bg-primary"><span class="pi pi-palette"></span></span> at the topbar to switch themes.
</p>
</app-docsectiontext>
<div class="h-20rem overflow-auto">
<app-code [code]="code" [hideToggleCode]="true"></app-code>
</div>
`
})
export class BuiltInThemesDoc {
code: Code = {
basic: `primeng/resources/themes/bootstrap4-light-blue/theme.css
primeng/resources/themes/bootstrap4-light-purple/theme.css
primeng/resources/themes/bootstrap4-dark-blue/theme.css
primeng/resources/themes/bootstrap4-dark-purple/theme.css
primeng/resources/themes/md-light-indigo/theme.css
primeng/resources/themes/md-light-deeppurple/theme.css
primeng/resources/themes/md-dark-indigo/theme.css
primeng/resources/themes/md-dark-deeppurple/theme.css
primeng/resources/themes/mdc-light-indigo/theme.css
primeng/resources/themes/mdc-light-deeppurple/theme.css
primeng/resources/themes/mdc-dark-indigo/theme.css
primeng/resources/themes/mdc-dark-deeppurple/theme.css
primeng/resources/themes/fluent-light/theme.css
primeng/resources/themes/lara-light-blue/theme.css
primeng/resources/themes/lara-light-indigo/theme.css
primeng/resources/themes/lara-light-purple/theme.css
primeng/resources/themes/lara-light-teal/theme.css
primeng/resources/themes/lara-dark-blue/theme.css
primeng/resources/themes/lara-dark-indigo/theme.css
primeng/resources/themes/lara-dark-purple/theme.css
primeng/resources/themes/lara-dark-teal/theme.css
primeng/resources/themes/soho-light/theme.css
primeng/resources/themes/soho-dark/theme.css
primeng/resources/themes/viva-light/theme.css
primeng/resources/themes/viva-dark/theme.css
primeng/resources/themes/mira/theme.css
primeng/resources/themes/nano/theme.css
primeng/resources/themes/saga-blue/theme.css
primeng/resources/themes/saga-green/theme.css
primeng/resources/themes/saga-orange/theme.css
primeng/resources/themes/saga-purple/theme.css
primeng/resources/themes/vela-blue/theme.css
primeng/resources/themes/vela-green/theme.css
primeng/resources/themes/vela-orange/theme.css
primeng/resources/themes/vela-purple/theme.css
primeng/resources/themes/arya-blue/theme.css
primeng/resources/themes/arya-green/theme.css
primeng/resources/themes/arya-orange/theme.css
primeng/resources/themes/arya-purple/theme.css
primeng/resources/themes/nova/theme.css
primeng/resources/themes/nova-alt/theme.css
primeng/resources/themes/nova-accent/theme.css
primeng/resources/themes/luna-amber/theme.css
primeng/resources/themes/luna-blue/theme.css
primeng/resources/themes/luna-green/theme.css
primeng/resources/themes/luna-pink/theme.css
primeng/resources/themes/rhea/theme.css`
};
}
``` | /content/code_sandbox/src/app/showcase/doc/theming/builtinthemesdoc.ts | xml | 2016-01-16T09:23:28 | 2024-08-16T19:58:20 | primeng | primefaces/primeng | 9,969 | 715 |
```xml
/*your_sha256_hash-----------------------------
*your_sha256_hash----------------------------*/
import type { languages } from '../../fillers/monaco-editor-core';
export const conf: languages.LanguageConfiguration = {
comments: {
lineComment: '//'
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '"', close: '"', notIn: ['string', 'comment'] },
{ open: "'", close: "'", notIn: ['string', 'comment'] },
{ open: '{', close: '}', notIn: ['string', 'comment'] },
{ open: '[', close: ']', notIn: ['string', 'comment'] },
{ open: '(', close: ')', notIn: ['string', 'comment'] }
],
folding: {
offSide: true
}
};
export const language = <languages.IMonarchLanguage>{
defaultToken: '',
tokenPostfix: '.pug',
ignoreCase: true,
brackets: [
{ token: 'delimiter.curly', open: '{', close: '}' },
{ token: 'delimiter.array', open: '[', close: ']' },
{ token: 'delimiter.parenthesis', open: '(', close: ')' }
],
keywords: [
'append',
'block',
'case',
'default',
'doctype',
'each',
'else',
'extends',
'for',
'if',
'in',
'include',
'mixin',
'typeof',
'unless',
'var',
'when'
],
tags: [
'a',
'abbr',
'acronym',
'address',
'area',
'article',
'aside',
'audio',
'b',
'base',
'basefont',
'bdi',
'bdo',
'blockquote',
'body',
'br',
'button',
'canvas',
'caption',
'center',
'cite',
'code',
'col',
'colgroup',
'command',
'datalist',
'dd',
'del',
'details',
'dfn',
'div',
'dl',
'dt',
'em',
'embed',
'fieldset',
'figcaption',
'figure',
'font',
'footer',
'form',
'frame',
'frameset',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'head',
'header',
'hgroup',
'hr',
'html',
'i',
'iframe',
'img',
'input',
'ins',
'keygen',
'kbd',
'label',
'li',
'link',
'map',
'mark',
'menu',
'meta',
'meter',
'nav',
'noframes',
'noscript',
'object',
'ol',
'optgroup',
'option',
'output',
'p',
'param',
'pre',
'progress',
'q',
'rp',
'rt',
'ruby',
's',
'samp',
'script',
'section',
'select',
'small',
'source',
'span',
'strike',
'strong',
'style',
'sub',
'summary',
'sup',
'table',
'tbody',
'td',
'textarea',
'tfoot',
'th',
'thead',
'time',
'title',
'tr',
'tracks',
'tt',
'u',
'ul',
'video',
'wbr'
],
// we include these common regular expressions
symbols: /[\+\-\*\%\&\|\!\=\/\.\,\:]+/,
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
tokenizer: {
root: [
// Tag or a keyword at start
[
/^(\s*)([a-zA-Z_-][\w-]*)/,
{
cases: {
'$2@tags': {
cases: {
'@eos': ['', 'tag'],
'@default': ['', { token: 'tag', next: '@tag.$1' }]
}
},
'$2@keywords': ['', { token: 'keyword.$2' }],
'@default': ['', '']
}
}
],
// id
[
/^(\s*)(#[a-zA-Z_-][\w-]*)/,
{
cases: {
'@eos': ['', 'tag.id'],
'@default': ['', { token: 'tag.id', next: '@tag.$1' }]
}
}
],
// class
[
/^(\s*)(\.[a-zA-Z_-][\w-]*)/,
{
cases: {
'@eos': ['', 'tag.class'],
'@default': ['', { token: 'tag.class', next: '@tag.$1' }]
}
}
],
// plain text with pipe
[/^(\s*)(\|.*)$/, ''],
{ include: '@whitespace' },
// keywords
[
/[a-zA-Z_$][\w$]*/,
{
cases: {
'@keywords': { token: 'keyword.$0' },
'@default': ''
}
}
],
// delimiters and operators
[/[{}()\[\]]/, '@brackets'],
[/@symbols/, 'delimiter'],
// numbers
[/\d+\.\d+([eE][\-+]?\d+)?/, 'number.float'],
[/\d+/, 'number'],
// strings:
[/"/, 'string', '@string."'],
[/'/, 'string', "@string.'"]
],
tag: [
[/(\.)(\s*$)/, [{ token: 'delimiter', next: '@blockText.$S2.' }, '']],
[/\s+/, { token: '', next: '@simpleText' }],
// id
[
/#[a-zA-Z_-][\w-]*/,
{
cases: {
'@eos': { token: 'tag.id', next: '@pop' },
'@default': 'tag.id'
}
}
],
// class
[
/\.[a-zA-Z_-][\w-]*/,
{
cases: {
'@eos': { token: 'tag.class', next: '@pop' },
'@default': 'tag.class'
}
}
],
// attributes
[/\(/, { token: 'delimiter.parenthesis', next: '@attributeList' }]
],
simpleText: [
[/[^#]+$/, { token: '', next: '@popall' }],
[/[^#]+/, { token: '' }],
// interpolation
[
/(#{)([^}]*)(})/,
{
cases: {
'@eos': [
'interpolation.delimiter',
'interpolation',
{
token: 'interpolation.delimiter',
next: '@popall'
}
],
'@default': ['interpolation.delimiter', 'interpolation', 'interpolation.delimiter']
}
}
],
[/#$/, { token: '', next: '@popall' }],
[/#/, '']
],
attributeList: [
[/\s+/, ''],
[
/(\w+)(\s*=\s*)("|')/,
['attribute.name', 'delimiter', { token: 'attribute.value', next: '@value.$3' }]
],
[/\w+/, 'attribute.name'],
[
/,/,
{
cases: {
'@eos': {
token: 'attribute.delimiter',
next: '@popall'
},
'@default': 'attribute.delimiter'
}
}
],
[/\)$/, { token: 'delimiter.parenthesis', next: '@popall' }],
[/\)/, { token: 'delimiter.parenthesis', next: '@pop' }]
],
whitespace: [
[/^(\s*)(\/\/.*)$/, { token: 'comment', next: '@blockText.$1.comment' }],
[/[ \t\r\n]+/, ''],
[/<!--/, { token: 'comment', next: '@comment' }]
],
blockText: [
[
/^\s+.*$/,
{
cases: {
'($S2\\s+.*$)': { token: '$S3' },
'@default': { token: '@rematch', next: '@popall' }
}
}
],
[/./, { token: '@rematch', next: '@popall' }]
],
comment: [
[/[^<\-]+/, 'comment.content'],
[/-->/, { token: 'comment', next: '@pop' }],
[/<!--/, 'comment.content.invalid'],
[/[<\-]/, 'comment.content']
],
string: [
[
/[^\\"'#]+/,
{
cases: {
'@eos': { token: 'string', next: '@popall' },
'@default': 'string'
}
}
],
[
/@escapes/,
{
cases: {
'@eos': { token: 'string.escape', next: '@popall' },
'@default': 'string.escape'
}
}
],
[
/\\./,
{
cases: {
'@eos': {
token: 'string.escape.invalid',
next: '@popall'
},
'@default': 'string.escape.invalid'
}
}
],
// interpolation
[/(#{)([^}]*)(})/, ['interpolation.delimiter', 'interpolation', 'interpolation.delimiter']],
[/#/, 'string'],
[
/["']/,
{
cases: {
'$#==$S2': { token: 'string', next: '@pop' },
'@default': { token: 'string' }
}
}
]
],
// Almost identical to above, except for escapes and the output token
value: [
[
/[^\\"']+/,
{
cases: {
'@eos': { token: 'attribute.value', next: '@popall' },
'@default': 'attribute.value'
}
}
],
[
/\\./,
{
cases: {
'@eos': { token: 'attribute.value', next: '@popall' },
'@default': 'attribute.value'
}
}
],
[
/["']/,
{
cases: {
'$#==$S2': { token: 'attribute.value', next: '@pop' },
'@default': { token: 'attribute.value' }
}
}
]
]
}
};
``` | /content/code_sandbox/src/basic-languages/pug/pug.ts | xml | 2016-06-07T16:56:31 | 2024-08-16T17:17:05 | monaco-editor | microsoft/monaco-editor | 39,508 | 2,793 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FlexmarkExt.ModuleBuildProperties">
<option name="extensionName" value="Util" />
<option name="extensionPackage" value="com.vladsch.flexmark.util.builder" />
<option name="delimiterProcessor" value="false" />
<option name="blockParser" value="false" />
<option name="blockPreProcessor" value="false" />
<option name="linkRefProcessor" value="false" />
<option name="paragraphPreProcessor" value="false" />
<option name="nodePostProcessor" value="false" />
<option name="documentPostProcessor" value="false" />
<option name="nodeRenderer" value="false" />
<option name="customBlockNode" value="false" />
<option name="customNode" value="false" />
<option name="customNodeRepository" value="false" />
<option name="customProperties" value="false" />
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.13" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" name="org.jetbrains:annotations" level="project" />
<orderEntry type="module" module-name="flexmark-util-data" />
<orderEntry type="module" module-name="flexmark-util-misc" />
</component>
</module>
``` | /content/code_sandbox/flexmark-util-builder/flexmark-util-builder.iml | xml | 2016-01-23T15:29:29 | 2024-08-15T04:04:18 | flexmark-java | vsch/flexmark-java | 2,239 | 508 |
```xml
import { IPositionStats, IScrollState, IScrollerDistance } from '../../models';
export function shouldFireScrollEvent(
container: IPositionStats,
distance: IScrollerDistance = { down: 0, up: 0 },
scrollingDown: boolean
) {
let remaining: number;
let containerBreakpoint: number;
if (container.totalToScroll <= 0) {
return false;
}
const scrolledUntilNow = container.isWindow
? container.scrolled
: container.height + container.scrolled;
if (scrollingDown) {
remaining =
(container.totalToScroll - scrolledUntilNow) / container.totalToScroll;
const distanceDown = distance?.down ? distance.down : 0;
containerBreakpoint = distanceDown / 10;
} else {
const totalHiddenContentHeight =
container.scrolled + (container.totalToScroll - scrolledUntilNow);
remaining = container.scrolled / totalHiddenContentHeight;
const distanceUp = distance?.up ? distance.up : 0;
containerBreakpoint = distanceUp / 10;
}
const shouldFireEvent: boolean = remaining <= containerBreakpoint;
return shouldFireEvent;
}
export function isScrollingDownwards(
lastScrollPosition: number,
container: IPositionStats
) {
return lastScrollPosition < container.scrolled;
}
export function getScrollStats(
lastScrollPosition: number,
container: IPositionStats,
distance: IScrollerDistance
) {
const scrollDown = isScrollingDownwards(lastScrollPosition, container);
return {
fire: shouldFireScrollEvent(container, distance, scrollDown),
scrollDown,
};
}
export function updateScrollPosition(
position: number,
scrollState: IScrollState
) {
return (scrollState.lastScrollPosition = position);
}
export function updateTotalToScroll(
totalToScroll: number,
scrollState: IScrollState
) {
if (scrollState.lastTotalToScroll !== totalToScroll) {
scrollState.lastTotalToScroll = scrollState.totalToScroll;
scrollState.totalToScroll = totalToScroll;
}
}
export function isSameTotalToScroll(scrollState: IScrollState) {
return scrollState.totalToScroll === scrollState.lastTotalToScroll;
}
export function updateTriggeredFlag(
scroll: number,
scrollState: IScrollState,
triggered: boolean,
isScrollingDown: boolean
) {
if (isScrollingDown) {
scrollState.triggered.down = scroll;
} else {
scrollState.triggered.up = scroll;
}
}
export function isTriggeredScroll(
totalToScroll: number,
scrollState: IScrollState,
isScrollingDown: boolean
) {
return isScrollingDown
? scrollState.triggered.down === totalToScroll
: scrollState.triggered.up === totalToScroll;
}
export function updateScrollState(
scrollState: IScrollState,
scrolledUntilNow: number,
totalToScroll: number
) {
updateScrollPosition(scrolledUntilNow, scrollState);
updateTotalToScroll(totalToScroll, scrollState);
// const isSameTotal = isSameTotalToScroll(scrollState);
// if (!isSameTotal) {
// updateTriggeredFlag(scrollState, false, isScrollingDown);
// }
}
``` | /content/code_sandbox/projects/ngx-infinite-scroll/src/lib/services/scroll-resolver.ts | xml | 2016-02-05T09:19:39 | 2024-08-15T16:17:38 | ngx-infinite-scroll | orizens/ngx-infinite-scroll | 1,231 | 727 |
```xml
import { BrushHighlight } from './brushHighlight';
export function brushYRegion(x, y, x1, y1, extent) {
const [minX, , maxX] = extent;
return [minX, y, maxX, y1];
}
export function BrushYHighlight(options) {
return BrushHighlight({
...options,
brushRegion: brushYRegion,
selectedHandles: ['handle-n', 'handle-s'],
});
}
``` | /content/code_sandbox/src/interaction/brushYHighlight.ts | xml | 2016-05-26T09:21:04 | 2024-08-15T16:11:17 | G2 | antvis/G2 | 12,060 | 95 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
import {render, screen} from 'modules/testing-library';
import noop from 'lodash/noop';
import {OperationItems} from '../';
import {OperationItem} from '../../OperationItem';
describe('Modification Mode', () => {
it('should show the correct icon based on the type', () => {
render(
<OperationItems>
<OperationItem
type="ENTER_MODIFICATION_MODE"
onClick={noop}
title="modify process instance"
/>
</OperationItems>,
);
expect(screen.getByTestId('enter-modification-mode')).toBeInTheDocument();
});
it('should render modify button', () => {
const BUTTON_TITLE = 'Modify Instance 1';
render(
<OperationItems>
<OperationItem
type="ENTER_MODIFICATION_MODE"
onClick={noop}
title={BUTTON_TITLE}
/>
</OperationItems>,
);
expect(
screen.getByRole('button', {name: BUTTON_TITLE}),
).toBeInTheDocument();
});
it('should execute callback function', async () => {
const BUTTON_TITLE = 'Modify Instance 1';
const MOCK_ON_CLICK = jest.fn();
const {user} = render(
<OperationItems>
<OperationItem
type="ENTER_MODIFICATION_MODE"
onClick={MOCK_ON_CLICK}
title={BUTTON_TITLE}
/>
</OperationItems>,
);
await user.click(screen.getByRole('button', {name: BUTTON_TITLE}));
expect(MOCK_ON_CLICK).toHaveBeenCalled();
});
});
``` | /content/code_sandbox/operate/client/src/modules/components/OperationItems/tests/modificationMode.test.tsx | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 341 |
```xml
<dict>
<key>LayoutID</key>
<integer>3</integer>
<key>PathMapRef</key>
<array>
<dict>
<key>CodecID</key>
<array>
<integer>283902594</integer>
</array>
<key>Headphone</key>
<dict/>
<key>Inputs</key>
<array>
<string>Mic</string>
<string>LineIn</string>
</array>
<key>IntSpeaker</key>
<dict/>
<key>LineIn</key>
<dict>
<key>MuteGPIO</key>
<integer>1342242841</integer>
<key>SignalProcessing</key>
<dict>
<key>SoftwareDSP</key>
<dict>
<key>DspFunction0</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>0</integer>
<key>DspFuncName</key>
<string>DspNoiseReduction</string>
<key>DspFuncProcessingIndex</key>
<integer>0</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>-1073029587</integer>
<key>5</key>
<data>your_sha256_hashHMuYwrl9lcJXm4/CBhmQwuJvlMKbxJTC7qyUwtjDl8KU+ZzCnCaewsmuncK/your_sha512_hash+your_sha256_hashyour_sha256_hashfwhFzosLIZaPCwUOjwo6TosIkR6LC6vehwtrwosIdtJ/CXLmbwlSZmcKDhJXCDFGRwnV6j8JTjY/CrqGQwgqYk8INzpjCuTufwrjlocKviKPC5YqlwgdmpcKZ2aXCGiumwq95osJOIJ/Cxl+ewtWGl8KmPJPC+sSawkdHo8JWB6LCskyhwqk7pcIth6nCh4Wswk+crcK9J6zCYJWqwmVJq8K8063Cyour_sha512_hash+M0MKaftbCpcjdwm+p5sL/CfHCHcT8wrp3A8PiJAzD</data>
</dict>
<key>PatchbayInfo</key>
<dict/>
</dict>
<key>DspFunction1</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>1</integer>
<key>DspFuncName</key>
<string>DspEqualization32</string>
<key>DspFuncProcessingIndex</key>
<integer>1</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>9</key>
<integer>0</integer>
<key>Filter</key>
<array>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>1</integer>
<key>6</key>
<integer>1119939268</integer>
<key>7</key>
<integer>1060439283</integer>
<key>8</key>
<integer>-1069504319</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>4</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1165674830</integer>
<key>7</key>
<integer>1106304591</integer>
<key>8</key>
<integer>-1073964333</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>5</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1141348835</integer>
<key>7</key>
<integer>1084737706</integer>
<key>8</key>
<integer>-1065063953</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>6</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1139052693</integer>
<key>7</key>
<integer>1080938866</integer>
<key>8</key>
<integer>-1073319056</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>8</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1161958655</integer>
<key>7</key>
<integer>1099668786</integer>
<key>8</key>
<integer>-1073319056</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>9</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1148922426</integer>
<key>7</key>
<integer>1086508776</integer>
<key>8</key>
<integer>-1076100424</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>10</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1169908270</integer>
<key>7</key>
<integer>1106659062</integer>
<key>8</key>
<integer>-1078236516</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>11</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1168889995</integer>
<key>7</key>
<integer>1103911084</integer>
<key>8</key>
<integer>-1082886964</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>12</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1160729473</integer>
<key>7</key>
<integer>1095247586</integer>
<key>8</key>
<integer>-1076100424</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>19</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1171440929</integer>
<key>7</key>
<integer>1103785747</integer>
<key>8</key>
<integer>-1075032379</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>21</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1163187837</integer>
<key>7</key>
<integer>1102690138</integer>
<key>8</key>
<integer>-1073319056</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>23</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1172459204</integer>
<key>7</key>
<integer>1098523915</integer>
<key>8</key>
<integer>-1062927862</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>24</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1175303133</integer>
<key>7</key>
<integer>1102375714</integer>
<key>8</key>
<integer>-1061058782</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>25</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1179874390</integer>
<key>7</key>
<integer>1097945441</integer>
<key>8</key>
<integer>-1054338996</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>26</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1167504019</integer>
<key>7</key>
<integer>1102555367</integer>
<key>8</key>
<integer>-1044515201</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>27</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1177335863</integer>
<key>7</key>
<integer>1102845396</integer>
<key>8</key>
<integer>-1054739513</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>31</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>0</integer>
<key>6</key>
<integer>1184146588</integer>
<key>7</key>
<integer>1060439283</integer>
<key>8</key>
<integer>-1069504319</integer>
</dict>
</array>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
<key>DspFunction2</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>2</integer>
<key>DspFuncName</key>
<string>DspGainStage</string>
<key>DspFuncProcessingIndex</key>
<integer>2</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>1065353216</integer>
<key>3</key>
<integer>1065353216</integer>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
</dict>
</dict>
</dict>
<key>Mic</key>
<dict>
<key>MuteGPIO</key>
<integer>0</integer>
<key>SignalProcessing</key>
<dict>
<key>SoftwareDSP</key>
<dict>
<key>DspFunction0</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>0</integer>
<key>DspFuncName</key>
<string>DspNoiseReduction</string>
<key>DspFuncProcessingIndex</key>
<integer>0</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>1</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>-1073029587</integer>
<key>5</key>
<data>your_sha256_hashHMuYwrl9lcJXm4/CBhmQwuJvlMKbxJTC7qyUwtjDl8KU+ZzCnCaewsmuncK/your_sha512_hash+your_sha256_hashyour_sha256_hashfwhFzosLIZaPCwUOjwo6TosIkR6LC6vehwtrwosIdtJ/CXLmbwlSZmcKDhJXCDFGRwnV6j8JTjY/CrqGQwgqYk8INzpjCuTufwrjlocKviKPC5YqlwgdmpcKZ2aXCGiumwq95osJOIJ/Cxl+ewtWGl8KmPJPC+sSawkdHo8JWB6LCskyhwqk7pcIth6nCh4Wswk+crcK9J6zCYJWqwmVJq8K8063Cyour_sha512_hash+M0MKaftbCpcjdwm+p5sL/CfHCHcT8wrp3A8PiJAzD</data>
</dict>
<key>PatchbayInfo</key>
<dict/>
</dict>
<key>DspFunction1</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>1</integer>
<key>DspFuncName</key>
<string>DspEqualization32</string>
<key>DspFuncProcessingIndex</key>
<integer>1</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>9</key>
<integer>0</integer>
<key>Filter</key>
<array>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>1</integer>
<key>6</key>
<integer>1119939268</integer>
<key>7</key>
<integer>1060439283</integer>
<key>8</key>
<integer>-1069504319</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>4</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1165674830</integer>
<key>7</key>
<integer>1106304591</integer>
<key>8</key>
<integer>-1073964333</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>5</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1141348835</integer>
<key>7</key>
<integer>1084737706</integer>
<key>8</key>
<integer>-1065063953</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>6</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1139052693</integer>
<key>7</key>
<integer>1080938866</integer>
<key>8</key>
<integer>-1073319056</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>8</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1161958655</integer>
<key>7</key>
<integer>1099668786</integer>
<key>8</key>
<integer>-1073319056</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>9</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1148922426</integer>
<key>7</key>
<integer>1086508776</integer>
<key>8</key>
<integer>-1076100424</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>10</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1169908270</integer>
<key>7</key>
<integer>1106659062</integer>
<key>8</key>
<integer>-1078236516</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>11</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1168889995</integer>
<key>7</key>
<integer>1103911084</integer>
<key>8</key>
<integer>-1082886964</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>12</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1160729473</integer>
<key>7</key>
<integer>1095247586</integer>
<key>8</key>
<integer>-1076100424</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>19</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1171440929</integer>
<key>7</key>
<integer>1103785747</integer>
<key>8</key>
<integer>-1075032379</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>21</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1163187837</integer>
<key>7</key>
<integer>1102690138</integer>
<key>8</key>
<integer>-1073319056</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>23</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1172459204</integer>
<key>7</key>
<integer>1098523915</integer>
<key>8</key>
<integer>-1062927862</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>24</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1175303133</integer>
<key>7</key>
<integer>1102375714</integer>
<key>8</key>
<integer>-1061058782</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>25</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1179874390</integer>
<key>7</key>
<integer>1097945441</integer>
<key>8</key>
<integer>-1054338996</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>26</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1167504019</integer>
<key>7</key>
<integer>1102555367</integer>
<key>8</key>
<integer>-1044515201</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>27</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1177335863</integer>
<key>7</key>
<integer>1102845396</integer>
<key>8</key>
<integer>-1054739513</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>31</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>0</integer>
<key>6</key>
<integer>1184146588</integer>
<key>7</key>
<integer>1060439283</integer>
<key>8</key>
<integer>-1069504319</integer>
</dict>
</array>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
<key>DspFunction2</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>2</integer>
<key>DspFuncName</key>
<string>DspGainStage</string>
<key>DspFuncProcessingIndex</key>
<integer>2</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>1065353216</integer>
<key>3</key>
<integer>1065353216</integer>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
</dict>
</dict>
</dict>
<key>Outputs</key>
<array>
<string>Headphone</string>
<string>IntSpeaker</string>
</array>
<key>PathMapID</key>
<integer>282</integer>
</dict>
</array>
</dict>
``` | /content/code_sandbox/Resources/ALC282/layout3.xml | xml | 2016-03-07T20:45:58 | 2024-08-14T08:57:03 | AppleALC | acidanthera/AppleALC | 3,420 | 7,844 |
```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>{BE228814-A8FE-45F3-91A8-5F73AD61AB02}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>Shadows</RootNamespace>
<WindowsTargetPlatformVersion>10.0.10240.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<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>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<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>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\Common\Camera.cpp" />
<ClCompile Include="..\..\Common\d3dApp.cpp" />
<ClCompile Include="..\..\Common\d3dUtil.cpp" />
<ClCompile Include="..\..\Common\DDSTextureLoader.cpp" />
<ClCompile Include="..\..\Common\GameTimer.cpp" />
<ClCompile Include="..\..\Common\GeometryGenerator.cpp" />
<ClCompile Include="..\..\Common\MathHelper.cpp" />
<ClCompile Include="FrameResource.cpp" />
<ClCompile Include="ShadowMap.cpp" />
<ClCompile Include="ShadowMapApp.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\Common\Camera.h" />
<ClInclude Include="..\..\Common\d3dApp.h" />
<ClInclude Include="..\..\Common\d3dUtil.h" />
<ClInclude Include="..\..\Common\d3dx12.h" />
<ClInclude Include="..\..\Common\DDSTextureLoader.h" />
<ClInclude Include="..\..\Common\GameTimer.h" />
<ClInclude Include="..\..\Common\GeometryGenerator.h" />
<ClInclude Include="..\..\Common\MathHelper.h" />
<ClInclude Include="..\..\Common\UploadBuffer.h" />
<ClInclude Include="FrameResource.h" />
<ClInclude Include="ShadowMap.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
``` | /content/code_sandbox/Chapter 20 Shadow Mapping/Shadows/Shadows.vcxproj | xml | 2016-03-25T04:33:36 | 2024-08-16T10:32:50 | d3d12book | d3dcoder/d3d12book | 1,487 | 2,025 |
```xml
describe('Dropdown', () => {
const selectors: any = { triggerButtonClass: 'ui-dropdown__trigger-button' };
const dropdownSlotClassNames: any = {
clearIndicator: 'ui-dropdown__clear-indicator',
container: 'ui-dropdown__container',
toggleIndicator: 'ui-dropdown__toggle-indicator',
item: 'ui-dropdown__item',
itemsList: 'ui-dropdown__items-list',
searchInput: 'ui-dropdown__searchinput',
selectedItem: 'ui-dropdown__selecteditem',
selectedItems: 'ui-dropdown__selected-items',
triggerButton: 'ui-dropdown__trigger-button',
};
const triggerButton = `.${selectors.triggerButtonClass}`;
const list = `.${dropdownSlotClassNames.itemsList}`;
describe('Focus behavior', () => {
beforeEach(() => {
cy.gotoTestCase(__filename, triggerButton);
});
it('keeps focused on TAB from the dropdown list', () => {
cy.focusOn(triggerButton);
cy.waitForSelectorAndPressKey(triggerButton, '{downarrow}'); // open dropdown list
cy.waitForSelectorAndPressKey(list, 'Tab'); // TAB from opened dropdown list
cy.isFocused(triggerButton);
});
it('keeps focused on Shift+TAB from the dropdown list', () => {
cy.focusOn(triggerButton);
cy.waitForSelectorAndPressKey(triggerButton, '{downarrow}'); // open dropdown list
cy.waitForSelectorAndPressKey(list, 'Tab', 'Shift'); // Shift+TAB from opened dropdown list
cy.isFocused(triggerButton);
});
});
});
``` | /content/code_sandbox/packages/fluentui/e2e/tests/dropdown.spec.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 338 |
```xml
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "../../../../../src"
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column({ default: () => "CURRENT_TIMESTAMP" })
col1: Date
@Column({ default: () => "CURRENT_TIMESTAMP(3)" })
col2: Date
@Column({ default: () => "current_timestamp" })
col3: Date
@Column({ default: () => "CURRENT_DATE" })
col4: Date
@Column({ default: () => "current_date" })
col5: Date
@Column({ default: () => "LOCALTIMESTAMP" })
col6: Date
@Column({ default: () => "LOCALTIMESTAMP(3)" })
col7: Date
@Column({ default: () => "localtimestamp" })
col8: Date
@Column({ default: () => "SYSDATE" })
col9: Date
@Column({ default: () => "sysdate" })
col10: Date
@Column({ default: () => "SYSTIMESTAMP" })
col11: Date
@Column({ default: () => "SYSTIMESTAMP(3)" })
col12: Date
@Column({ default: () => "systimestamp" })
col13: Date
@CreateDateColumn({ default: () => "CURRENT_TIMESTAMP" })
col14: Date
@CreateDateColumn({ default: () => "CURRENT_TIMESTAMP(3)" })
col15: Date
@CreateDateColumn({ default: () => "current_timestamp" })
col16: Date
@CreateDateColumn({ default: () => "CURRENT_DATE" })
col17: Date
@CreateDateColumn({ default: () => "current_date" })
col18: Date
@CreateDateColumn({ default: () => "LOCALTIMESTAMP" })
col19: Date
@CreateDateColumn({ default: () => "LOCALTIMESTAMP(3)" })
col20: Date
@CreateDateColumn({ default: () => "localtimestamp" })
col21: Date
@CreateDateColumn({ default: () => "SYSDATE" })
col22: Date
@CreateDateColumn({ default: () => "sysdate" })
col23: Date
@CreateDateColumn({ default: () => "SYSTIMESTAMP" })
col24: Date
@CreateDateColumn({ default: () => "SYSTIMESTAMP(3)" })
col25: Date
@CreateDateColumn({ default: () => "systimestamp" })
col26: Date
@UpdateDateColumn({ default: () => "CURRENT_TIMESTAMP" })
col27: Date
@UpdateDateColumn({ default: () => "CURRENT_TIMESTAMP(3)" })
col28: Date
@UpdateDateColumn({ default: () => "current_timestamp" })
col29: Date
@UpdateDateColumn({ default: () => "CURRENT_DATE" })
col30: Date
@UpdateDateColumn({ default: () => "current_date" })
col31: Date
@UpdateDateColumn({ default: () => "LOCALTIMESTAMP" })
col32: Date
@UpdateDateColumn({ default: () => "LOCALTIMESTAMP(3)" })
col33: Date
@UpdateDateColumn({ default: () => "localtimestamp" })
col34: Date
@UpdateDateColumn({ default: () => "SYSDATE" })
col35: Date
@UpdateDateColumn({ default: () => "sysdate" })
col36: Date
@UpdateDateColumn({ default: () => "SYSTIMESTAMP" })
col37: Date
@UpdateDateColumn({ default: () => "SYSTIMESTAMP(3)" })
col38: Date
@UpdateDateColumn({ default: () => "systimestamp" })
col39: Date
}
``` | /content/code_sandbox/test/github-issues/3991/entity/oracle/Post.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 870 |
```xml
//# sourceMappingURL=runtime.d.ts.map
``` | /content/code_sandbox/packages/expo/build/winter/runtime.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 8 |
```xml
import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { ListResponse } from "@bitwarden/common/models/response/list.response";
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service";
import { EncString } from "@bitwarden/common/platform/models/domain/enc-string";
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
import { ProjectListView } from "../models/view/project-list.view";
import { ProjectView } from "../models/view/project.view";
import { BulkOperationStatus } from "../shared/dialogs/bulk-status-dialog.component";
import { ProjectRequest } from "./models/requests/project.request";
import { ProjectListItemResponse } from "./models/responses/project-list-item.response";
import { ProjectResponse } from "./models/responses/project.response";
@Injectable({
providedIn: "root",
})
export class ProjectService {
protected _project = new Subject<ProjectView>();
project$ = this._project.asObservable();
constructor(
private cryptoService: CryptoService,
private apiService: ApiService,
private encryptService: EncryptService,
) {}
async getByProjectId(projectId: string): Promise<ProjectView> {
const r = await this.apiService.send("GET", "/projects/" + projectId, null, true, true);
const projectResponse = new ProjectResponse(r);
return await this.createProjectView(projectResponse);
}
async getProjects(organizationId: string): Promise<ProjectListView[]> {
const r = await this.apiService.send(
"GET",
"/organizations/" + organizationId + "/projects",
null,
true,
true,
);
const results = new ListResponse(r, ProjectListItemResponse);
return await this.createProjectsListView(organizationId, results.data);
}
async create(organizationId: string, projectView: ProjectView): Promise<ProjectView> {
const request = await this.getProjectRequest(organizationId, projectView);
const r = await this.apiService.send(
"POST",
"/organizations/" + organizationId + "/projects",
request,
true,
true,
);
const project = await this.createProjectView(new ProjectResponse(r));
this._project.next(project);
return project;
}
async update(organizationId: string, projectView: ProjectView) {
const request = await this.getProjectRequest(organizationId, projectView);
const r = await this.apiService.send("PUT", "/projects/" + projectView.id, request, true, true);
this._project.next(await this.createProjectView(new ProjectResponse(r)));
}
async delete(projects: ProjectListView[]): Promise<BulkOperationStatus[]> {
const projectIds = projects.map((project) => project.id);
const r = await this.apiService.send("POST", "/projects/delete", projectIds, true, true);
this._project.next(null);
return r.data.map((element: { id: string; error: string }) => {
const bulkOperationStatus = new BulkOperationStatus();
bulkOperationStatus.id = element.id;
bulkOperationStatus.name = projects.find((project) => project.id == element.id).name;
bulkOperationStatus.errorMessage = element.error;
return bulkOperationStatus;
});
}
private async getOrganizationKey(organizationId: string): Promise<SymmetricCryptoKey> {
return await this.cryptoService.getOrgKey(organizationId);
}
private async getProjectRequest(
organizationId: string,
projectView: ProjectView,
): Promise<ProjectRequest> {
const orgKey = await this.getOrganizationKey(organizationId);
const request = new ProjectRequest();
request.name = await this.encryptService.encrypt(projectView.name, orgKey);
return request;
}
private async createProjectView(projectResponse: ProjectResponse) {
const orgKey = await this.getOrganizationKey(projectResponse.organizationId);
const projectView = new ProjectView();
projectView.id = projectResponse.id;
projectView.organizationId = projectResponse.organizationId;
projectView.creationDate = projectResponse.creationDate;
projectView.revisionDate = projectResponse.revisionDate;
projectView.read = projectResponse.read;
projectView.write = projectResponse.write;
projectView.name = await this.encryptService.decryptToUtf8(
new EncString(projectResponse.name),
orgKey,
);
return projectView;
}
private async createProjectsListView(
organizationId: string,
projects: ProjectListItemResponse[],
): Promise<ProjectListView[]> {
const orgKey = await this.getOrganizationKey(organizationId);
return await Promise.all(
projects.map(async (s: ProjectListItemResponse) => {
const projectListView = new ProjectListView();
projectListView.id = s.id;
projectListView.organizationId = s.organizationId;
projectListView.read = s.read;
projectListView.write = s.write;
projectListView.name = await this.encryptService.decryptToUtf8(
new EncString(s.name),
orgKey,
);
projectListView.creationDate = s.creationDate;
projectListView.revisionDate = s.revisionDate;
return projectListView;
}),
);
}
}
``` | /content/code_sandbox/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 1,128 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/**
* Interface describing `dmaxsorted`.
*/
interface Routine {
/**
* Computes the maximum value of a sorted double-precision floating-point strided array.
*
* @param N - number of indexed elements
* @param x - sorted input array
* @param stride - stride length
* @returns maximum value
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, 2.0, 3.0 ] );
*
* var v = dmaxsorted( x.length, x, 1 );
* // returns 3.0
*/
( N: number, x: Float64Array, stride: number ): number;
/**
* Computes the maximum value of a sorted double-precision floating-point strided array using alternative indexing semantics.
*
* @param N - number of indexed elements
* @param x - sorted input array
* @param stride - stride length
* @param offset - starting index
* @returns maximum value
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, 2.0, 3.0 ] );
*
* var v = dmaxsorted.ndarray( x.length, x, 1, 0 );
* // returns 3.0
*/
ndarray( N: number, x: Float64Array, stride: number, offset: number ): number;
}
/**
* Computes the maximum value of a sorted double-precision floating-point strided array.
*
* @param N - number of indexed elements
* @param x - sorted input array
* @param stride - stride length
* @returns maximum value
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, 2.0, 3.0 ] );
*
* var v = dmaxsorted( x.length, x, 1 );
* // returns 3.0
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, 2.0, 3.0 ] );
*
* var v = dmaxsorted.ndarray( x.length, x, 1, 0 );
* // returns 3.0
*/
declare var dmaxsorted: Routine;
// EXPORTS //
export = dmaxsorted;
``` | /content/code_sandbox/lib/node_modules/@stdlib/stats/base/dmaxsorted/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 637 |
```xml
import React, { useRef, useState } from 'react'
import { useEffectOnce } from 'react-use'
import {
ButtonProps,
LoadingButton,
} from '../../../../design/components/atoms/Button'
import Form from '../../../../design/components/molecules/Form'
import { FormRowProps } from '../../../../design/components/molecules/Form/templates/FormRow'
import styled from '../../../../design/lib/styled'
import ModalContainer from './atoms/ModalContainer'
import MobileFormControl from '../../atoms/MobileFormControl'
interface MobileResourceModalProps {
title: string
prevRows?: FormRowProps[]
defaultInputValue?: string
placeholder: string
defaultEmoji?: string
defaultIcon: string
inputIsDisabled?: boolean
submitButtonProps: ButtonProps & {
label: React.ReactNode
spinning?: boolean
}
onSubmit: (input: string, emoji?: string) => void
}
const MobileResourceModal = ({
title,
defaultInputValue = '',
defaultEmoji,
defaultIcon,
prevRows = [],
placeholder,
submitButtonProps,
inputIsDisabled,
onSubmit,
}: MobileResourceModalProps) => {
const inputRef = useRef<HTMLInputElement>(null)
const [value, setValue] = useState(defaultInputValue)
const [emoji, setEmoji] = useState(defaultEmoji)
useEffectOnce(() => {
if (inputRef.current != null && !inputIsDisabled) {
inputRef.current.focus()
}
})
return (
<ModalContainer title={title}>
<Container>
<div className='body'>
<MobileFormControl>
<Form
rows={[
...prevRows,
{
items: [
{
type: 'emoji',
props: {
defaultIcon,
emoji,
setEmoji,
},
},
{
type: 'input',
props: {
ref: inputRef,
disabled: inputIsDisabled,
placeholder,
value: value,
onChange: (event) => setValue(event.target.value),
},
},
],
},
]}
onSubmit={() => onSubmit(value, emoji)}
/>
</MobileFormControl>
<MobileFormControl>
<LoadingButton
spinning={submitButtonProps.spinning}
onClick={() => onSubmit(value, emoji)}
>
{submitButtonProps.label}
</LoadingButton>
</MobileFormControl>
</div>
</Container>
</ModalContainer>
)
}
export default MobileResourceModal
const Container = styled.div`
.body {
padding: ${({ theme }) => theme.sizes.spaces.md}px;
}
`
``` | /content/code_sandbox/src/mobile/components/organisms/modals/MobileResourceModal.tsx | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 543 |
```xml
/**
* The inbuilt toEqual() matcher will always return TRUE when provided with 2 ArrayBuffers.
* This is because an ArrayBuffer must be wrapped in a new Uint8Array to be accessible.
* This custom matcher will automatically instantiate a new Uint8Array on the received value
* (and optionally, the expected value) and then call toEqual() on the resulting Uint8Arrays.
*/
export const toEqualBuffer: jest.CustomMatcher = function (
received: ArrayBuffer | Uint8Array,
expected: ArrayBuffer | Uint8Array,
) {
received = new Uint8Array(received);
expected = new Uint8Array(expected);
if (this.equals(received, expected)) {
return {
message: () => `expected
${received}
not to match
${expected}`,
pass: true,
};
}
return {
message: () => `expected
${received}
to match
${expected}`,
pass: false,
};
};
``` | /content/code_sandbox/libs/common/spec/matchers/to-equal-buffer.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 201 |
```xml
import type { SBType } from '@storybook/core/types';
import { UnknownArgTypesError } from '@storybook/core/preview-errors';
import type { FlowLiteralType, FlowSigType, FlowType } from './types';
const isLiteral = (type: FlowType): type is FlowLiteralType => type.name === 'literal';
const toEnumOption = (element: FlowLiteralType) => element.value.replace(/['|"]/g, '');
const convertSig = (type: FlowSigType) => {
switch (type.type) {
case 'function':
return { name: 'function' };
case 'object':
const values: any = {};
type.signature.properties.forEach((prop) => {
values[prop.key] = convert(prop.value);
});
return {
name: 'object',
value: values,
};
default:
throw new UnknownArgTypesError({ type: type, language: 'Flow' });
}
};
export const convert = (type: FlowType): SBType | void => {
const { name, raw } = type;
const base: any = {};
if (typeof raw !== 'undefined') {
base.raw = raw;
}
switch (type.name) {
case 'literal':
return { ...base, name: 'other', value: type.value };
case 'string':
case 'number':
case 'symbol':
case 'boolean': {
return { ...base, name };
}
case 'Array': {
return { ...base, name: 'array', value: type.elements.map(convert) };
}
case 'signature':
return { ...base, ...convertSig(type) };
case 'union':
if (type.elements?.every(isLiteral)) {
return { ...base, name: 'enum', value: type.elements?.map(toEnumOption) };
}
return { ...base, name, value: type.elements?.map(convert) };
case 'intersection':
return { ...base, name, value: type.elements?.map(convert) };
default:
return { ...base, name: 'other', value: name };
}
};
``` | /content/code_sandbox/code/core/src/docs-tools/argTypes/convert/flow/convert.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 453 |
```xml
/// <reference types="jest-expo/rsc/expect" />
import * as React from 'react';
import { EmptyRoute } from '../EmptyRoute';
import { ErrorBoundary } from '../ErrorBoundary';
import { Screen } from '../Screen';
import { Sitemap } from '../Sitemap';
it(`renders Screen`, async () => {
await expect(<Screen />).toMatchFlightSnapshot();
});
it(`renders Sitemap`, async () => {
await expect(<Sitemap />).toMatchFlightSnapshot();
});
it(`renders EmptyRoute`, async () => {
await expect(<EmptyRoute />).toMatchFlightSnapshot();
});
it(`renders ErrorBoundary`, async () => {
await expect(
// @ts-expect-error: errors and retry methods cannot be passed here.
<ErrorBoundary />
).toMatchFlightSnapshot();
});
``` | /content/code_sandbox/packages/expo-router/src/views/__rsc_tests__/views.test.tsx | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 171 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="path_to_url"
xmlns="path_to_url" xmlns:web="path_to_url"
xsi:schemaLocation="path_to_url
path_to_url"
id="WebApp_ID" version="2.5" metadata-complete="true">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>journaldev</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
``` | /content/code_sandbox/PrimeFaces/Primefaces-Themes-Sample/src/main/webapp/WEB-INF/web.xml | xml | 2016-05-02T05:43:21 | 2024-08-16T06:51:39 | journaldev | WebJournal/journaldev | 1,314 | 335 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.