text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```xml
import { waitFor } from '@testing-library/react';
import { buildStoreState } from '../../../test/storeBuilders';
import { mountedComponentFactory, setupI18Next, uuidRegex } from '../../../test/testUtils';
describe('Library view container', () => {
beforeAll(() => {
setupI18Next();
});
it('should display an empty local library', () => {
const initialState = buildStoreState()
.withPlugins()
.withConnectivity()
.withLocal([])
.build();
const { component } = mountComponent(initialState);
expect(component.asFragment()).toMatchSnapshot();
});
it('should display local library in simple list mode', () => {
const { component } = mountComponent();
expect(component.asFragment()).toMatchSnapshot();
});
it('should display local library in album grid mode', () => {
const { component } = mountComponent();
waitFor(() => component.getByTestId('library-list-type-toggle-album-grid').click());
expect(component.asFragment()).toMatchSnapshot();
});
it('should display local library in folder tree mode', () => {
const { component } = mountComponent();
waitFor(() => component.getByTestId('library-list-type-toggle-folder-tree').click());
expect(component.asFragment()).toMatchSnapshot();
});
it('should add a folder to the local library', async () => {
const { component } = mountComponent();
await waitFor(() => component.getByText(/add folders/i).click());
// eslint-disable-next-line @typescript-eslint/no-var-requires
const remote = require('electron').remote;
expect(remote.dialog.showOpenDialog).toHaveBeenCalledWith(
'currentWindow',
{
properties: ['openDirectory', 'multiSelections']
}
);
});
it('should add a track from the local library to the queue', async () => {
const { component, store } = mountComponent();
await waitFor(() => component.getAllByTestId('track-popup-trigger')[0].click());
await waitFor(() => component.getByText(/add to queue/i).click());
const state = store.getState();
expect(state.queue.queueItems).toStrictEqual([
expect.objectContaining({
uuid: expect.stringMatching(uuidRegex),
artist: 'local artist 1',
name: 'local track 1',
duration: 300,
local: true
})
]);
});
it('should not display the download button for tracks', async () => {
const { component } = mountComponent();
await waitFor(() => component.getAllByTestId('track-popup-trigger')[0].click());
await component.findByText(/add to queue/i);
expect(component.queryByText(/download/i)).toBeNull();
});
it('should not display the download all button for selected tracks', async () => {
const { component } = mountComponent();
await waitFor(() => component.getAllByTestId('track-popup-trigger')[0].click());
await waitFor(() => component.getByTitle('Toggle All Rows Selected').click());
await waitFor(() => component.getByTestId('select-all-popup-trigger').click());
await component.findByText(/add selected to queue/i);
expect(component.queryByText(/add selected to downloads/i)).toBeNull();
});
it('should add a track from the local library with the old format stream to the queue', async () => {
const initialState = buildStoreState()
.withPlugins()
.withConnectivity()
.withLocal([{
uuid: 'local-track-1',
artist: 'local artist 1',
name: 'local track 1',
duration: 250,
path: '/path/to/local/track/1',
local: true,
streams: [{
id: 'old-format-stream',
source: 'Local',
duration: 250,
stream: 'file:///path/to/local/track/1'
}]
}])
.build();
const { component, store } = mountComponent(initialState);
await waitFor(() => component.getAllByTestId('track-popup-trigger')[0].click());
await waitFor(() => component.getByText(/add to queue/i).click());
const state = store.getState();
expect(state.queue.queueItems).toStrictEqual([
expect.objectContaining({
uuid: expect.stringMatching(uuidRegex),
artist: 'local artist 1',
name: 'local track 1',
duration: 250,
streams: [{
id: 'old-format-stream',
source: 'Local',
duration: 250,
stream: 'file:///path/to/local/track/1'
}]
})
]);
});
const mountComponent = mountedComponentFactory(
['/library'],
buildStoreState()
.withPlugins()
.withConnectivity()
.withLocal()
.build()
);
});
``` | /content/code_sandbox/packages/app/app/containers/LibraryViewContainer/LibraryViewContainer.test.tsx | xml | 2016-09-22T22:58:21 | 2024-08-16T15:47:39 | nuclear | nukeop/nuclear | 11,862 | 1,002 |
```xml
import { Post } from "@/interfaces/post";
import { PostPreview } from "./post-preview";
type Props = {
posts: Post[];
};
export function MoreStories({ posts }: Props) {
return (
<section>
<h2 className="mb-8 text-5xl md:text-7xl font-bold tracking-tighter leading-tight">
More Stories
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
{posts.map((post) => (
<PostPreview
key={post.slug}
title={post.title}
coverImage={post.coverImage}
date={post.date}
author={post.author}
slug={post.slug}
excerpt={post.excerpt}
/>
))}
</div>
</section>
);
}
``` | /content/code_sandbox/examples/blog-starter/src/app/_components/more-stories.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 199 |
```xml
///
///
///
/// path_to_url
///
/// Unless required by applicable law or agreed to in writing, software
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
///
import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core';
import { ControlValueAccessor, UntypedFormBuilder, UntypedFormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms';
import { PageComponent } from '@shared/components/page.component';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { TranslateService } from '@ngx-translate/core';
import { WidgetFont } from '@home/components/widget/lib/settings/common/widget-font.component';
export interface LabelWidgetLabel {
pattern: string;
x: number;
y: number;
backgroundColor: string;
font: WidgetFont;
}
@Component({
selector: 'tb-label-widget-label',
templateUrl: './label-widget-label.component.html',
styleUrls: ['./label-widget-label.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => LabelWidgetLabelComponent),
multi: true
}
]
})
export class LabelWidgetLabelComponent extends PageComponent implements OnInit, ControlValueAccessor {
@Input()
disabled: boolean;
@Input()
expanded = false;
@Output()
removeLabel = new EventEmitter();
private modelValue: LabelWidgetLabel;
private propagateChange = null;
public labelWidgetLabelFormGroup: UntypedFormGroup;
constructor(protected store: Store<AppState>,
private translate: TranslateService,
private fb: UntypedFormBuilder) {
super(store);
}
ngOnInit(): void {
this.labelWidgetLabelFormGroup = this.fb.group({
pattern: [null, [Validators.required]],
x: [null, [Validators.min(0), Validators.max(100)]],
y: [null, [Validators.min(0), Validators.max(100)]],
backgroundColor: [null, []],
font: [null, []]
});
this.labelWidgetLabelFormGroup.valueChanges.subscribe(() => {
this.updateModel();
});
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
if (isDisabled) {
this.labelWidgetLabelFormGroup.disable({emitEvent: false});
} else {
this.labelWidgetLabelFormGroup.enable({emitEvent: false});
}
}
writeValue(value: LabelWidgetLabel): void {
this.modelValue = value;
this.labelWidgetLabelFormGroup.patchValue(
value, {emitEvent: false}
);
}
private updateModel() {
const value: LabelWidgetLabel = this.labelWidgetLabelFormGroup.value;
this.modelValue = value;
if (this.labelWidgetLabelFormGroup.valid) {
this.propagateChange(this.modelValue);
} else {
this.propagateChange(null);
}
}
}
``` | /content/code_sandbox/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.ts | xml | 2016-12-01T09:33:30 | 2024-08-16T19:58:25 | thingsboard | thingsboard/thingsboard | 16,820 | 648 |
```xml
<project xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<groupId>foo.bar</groupId>
<artifactId>salut6</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<!-- use 2.9.1 for Java 7 projects -->
<version>3.20.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
``` | /content/code_sandbox/org.eclipse.jdt.ls.tests/projects/maven/salut6/pom.xml | xml | 2016-06-27T13:06:53 | 2024-08-16T00:38:32 | eclipse.jdt.ls | eclipse-jdtls/eclipse.jdt.ls | 1,726 | 266 |
```xml
import React from "react";
import {OperationParamsErrorReporter, ValueResolver} from "cad/craft/schema/schema";
import {ApplicationContext} from "cad/context";
import {ObjectTypeSchema} from "cad/craft/schema/types/objectType";
import {AxisBasedWidgetDefinition, AxisBasedWidgetProps, AxisInput, AxisResolver} from "cad/mdf/ui/AxisWidget";
import {UnitVector} from "math/vector";
export const DirectionResolver: ValueResolver<AxisInput, UnitVector> = (ctx: ApplicationContext,
value: AxisInput,
md: ObjectTypeSchema,
reportError: OperationParamsErrorReporter): UnitVector => {
return AxisResolver(ctx, value, md, reportError)?.direction;
}
export interface DirectionWidgetProps extends AxisBasedWidgetProps {
type: 'direction';
}
export const DirectionWidgetDefinition = (props: DirectionWidgetProps) => AxisBasedWidgetDefinition({
resolve: DirectionResolver,
...props,
});
``` | /content/code_sandbox/web/app/cad/mdf/ui/DirectionWidget.tsx | xml | 2016-08-26T21:55:19 | 2024-08-15T01:02:53 | jsketcher | xibyte/jsketcher | 1,461 | 196 |
```xml
import styled from "@emotion/styled"
import { FC, PropsWithChildren } from "react"
import { CircularProgress } from "../ui/CircularProgress"
import { Dialog, DialogContent } from "./Dialog"
const Message = styled.div`
color: ${({ theme }) => theme.textColor};
margin-left: 1rem;
display: flex;
align-items: center;
font-size: 0.8rem;
`
export type LoadingDialog = PropsWithChildren<{
open: boolean
}>
export const LoadingDialog: FC<LoadingDialog> = ({ open, children }) => {
return (
<Dialog open={open} style={{ minWidth: "20rem" }}>
<DialogContent style={{ display: "flex", marginBottom: "0" }}>
<CircularProgress />
<Message>{children}</Message>
</DialogContent>
</Dialog>
)
}
``` | /content/code_sandbox/app/src/components/Dialog/LoadingDialog.tsx | xml | 2016-03-06T15:19:53 | 2024-08-15T14:27:10 | signal | ryohey/signal | 1,238 | 182 |
```xml
/**
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
type HunkGroup = {
common: string[];
removed: string[];
added: string[];
};
/**
* We must find the groups within `lines` so that multiline sequences of
* modified lines are displayed correctly. A group is defined by:
*
* - a sequence of 0 or more "common lines" that start with ' '
* - a sequence of 0 or more "removed lines" that start with '-'
* - a sequence of 0 or more "added lines" that start with '+'
*
* Therefore, the end of a group is determined by either:
*
* - reaching the end of a list of lines
* - encountering a "common line" after an "added" or "removed" line.
*/
export default function organizeLinesIntoGroups(lines: string[]): HunkGroup[] {
const groups = [];
let group = newGroup();
lines.forEach(fullLine => {
const firstChar = fullLine.charAt(0);
const line = fullLine.slice(1);
if (firstChar === ' ') {
if (hasDeltas(group)) {
// This must be the start of a new group!
groups.push(group);
group = newGroup();
}
group.common.push(line);
} else if (firstChar === '-') {
group.removed.push(line);
} else if (firstChar === '+') {
group.added.push(line);
}
});
groups.push(group);
return groups;
}
function hasDeltas(group: HunkGroup): boolean {
return group.removed.length !== 0 || group.added.length !== 0;
}
function newGroup(): HunkGroup {
return {
common: [],
removed: [],
added: [],
};
}
``` | /content/code_sandbox/eden/contrib/shared/SplitDiffView/organizeLinesIntoGroups.ts | xml | 2016-05-05T16:53:47 | 2024-08-16T19:12:02 | sapling | facebook/sapling | 5,987 | 394 |
```xml
import { createContext, useContext, useEffect, useState } from 'react';
import { c } from 'ttag';
import { useNotifications } from '@proton/components/hooks';
import { useLoading } from '@proton/hooks';
import { sendErrorReport } from '../../utils/errorHandling';
import { EnrichedError } from '../../utils/errorHandling/EnrichedError';
import { useLink } from '../_links';
import { useVolumesState } from '../_volumes';
import type { Device } from './interface';
import useDevicesApi from './useDevicesApi';
export function useDevicesListingProvider() {
const devicesApi = useDevicesApi();
const { getLink } = useLink();
const volumesState = useVolumesState();
const [state, setState] = useState<Map<string, Device>>(new Map());
const [isLoading, withLoading] = useLoading();
const { createNotification } = useNotifications();
const loadDevices = (abortSignal: AbortSignal) =>
withLoading(async () => {
const devices = await devicesApi.loadDevices(abortSignal);
if (devices) {
const devicesMap = new Map();
let hasError = false;
for (const key in devices) {
const { volumeId, shareId, linkId, name } = devices[key];
try {
volumesState.setVolumeShareIds(volumeId, [shareId]);
devices[key] = {
...devices[key],
name: name || (await getLink(abortSignal, shareId, linkId)).name,
};
devicesMap.set(key, devices[key]);
} catch (e) {
hasError = true;
// Send an error report for this
sendErrorReport(
new EnrichedError('Decrypting device failed', {
tags: {
volumeId,
shareId,
linkId,
},
extra: {
e,
},
})
);
}
}
if (hasError) {
createNotification({
type: 'error',
text: c('Error').t`Error decrypting a computer`,
});
}
setState(devicesMap);
}
});
const getState = () => {
return [...state.values()];
};
const getDeviceByShareId = (shareId: string) => {
return getState().find((device) => {
return device.shareId === shareId;
});
};
const removeDevice = (deviceId: string) => {
const newState = new Map(state);
newState.delete(deviceId);
setState(newState);
};
const renameDevice = (deviceId: string, name: string) => {
const newState = new Map(state);
const device = newState.get(deviceId);
if (!device) {
return;
}
newState.set(deviceId, {
...device,
name,
});
setState(newState);
};
return {
isLoading,
loadDevices,
cachedDevices: getState(),
getDeviceByShareId,
renameDevice,
removeDevice,
};
}
const LinksListingContext = createContext<{
isLoading: boolean;
cachedDevices: ReturnType<typeof useDevicesListingProvider>['cachedDevices'];
getDeviceByShareId: ReturnType<typeof useDevicesListingProvider>['getDeviceByShareId'];
removeCachedDevice: ReturnType<typeof useDevicesListingProvider>['removeDevice'];
renameCachedDevice: ReturnType<typeof useDevicesListingProvider>['renameDevice'];
} | null>(null);
export function DevicesListingProvider({ children }: { children: React.ReactNode }) {
const value = useDevicesListingProvider();
useEffect(() => {
const ac = new AbortController();
value.loadDevices(ac.signal).catch(sendErrorReport);
return () => {
ac.abort();
};
}, []);
return (
<LinksListingContext.Provider
value={{
isLoading: value.isLoading,
cachedDevices: value.cachedDevices,
getDeviceByShareId: value.getDeviceByShareId,
removeCachedDevice: value.removeDevice,
renameCachedDevice: value.renameDevice,
}}
>
{children}
</LinksListingContext.Provider>
);
}
export default function useDevicesListing() {
const state = useContext(LinksListingContext);
if (!state) {
throw new Error('Trying to use uninitialized LinksListingProvider');
}
return state;
}
``` | /content/code_sandbox/applications/drive/src/app/store/_devices/useDevicesListing.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 912 |
```xml
export const pi = 3 + 0.14;
export function add(num1: number, num2: number) {
return num1 + num2;
}
export function addOne(number: number) {
number++;
return number;
}
export function negate(number: number) {
return -number;
}
export function isNegativeNumber(number: number) {
var isNegative = false;
if (number < 0) {
isNegative = true;
}
return isNegative;
}
``` | /content/code_sandbox/packages/vitest-runner/testResources/simple-project/math.orig.ts | xml | 2016-02-12T13:14:28 | 2024-08-15T18:38:25 | stryker-js | stryker-mutator/stryker-js | 2,561 | 107 |
```xml
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { SignupPage } from './signup';
const routes: Routes = [
{
path: '',
component: SignupPage
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class SignupPageRoutingModule { }
``` | /content/code_sandbox/examples/ionic-angular/src/app/pages/signup/signup-routing.module.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 75 |
```xml
import { buildStatementCommand } from "./command-helper.js";
const command = buildStatementCommand("select * from items");
export { command };
``` | /content/code_sandbox/javascriptv3/example_code/cross-services/aurora-serverless-app/src/statement-commands/get-all-items.ts | xml | 2016-08-18T19:06:57 | 2024-08-16T18:59:44 | aws-doc-sdk-examples | awsdocs/aws-doc-sdk-examples | 9,298 | 29 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:id="@+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:orientation="vertical"
app:behavior_hideable="false"
app:behavior_peekHeight="180dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
<EditText
android:id="@+id/editTextSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:hint="@string/search_hint" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:text="@string/nearby_places"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textViewNoItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:fontFamily="sans-serif-condensed"
android:gravity="center"
android:text="@string/no_items_available"
android:textSize="16sp"
android:visibility="gone" />
<android.support.v7.widget.RecyclerView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="0.3"
android:drawSelectorOnTop="false"
android:orientation="vertical"
android:scrollbars="vertical" />
</LinearLayout>
``` | /content/code_sandbox/Android/app/src/main/res/layout/bottomsheet_map_cards.xml | xml | 2016-01-30T13:42:30 | 2024-08-12T19:21:10 | Travel-Mate | project-travel-mate/Travel-Mate | 1,292 | 451 |
```xml
import { CollectionPermission } from "@shared/types";
import { View, UserMembership } from "@server/models";
import {
buildAdmin,
buildCollection,
buildDocument,
buildTeam,
buildUser,
} from "@server/test/factories";
import { getTestServer } from "@server/test/support";
const server = getTestServer();
describe("#views.list", () => {
it("should return views for a document", async () => {
const user = await buildUser();
const document = await buildDocument({
userId: user.id,
teamId: user.teamId,
});
await View.incrementOrCreate({
documentId: document.id,
userId: user.id,
});
const res = await server.post("/api/views.list", {
body: {
token: user.getJwtToken(),
documentId: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data[0].count).toBe(1);
expect(body.data[0].user.name).toBe(user.name);
});
it("should not return views for suspended user by default", async () => {
const team = await buildTeam();
const admin = await buildAdmin({ teamId: team.id });
const user = await buildUser({ teamId: team.id });
const document = await buildDocument({ userId: user.id, teamId: team.id });
await View.incrementOrCreate({
documentId: document.id,
userId: user.id,
});
await user.update({ suspendedAt: new Date() });
const res = await server.post("/api/views.list", {
body: {
token: admin.getJwtToken(),
documentId: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.length).toBe(0);
});
it("should return views for a document in read-only collection", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({
userId: user.id,
teamId: team.id,
});
const document = await buildDocument({
userId: user.id,
collectionId: collection.id,
teamId: team.id,
});
collection.permission = null;
await collection.save();
await UserMembership.create({
createdById: user.id,
collectionId: collection.id,
userId: user.id,
permission: CollectionPermission.Read,
});
await View.incrementOrCreate({
documentId: document.id,
userId: user.id,
});
const res = await server.post("/api/views.list", {
body: {
token: user.getJwtToken(),
documentId: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data[0].count).toBe(1);
expect(body.data[0].user.name).toBe(user.name);
});
it("should require authentication", async () => {
const document = await buildDocument();
const res = await server.post("/api/views.list", {
body: {
documentId: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(401);
expect(body).toMatchSnapshot();
});
it("should require authorization", async () => {
const document = await buildDocument();
const user = await buildUser();
const res = await server.post("/api/views.list", {
body: {
token: user.getJwtToken(),
documentId: document.id,
},
});
expect(res.status).toEqual(403);
});
});
describe("#views.create", () => {
it("should allow creating a view record for document", async () => {
const user = await buildUser();
const document = await buildDocument({
userId: user.id,
teamId: user.teamId,
});
const res = await server.post("/api/views.create", {
body: {
token: user.getJwtToken(),
documentId: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.count).toBe(1);
});
it("should allow creating a view record for document in read-only collection", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const collection = await buildCollection({
userId: user.id,
teamId: team.id,
});
const document = await buildDocument({
userId: user.id,
collectionId: collection.id,
teamId: team.id,
});
collection.permission = null;
await collection.save();
await UserMembership.create({
createdById: user.id,
collectionId: collection.id,
userId: user.id,
permission: CollectionPermission.Read,
});
const res = await server.post("/api/views.create", {
body: {
token: user.getJwtToken(),
documentId: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.count).toBe(1);
});
it("should require authentication", async () => {
const document = await buildDocument();
const res = await server.post("/api/views.create", {
body: {
documentId: document.id,
},
});
const body = await res.json();
expect(res.status).toEqual(401);
expect(body).toMatchSnapshot();
});
it("should require authorization", async () => {
const document = await buildDocument();
const user = await buildUser();
const res = await server.post("/api/views.create", {
body: {
token: user.getJwtToken(),
documentId: document.id,
},
});
expect(res.status).toEqual(403);
});
});
``` | /content/code_sandbox/server/routes/api/views/views.test.ts | xml | 2016-05-22T21:31:47 | 2024-08-16T19:57:22 | outline | outline/outline | 26,751 | 1,262 |
```xml
import * as React from 'react';
import { makeStyles, Text } from '@fluentui/react-components';
const useStyles = makeStyles({
container: {
gap: '16px',
display: 'flex',
flexDirection: 'column',
},
});
export const Font = () => {
const styles = useStyles();
return (
<div className={styles.container}>
<Text font="base">This is the default font</Text>
<Text font="numeric">This is numeric font</Text>
<Text font="monospace">This is monospace font</Text>
</div>
);
};
``` | /content/code_sandbox/packages/react-components/react-text/stories/src/Text/TextFont.stories.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 130 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file source-language="en" target-language="vi" datatype="plaintext" original="invoice-calculator.en.xlf">
<body>
<trans-unit id="MviRJeB" resname="invoice_calculator">
<source>invoice_calculator</source>
<target>Tnh tng</target>
</trans-unit>
<trans-unit id="N6juwc4" resname="default">
<source>default</source>
<target state="translated">Mc nh: mt mc nhp cho mi bn ghi thi gian</target>
</trans-unit>
<trans-unit id="_bAHi13" resname="short">
<source>short</source>
<target state="translated">Gi: h s c tng hp, tng s mt mc nhp</target>
</trans-unit>
<trans-unit id="BPiZbad" resname="user">
<source>user</source>
<target>Ngi dng: mt mc nhp cho mi ngi dng</target>
</trans-unit>
<trans-unit id="BlGGO.X" resname="activity">
<source>activity</source>
<target>Hot ng: mt mc nhp cho mi hot ng</target>
</trans-unit>
<trans-unit id="JEIQ5IQ" resname="project">
<source>project</source>
<target>D n: mt mc nhp cho mi d n</target>
</trans-unit>
<trans-unit id="DodjLNR" resname="date">
<source>date</source>
<target state="translated">Ngy: mt mc nhp mt ngy (s dng ngy bt u)</target>
</trans-unit>
<trans-unit id="aDtTH0H" resname="price">
<source>price</source>
<target state="translated">Gi: mi mc nhp cho mi gi</target>
</trans-unit>
<trans-unit id="iFDs7Zh" resname="weekly">
<source>weekly</source>
<target state="translated">Hng tun: mi mc nhp cho mi tun (s dng ngy bt u)</target>
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/translations/invoice-calculator.vi.xlf | xml | 2016-10-20T17:06:34 | 2024-08-16T18:27:30 | kimai | kimai/kimai | 3,084 | 545 |
```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 pmf = require( './index' );
// TESTS //
// The function returns a number...
{
pmf( 2, 0.4 ); // $ExpectType number
pmf( 1, 0.2 ); // $ExpectType number
}
// The compiler throws an error if the function is provided values other than two numbers...
{
pmf( true, 0.3 ); // $ExpectError
pmf( false, 0.2 ); // $ExpectError
pmf( '5', 0.1 ); // $ExpectError
pmf( [], 0.1 ); // $ExpectError
pmf( {}, 0.4 ); // $ExpectError
pmf( ( x: number ): number => x, 0.2 ); // $ExpectError
pmf( 0, true ); // $ExpectError
pmf( 1, false ); // $ExpectError
pmf( 0, '5' ); // $ExpectError
pmf( 1, [] ); // $ExpectError
pmf( 2, {} ); // $ExpectError
pmf( 3, ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the function is provided an unsupported number of arguments...
{
pmf(); // $ExpectError
pmf( 0 ); // $ExpectError
pmf( 1, 0.3, 4 ); // $ExpectError
}
// Attached to main export is a `factory` method which returns a function...
{
pmf.factory( 0.4 ); // $ExpectType Unary
}
// The `factory` method returns a function which returns a number...
{
const fcn = pmf.factory( 0.4 );
fcn( 2 ); // $ExpectType number
}
// The compiler throws an error if the function returned by the `factory` method is provided an invalid argument...
{
const fcn = pmf.factory( 0.4 );
fcn( true ); // $ExpectError
fcn( false ); // $ExpectError
fcn( '5' ); // $ExpectError
fcn( [] ); // $ExpectError
fcn( {} ); // $ExpectError
fcn( ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the function returned by the `factory` method is provided an unsupported number of arguments...
{
const fcn = pmf.factory( 0.4 );
fcn(); // $ExpectError
fcn( 2, 0 ); // $ExpectError
fcn( 2, 0, 1 ); // $ExpectError
}
// The compiler throws an error if the `factory` method is provided a value other than a number...
{
pmf.factory( true ); // $ExpectError
pmf.factory( false ); // $ExpectError
pmf.factory( '5' ); // $ExpectError
pmf.factory( [] ); // $ExpectError
pmf.factory( {} ); // $ExpectError
pmf.factory( ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the `factory` method is provided an unsupported number of arguments...
{
pmf.factory( 0, 0.2 ); // $ExpectError
pmf.factory( 0, 0.4, 8 ); // $ExpectError
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/stats/base/dists/geometric/pmf/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 781 |
```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.
*/
/* eslint-disable max-classes-per-file */
import { objects } from '@liskhq/lisk-utils';
import * as childProcess from 'child_process';
import * as fs from 'fs-extra';
import * as os from 'os';
import { join } from 'path';
import { Modules, Plugins } from '../../src';
import { Application } from '../../src/application';
import { Bus } from '../../src/controller/bus';
import { WSServer } from '../../src/controller/ws/ws_server';
import { createLogger } from '../../src/logger';
import { Engine } from '../../src/engine';
import * as basePluginModule from '../../src/plugins/base_plugin';
import * as defaultConfig from '../fixtures/config/devnet/config.json';
import { ABIServer } from '../../src/abi_handler/abi_server';
import { ABIHandler, EVENT_ENGINE_READY } from '../../src/abi_handler/abi_handler';
import { systemDirs } from '../../src/system_dirs';
import { OWNER_READ_WRITE } from '../../src/constants';
jest.mock('fs-extra');
jest.mock('zeromq', () => {
return {
Publisher: jest
.fn()
.mockReturnValue({ bind: jest.fn(), close: jest.fn(), subscribe: jest.fn() }),
Subscriber: jest
.fn()
.mockReturnValue({ bind: jest.fn(), close: jest.fn(), subscribe: jest.fn() }),
Router: jest.fn().mockReturnValue({ bind: jest.fn(), close: jest.fn() }),
};
});
jest.mock('@liskhq/lisk-db');
jest.mock('../../src/logger');
class TestPlugin extends Plugins.BasePlugin {
public get nodeModulePath(): string {
return __filename;
}
public get name() {
return 'test-plugin';
}
public async load(): Promise<void> {}
public async unload(): Promise<void> {}
}
class TestModule extends Modules.BaseModule {
public commands = [];
public endpoint: Modules.BaseEndpoint = {} as Modules.BaseEndpoint;
public method: Modules.BaseMethod = {} as Modules.BaseMethod;
public verifyAssets = jest.fn();
public beforeTransactionsExecute = jest.fn();
public afterCommandExecute = jest.fn();
public get name() {
return 'test-module';
}
public metadata(): Modules.ModuleMetadata {
throw new Error('Method not implemented.');
}
}
class TestInteroperableModule extends Modules.Interoperability.BaseInteroperableModule {
public crossChainMethod = {
stores: {},
events: {},
} as unknown as Modules.Interoperability.BaseCCMethod;
public commands = [];
public endpoint: Modules.BaseEndpoint = {} as Modules.BaseEndpoint;
public method: Modules.BaseMethod = {} as Modules.BaseMethod;
public verifyAssets = jest.fn();
public beforeTransactionsExecute = jest.fn();
public afterCommandExecute = jest.fn();
public get name() {
return 'test-interoperable-module';
}
public metadata(): Modules.ModuleMetadata {
throw new Error('Method not implemented.');
}
}
describe('Application', () => {
// Arrange
const config = {
...defaultConfig,
genesis: {
...defaultConfig.genesis,
chainID: '10000000',
},
};
const loggerMock = {
info: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
trace: jest.fn(),
fatal: jest.fn(),
};
let engineProcessMock: {
on: jest.Mock;
kill: jest.Mock;
};
(createLogger as jest.Mock).mockReturnValue(loggerMock);
beforeEach(() => {
engineProcessMock = {
on: jest.fn(),
kill: jest.fn(),
};
jest.spyOn(childProcess, 'fork').mockReturnValue(engineProcessMock as never);
jest.spyOn(os, 'homedir').mockReturnValue('/user');
// jest.spyOn(IPCServer.prototype, 'start').mockResolvedValue();
jest.spyOn(WSServer.prototype, 'start').mockResolvedValue(jest.fn() as never);
jest.spyOn(Engine.prototype, 'start').mockResolvedValue();
jest.spyOn(ABIHandler.prototype, 'cacheGenesisState').mockResolvedValue();
jest.spyOn(process, 'exit').mockReturnValue(0 as never);
});
describe('#constructor', () => {
it('should be able to start the application with default parameters if config is not provided', () => {
const { app } = Application.defaultApplication({ genesis: { chainID: '10000000' } });
expect(app.config).toBeDefined();
});
it('should merge the constants with genesis and assign it to app constants', () => {
const customConfig = objects.cloneDeep(config);
customConfig.genesis = {
...config.genesis,
maxTransactionsSize: 15 * 1024,
blockTime: 5,
};
const { app } = Application.defaultApplication(customConfig);
expect(app.config.genesis.maxTransactionsSize).toBe(15 * 1024);
});
it('should set internal variables', () => {
// Act
const { app } = Application.defaultApplication(config);
// Assert
expect(app.config).toMatchSnapshot();
expect(app['_stateMachine']).toBeDefined();
expect(app['_controller']).toBeDefined();
});
it('should not initialize logger', () => {
// Act
const { app } = Application.defaultApplication(config);
// Assert
expect(app.logger).toBeUndefined();
});
});
describe('#registerPlugin', () => {
it('should throw error when plugin with same name is already registered', () => {
// Arrange
const { app } = Application.defaultApplication(config);
app.registerPlugin(new TestPlugin());
// Act && Assert
expect(() => app.registerPlugin(new TestPlugin())).toThrow(
'A plugin with name "test-plugin" is already registered.',
);
});
it('should throw error when module with same name is already registered', () => {
// Arrange
const { app } = Application.defaultApplication(config);
class DuplicateNameModule extends TestModule {
public get name() {
return 'test-plugin';
}
}
app.registerModule(new DuplicateNameModule());
// Act && Assert
expect(() => app.registerPlugin(new TestPlugin())).toThrow(
'A module with name "test-plugin" is already registered.',
);
});
it('should call validatePluginSpec function', () => {
// Arrange
const { app } = Application.defaultApplication(config);
jest.spyOn(basePluginModule, 'validatePluginSpec').mockReturnValue();
// Act
app.registerPlugin(new TestPlugin());
// Assert
expect(basePluginModule.validatePluginSpec).toHaveBeenCalledTimes(1);
expect(basePluginModule.validatePluginSpec).toHaveBeenCalledWith(new TestPlugin());
});
it('should throw error when plugin is required to load as child process and not exported', () => {
// Arrange
const { app } = Application.defaultApplication(config);
jest.spyOn(basePluginModule, 'getPluginExportPath').mockReturnValue(undefined);
// Act && Assert
expect(() => app.registerPlugin(new TestPlugin(), { loadAsChildProcess: true })).toThrow(
'Unable to register plugin "test-plugin" to load as child process. Package name or __filename must be specified in nodeModulePath.',
);
expect(basePluginModule.getPluginExportPath).toHaveBeenCalledTimes(1);
expect(basePluginModule.getPluginExportPath).toHaveBeenCalledWith(new TestPlugin());
});
it('should add plugin to the collection', () => {
// Arrange
const { app } = Application.defaultApplication(config);
const plugin = new TestPlugin();
jest.spyOn(app['_controller'], 'registerPlugin');
app.registerPlugin(plugin);
// Act && Assert
expect(app['_controller'].registerPlugin).toHaveBeenCalledWith(plugin, {
loadAsChildProcess: false,
});
});
});
describe('#registerModule', () => {
it('should throw error when plugin with same name is already registered', () => {
// Arrange
const { app } = Application.defaultApplication(config);
class DuplicateNamePlugin extends TestPlugin {
public get name() {
return 'test-module';
}
}
app.registerPlugin(new DuplicateNamePlugin());
// Act && Assert
expect(() => app.registerModule(new TestModule())).toThrow(
'A plugin with name "test-module" is already registered.',
);
});
});
describe('#registerInteroperableModule', () => {
it('should register CCCommands and CCMethods of the registered interoperable module', () => {
const { app } = Application.defaultApplication(config);
const testInteroperableModule = new TestInteroperableModule();
app.registerInteroperableModule(testInteroperableModule);
const interoperabilityModule = app['_registeredModules'].find(
module => module.name === 'interoperability',
) as Modules.Interoperability.SidechainInteroperabilityModule;
expect(
interoperabilityModule['interoperableCCCommands'].has(testInteroperableModule.name),
).toBeTrue();
expect(
interoperabilityModule['interoperableCCMethods'].has(testInteroperableModule.name),
).toBeTrue();
});
it('should throw if Interoperability module is not registered', () => {
const { app } = Application.defaultApplication(config);
const index = app['_registeredModules'].findIndex(
module => module.name === Modules.Interoperability.MODULE_NAME_INTEROPERABILITY,
);
app['_registeredModules'][index] = new TestModule();
const testInteroperableModule = new TestInteroperableModule();
expect(() => app.registerInteroperableModule(testInteroperableModule)).toThrow(
`${Modules.Interoperability.MODULE_NAME_INTEROPERABILITY} module is not registered.`,
);
});
});
describe('#run', () => {
let app: Application;
beforeEach(async () => {
({ app } = Application.defaultApplication(config));
jest.spyOn(fs, 'readdirSync').mockReturnValue([]);
// jest.spyOn(IPCServer.prototype, 'start').mockResolvedValue();
jest.spyOn(Bus.prototype, 'publish').mockResolvedValue(jest.fn() as never);
jest.spyOn(WSServer.prototype, 'start').mockResolvedValue(jest.fn() as never);
jest.spyOn(ABIServer.prototype, 'start');
await app.run();
});
afterEach(async () => {
await app.shutdown();
});
// Skip for path_to_url
// eslint-disable-next-line jest/no-disabled-tests
it.skip('should start ABI server', () => {
expect(ABIServer.prototype.start).toHaveBeenCalledTimes(1);
});
it('should try to cache genesis state', () => {
expect(ABIHandler.prototype.cacheGenesisState).toHaveBeenCalledTimes(1);
});
// Skip for path_to_url
// eslint-disable-next-line jest/no-disabled-tests
it.skip('should start engine', () => {
expect(childProcess.fork).toHaveBeenCalledTimes(1);
expect(childProcess.fork).toHaveBeenCalledWith(expect.stringContaining('engine_igniter'), [
expect.stringContaining('.ipc'),
'--config',
expect.stringContaining('engine_config.json'),
]);
});
// Skip for path_to_url
// eslint-disable-next-line jest/no-disabled-tests
it.skip('should register engine signal handler', () => {
expect(engineProcessMock.on).toHaveBeenCalledWith('exit', expect.any(Function));
expect(engineProcessMock.on).toHaveBeenCalledWith('error', expect.any(Function));
});
});
describe('#_setupDirectories', () => {
let app: Application;
let dirs: any;
beforeEach(async () => {
({ app } = Application.defaultApplication(config));
jest.spyOn(fs, 'readdirSync').mockReturnValue([]);
// jest.spyOn(IPCServer.prototype, 'start').mockResolvedValue();
jest.spyOn(Bus.prototype, 'publish').mockResolvedValue(jest.fn() as never);
jest.spyOn(WSServer.prototype, 'start').mockResolvedValue(jest.fn() as never);
await app.run();
dirs = systemDirs(app.config.system.dataPath);
});
afterEach(async () => {
await app.shutdown();
});
it('should ensure directory exists', () => {
// Arrange
jest.spyOn(fs, 'ensureDir');
// Assert
Array.from(Object.values(dirs)).map(dirPath =>
expect(fs.ensureDir).toHaveBeenCalledWith(dirPath),
);
});
it('should write process id to pid file if pid file not exits', () => {
jest.spyOn(fs, 'pathExists').mockResolvedValue(false as never);
jest.spyOn(fs, 'writeFile');
expect(fs.writeFile).toHaveBeenCalledWith(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`${dirs.pids}/controller.pid`,
expect.toBeString(),
{
mode: OWNER_READ_WRITE,
},
);
});
});
describe('#_emptySocketsDirectory', () => {
let app: Application;
const fakeSocketFiles = ['1.sock' as any, '2.sock' as any];
beforeEach(async () => {
({ app } = Application.defaultApplication(config));
jest.spyOn(Engine.prototype, 'start').mockResolvedValue();
jest.spyOn(Engine.prototype, 'stop').mockResolvedValue();
jest.spyOn(fs, 'readdirSync').mockReturnValue(fakeSocketFiles);
jest.spyOn(Bus.prototype, 'publish').mockResolvedValue(jest.fn() as never);
jest.spyOn(fs, 'unlink').mockResolvedValue();
await app.run();
app['_abiHandler'].event.emit(EVENT_ENGINE_READY);
await app.shutdown();
});
it('should delete all files in ~/.lisk/tmp/sockets', () => {
const { sockets: socketsPath } = systemDirs(app.config.system.dataPath);
// Assert
for (const aSocketFile of fakeSocketFiles) {
expect(fs.unlink).toHaveBeenCalledWith(join(socketsPath, aSocketFile));
}
});
});
describe('shutdown', () => {
let app: Application;
const fakeSocketFiles = ['1.sock' as any, '2.sock' as any];
let clearControllerPidFileSpy: jest.SpyInstance<any, unknown[]>;
let emptySocketsDirectorySpy: jest.SpyInstance<any, unknown[]>;
let blockChainDBSpy: jest.SpyInstance<any, unknown[]>;
let forgerDBSpy: jest.SpyInstance<any, unknown[]>;
beforeEach(async () => {
jest.spyOn(Bus.prototype, 'publish').mockResolvedValue(jest.fn() as never);
({ app } = Application.defaultApplication(config));
jest.spyOn(Engine.prototype, 'start').mockResolvedValue();
jest.spyOn(Engine.prototype, 'stop').mockResolvedValue();
await app.run();
app['_abiHandler'].event.emit(EVENT_ENGINE_READY);
jest.spyOn(fs, 'readdirSync').mockReturnValue(fakeSocketFiles);
jest.spyOn(app['_controller'], 'stop');
blockChainDBSpy = jest.spyOn(app['_stateDB'], 'close');
forgerDBSpy = jest.spyOn(app['_moduleDB'], 'close');
emptySocketsDirectorySpy = jest
.spyOn(app as any, '_emptySocketsDirectory')
.mockResolvedValue([]);
clearControllerPidFileSpy = jest.spyOn(app as any, '_clearControllerPidFile');
});
// Skip for path_to_url
// eslint-disable-next-line jest/no-disabled-tests
it.skip('should stop the engine', async () => {
await app.shutdown();
expect(engineProcessMock.kill).toHaveBeenCalledTimes(2);
expect(engineProcessMock.kill).toHaveBeenCalledWith('SIGINT');
expect(engineProcessMock.kill).toHaveBeenCalledWith('SIGTERM');
});
it('should call cleanup methods', async () => {
await app.shutdown();
expect(clearControllerPidFileSpy).toHaveBeenCalledTimes(1);
expect(emptySocketsDirectorySpy).toHaveBeenCalledTimes(1);
expect(blockChainDBSpy).toHaveBeenCalledTimes(1);
expect(forgerDBSpy).toHaveBeenCalledTimes(1);
expect(app['_controller'].stop).toHaveBeenCalledTimes(1);
});
it('should call clearControllerPidFileSpy method with correct pid file location', async () => {
const unlinkSyncSpy = jest.spyOn(fs, 'unlinkSync').mockReturnValue();
await app.shutdown();
expect(unlinkSyncSpy).toHaveBeenCalledWith(
'/user/.lisk/beta-sdk-app/tmp/pids/controller.pid',
);
});
});
});
``` | /content/code_sandbox/framework/test/unit/application.spec.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 3,676 |
```xml
/**
* Truncates multi-line text to fit within an html element based on a set max-height.
* It then stores the diff of the original text string in a hidden <span> element following the visible text.
* This means the original text remains intact!
*/
export default function shave(
target: string | Element | Element[],
maxHeight: number,
options?: Shave.Options
): Shave;
export interface Shave {
}
export namespace Shave {
export interface Options {
classname?: string,
character?: string,
spaces?: boolean
}
}
``` | /content/code_sandbox/types/index.d.ts | xml | 2016-10-19T21:54:46 | 2024-07-24T09:13:19 | shave | dollarshaveclub/shave | 2,110 | 121 |
```xml
import { Then } from 'cucumber';
import { expect } from 'chai';
import { getVisibleTextsForSelector } from '../../../common/e2e/steps/helpers';
import { getWalletUtxosTotalAmount } from '../../../../source/renderer/app/utils/utxoUtils';
const container = '.WalletUtxo_container';
const selectors = {
container,
title: `${container} > h1`,
description: `${container} > p`,
chart: '.WalletUtxo_responsiveContainer',
walletAmount: `${container} > p b:nth-child(1)`,
walletUtxosAmount: `${container} > p b:nth-child(2)`,
};
Then('the {string} element renders the following text:', async function (
element,
data
) {
const [expectedTextData] = data.hashes();
const [renderedText] = await getVisibleTextsForSelector(
this.client,
selectors[element]
);
const expectedText = await this.intl(expectedTextData.message);
expect(renderedText).to.equal(expectedText);
});
Then(
'the page description displays the correct wallet and UTXOs amount',
async function () {
const [renderedWalletAmount] = await getVisibleTextsForSelector(
this.client,
selectors.walletAmount
);
const [renderedWalletUtxosAmount] = await getVisibleTextsForSelector(
this.client,
selectors.walletUtxosAmount
);
const {
value: { expextedWalletAmount, distribution },
} = await this.client.executeAsync((done) => {
const { walletUtxos } = daedalus.stores.walletSettings || {};
const { activeValue } = daedalus.stores.wallets;
done({
expextedWalletAmount: activeValue,
distribution: walletUtxos ? walletUtxos.distribution : {},
});
});
const expectedWalletUtxosAmount = getWalletUtxosTotalAmount(distribution);
expect(expextedWalletAmount).to.equal(renderedWalletAmount);
expect(expectedWalletUtxosAmount).to.equal(
parseInt(renderedWalletUtxosAmount, 10)
);
}
);
Then(/^the UTXOs chart is (hidden|visible)/, async function (state) {
const isVisible = state === 'visible';
await this.client.waitForVisible(selectors.chart, null, !isVisible);
});
``` | /content/code_sandbox/tests/transactions/e2e/steps/utxos.ts | xml | 2016-10-05T13:48:54 | 2024-08-13T22:03:19 | daedalus | input-output-hk/daedalus | 1,230 | 516 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Application xmlns="path_to_url" xmlns:x="path_to_url" xmlns:d="path_to_url" xmlns:mc="path_to_url" mc:Ignorable="d" x:Class="MyXamarinFormsApp.App">
<Application.Resources>
</Application.Resources>
</Application>
``` | /content/code_sandbox/tests/common/TestProjects/MyCatalystFormsApp/MyCatalystFormsAppNS/App.xaml | xml | 2016-04-20T18:24:26 | 2024-08-16T13:29:19 | xamarin-macios | xamarin/xamarin-macios | 2,436 | 75 |
```xml
import * as React from 'react';
import { css, createArray } from '@fluentui/react/lib/Utilities';
import { Checkbox } from '@fluentui/react/lib/Checkbox';
import { MarqueeSelection, Selection, IObjectWithKey } from '@fluentui/react/lib/MarqueeSelection';
import { getTheme, mergeStyleSets } from '@fluentui/react/lib/Styling';
import { useBoolean, useConst, useForceUpdate } from '@fluentui/react-hooks';
interface IPhoto extends IObjectWithKey {
url: string;
width: number;
height: number;
}
const PHOTOS: IPhoto[] = createArray(250, (index: number) => {
const randomWidth = 50 + Math.floor(Math.random() * 150);
return {
key: index,
url: `path_to_url{randomWidth}x100.png`,
width: randomWidth,
height: 100,
};
});
const theme = getTheme();
const styles = mergeStyleSets({
photoList: {
display: 'inline-block',
border: '1px solid ' + theme.palette.neutralTertiary,
margin: 0,
padding: 10,
overflow: 'hidden',
userSelect: 'none',
},
photoCell: {
position: 'relative',
display: 'inline-block',
margin: 2,
boxSizing: 'border-box',
background: theme.palette.neutralLighter,
lineHeight: 100,
verticalAlign: 'middle',
textAlign: 'center',
selectors: {
'&.is-selected': {
background: theme.palette.themeLighter,
border: '1px solid ' + theme.palette.themePrimary,
},
},
},
checkbox: {
margin: '10px 0',
},
});
export const MarqueeSelectionBasicExample: React.FunctionComponent = () => {
const [isMarqueeEnabled, { toggle: toggleIsMarqueeEnabled }] = useBoolean(true);
const forceUpdate = useForceUpdate();
const selection = useConst(
() =>
new Selection<IPhoto>({
items: PHOTOS,
onSelectionChanged: forceUpdate,
}),
);
return (
<MarqueeSelection selection={selection} isEnabled={isMarqueeEnabled}>
<Checkbox
className={styles.checkbox}
label="Is marquee enabled"
defaultChecked
onChange={toggleIsMarqueeEnabled}
/>
<p>Drag a rectangle around the items below to select them:</p>
<ul className={styles.photoList}>
{PHOTOS.map((photo, index) => (
<div
key={index}
className={css(styles.photoCell, selection.isIndexSelected(index) && 'is-selected')}
data-is-focusable
data-selection-index={index}
style={{ width: photo.width, height: photo.height }}
>
{index}
</div>
))}
</ul>
</MarqueeSelection>
);
};
``` | /content/code_sandbox/packages/react-examples/src/react/MarqueeSelection/MarqueeSelection.Basic.Example.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 641 |
```xml
import * as slash from 'slash';
import {join} from 'path';
import {APP_BASE, APP_DEST, ENV} from '../config';
let injectables: string[] = [];
export function injectableAssetsRef() {
return injectables;
}
export function registerInjectableAssetsRef(paths: string[], target: string = '') {
injectables = injectables.concat(
paths
.filter(path => !/(\.map)$/.test(path))
.map(path => join(target, slash(path).split('/').pop()))
);
}
export function transformPath(plugins, env) {
return function (filepath) {
filepath = ENV === 'prod' ? filepath.replace(`/${APP_DEST}`, '') : filepath;
return slash(plugins.inject.transform.apply(plugins.inject.transform, arguments));
};
}
``` | /content/code_sandbox/tools/utils/template-injectables.ts | xml | 2016-01-04T01:19:52 | 2024-08-15T22:13:36 | pev | AlexTatiyants/pev | 2,757 | 170 |
```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>BuildMachineOSBuild</key>
<string>15C50</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>ACPIBatteryManager</string>
<key>CFBundleGetInfoString</key>
<key>CFBundleIdentifier</key>
<string>org.rehabman.driver.AppleSmartBatteryManager</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>ACPIBatteryManager</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>1.60.5</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>1.60.5</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>7C68</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>12D75</string>
<key>DTSDKName</key>
<string>macosx10.8</string>
<key>DTXcode</key>
<string>0720</string>
<key>DTXcodeBuild</key>
<string>7C68</string>
<key>IOKitPersonalities</key>
<dict>
<key>ACPI AC Adapter</key>
<dict>
<key>CFBundleIdentifier</key>
<string>org.rehabman.driver.AppleSmartBatteryManager</string>
<key>IOClass</key>
<string>rehab_ACPIACAdapter</string>
<key>IONameMatch</key>
<string>ACPI0003</string>
<key>IOProbeScore</key>
<integer>1000</integer>
<key>IOProviderClass</key>
<string>IOACPIPlatformDevice</string>
</dict>
<key>ACPI Battery Manager</key>
<dict>
<key>CFBundleIdentifier</key>
<string>org.rehabman.driver.AppleSmartBatteryManager</string>
<key>Configuration</key>
<dict>
<key>Correct16bitSignedCurrentRate</key>
<true/>
<key>CorrectCorruptCapacities</key>
<true/>
<key>CurrentDischargeRateMax</key>
<integer>20000</integer>
<key>EstimateCycleCountDivisor</key>
<integer>6</integer>
<key>StartupDelay</key>
<integer>50</integer>
<key>UseDesignVoltageForCurrentCapacity</key>
<true/>
<key>UseDesignVoltageForDesignCapacity</key>
<true/>
<key>UseDesignVoltageForMaxCapacity</key>
<true/>
<key>UseExtendedBatteryInformationMethod</key>
<true/>
<key>UseExtraBatteryInformationMethod</key>
<true/>
</dict>
<key>IOClass</key>
<string>rehab_ACPIBatteryManager</string>
<key>IONameMatch</key>
<string>PNP0C0A</string>
<key>IOProbeScore</key>
<integer>1000</integer>
<key>IOProviderClass</key>
<string>IOACPIPlatformDevice</string>
</dict>
<key>ACPI Battery Tracker</key>
<dict>
<key>CFBundleIdentifier</key>
<string>org.rehabman.driver.AppleSmartBatteryManager</string>
<key>IOClass</key>
<string>rehab_BatteryTracker</string>
<key>IOMatchCategory</key>
<string>rehab_BatteryTracker</string>
<key>IOProviderClass</key>
<string>IOResources</string>
<key>IOResourceMatch</key>
<string>IOKit</string>
</dict>
</dict>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.iokit.IOACPIFamily</key>
<string>1.0d1</string>
<key>com.apple.kpi.iokit</key>
<string>9.0</string>
<key>com.apple.kpi.libkern</key>
<string>9.0</string>
</dict>
<key>OSBundleRequired</key>
<string>Root</string>
<key>Source Code</key>
<string>path_to_url
</dict>
</plist>
``` | /content/code_sandbox/Clover-Configs/Dell/Dell XPS 13 9350/CLOVER/kexts/10.11/ACPIBatteryManager.kext/Contents/Info.plist | xml | 2016-11-05T04:22:54 | 2024-08-12T19:25:53 | Hackintosh-Installer-University | huangyz0918/Hackintosh-Installer-University | 3,937 | 1,221 |
```xml
<?xml version="1.0"?>
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<configuration>
<statusListener class="ch.qos.logback.core.status.NopStatusListener" />
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.apache.shardingsphere" level="warn" additivity="false">
<appender-ref ref="console" />
</logger>
<root>
<level value="error" />
<appender-ref ref="console" />
</root>
</configuration>
``` | /content/code_sandbox/test/native/src/test/resources/logback-test.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 235 |
```xml
export class OtpResult {
static cancel = new OtpResult("cancel", false);
constructor(
public passcode: string,
public rememberMe: boolean,
) {}
}
``` | /content/code_sandbox/libs/importer/src/importers/lastpass/access/models/otp-result.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 41 |
```xml
export class CipherCollectionsRequest {
collectionIds: string[];
constructor(collectionIds: string[]) {
this.collectionIds = collectionIds == null ? [] : collectionIds;
}
}
``` | /content/code_sandbox/libs/common/src/vault/models/request/cipher-collections.request.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 39 |
```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 { Iterator as Iter, IterableIterator } from '@stdlib/types/iter';
// Define a union type representing both iterable and non-iterable iterators:
type Iterator = Iter | IterableIterator;
/**
* Callback function invoked for each iterated value.
*
* @returns callback result
*/
type nullaryCallback = () => unknown;
/**
* Callback function invoked for each iterated value.
*
* @param value - iterated value
* @returns callback result
*/
type unaryCallback = ( value: unknown ) => unknown;
/**
* Callback function invoked for each iterated value.
*
* @param value - iterated value
* @param i - iteration index
* @returns callback result
*/
type binaryCallback = ( value: unknown, i: number ) => unknown;
/**
* Callback function invoked for each iterated value.
*
* @param value - iterated value
* @param i - iteration index
* @returns callback result
*/
type Callback = nullaryCallback | unaryCallback | binaryCallback;
/**
* Predicate function invoked for each iterated value.
*
* @returns a boolean indicating whether to continue iterating or not
*/
type nullaryPredicate = () => boolean;
/**
* Predicate function invoked for each iterated value.
*
* @param value - iterated value
* @returns a boolean indicating whether to continue iterating or not
*/
type unaryPredicate = ( value: unknown ) => boolean;
/**
* Predicate function invoked for each iterated value.
*
* @param value - iterated value
* @param i - iteration index
* @returns a boolean indicating whether to continue iterating or not
*/
type binaryPredicate = ( value: unknown, i: number ) => boolean;
/**
* Predicate function invoked for each iterated value.
*
* @param value - iterated value
* @param i - iteration index
* @returns a boolean indicating whether to continue iterating or not
*/
type Predicate = nullaryPredicate | unaryPredicate | binaryPredicate;
/**
* Returns an iterator which invokes a function for each iterated value **before** returning the iterated value until either a predicate function returns `true` or the iterator has iterated over all values.
*
* ## Notes
*
* - When invoked, both the `predicate` and callback functions are provided two arguments:
*
* - **value**: iterated value
* - **index**: iteration index (zero-based)
*
* - If an environment supports `Symbol.iterator` **and** a provided iterator is iterable, the returned iterator is iterable.
*
* @param iterator - input iterator
* @param predicate - function which indicates whether to continue iterating
* @param fcn - callback function to invoke for each iterated value
* @param thisArg - execution context
* @returns iterator
*
* @example
* var array2iterator = require( '@stdlib/array/to-iterator' );
*
* function predicate( v ) {
* return v > 2;
* }
*
* function assert( v, i ) {
* if ( i > 1 ) {
* throw new Error( 'unexpected error' );
* }
* }
*
* var it = iterDoUntilEach( array2iterator( [ 1, 2, 3, 4 ] ), predicate, assert );
* // returns {}
*
* var r = it.next().value;
* // returns 1
*
* r = it.next().value;
* // returns 2
*
* r = it.next().value;
* // undefined
*
* // ...
*/
declare function iterDoUntilEach( iterator: Iterator, predicate: Predicate, fcn: Callback, thisArg?: unknown ): Iterator;
// EXPORTS //
export = iterDoUntilEach;
``` | /content/code_sandbox/lib/node_modules/@stdlib/iter/do-until-each/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 840 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<sql-parser-test-cases>
<create-trigger sql-case-id="create_trigger" />
<create-trigger sql-case-id="create_trigger_with_database_scoped" />
<!-- <create-trigger sql-case-id="create_trigger_of_balance" />-->
<!-- <create-trigger sql-case-id="create_trigger_with_when" />-->
<!-- <create-trigger sql-case-id="create_trigger_after_update" />-->
<create-trigger sql-case-id="create_trigger_with_create_view" />
<create-trigger sql-case-id="create_trigger_with_dml_event_clause" />
<create-trigger sql-case-id="create_trigger_with_body" />
<create-trigger sql-case-id="create_trigger_with_execute_immediate_statement" />
<create-trigger sql-case-id="create_trigger_with_assignment_statement" />
<create-trigger sql-case-id="create_trigger_with_logon" />
<create-trigger sql-case-id="create_trigger_with_cascade_1" />
<create-trigger sql-case-id="create_trigger_with_cascade_2" />
<create-trigger sql-case-id="create_trigger_with_cascade_3" />
<create-trigger sql-case-id="create_trigger_with_cascade_4" />
<create-trigger sql-case-id="create_trigger_with_dataManipulationLanguage_statement" />
<create-trigger sql-case-id="create_trigger_with_exceptionInit_pragma" />
<create-trigger sql-case-id="create_trigger_with_dml_event" />
</sql-parser-test-cases>
``` | /content/code_sandbox/test/it/parser/src/main/resources/case/ddl/create-trigger.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 389 |
```xml
import path from 'path';
import { expect } from 'chai';
import sinon from 'sinon';
import { testInjector } from '@stryker-mutator/test-helpers';
import type { requireResolve } from '@stryker-mutator/util';
import { ReactScriptsJestConfigLoader } from '../../../src/config-loaders/react-scripts-jest-config-loader.js';
import { pluginTokens } from '../../../src/plugin-di.js';
import { JestRunnerOptionsWithStrykerOptions } from '../../../src/jest-runner-options-with-stryker-options.js';
import { createJestOptions } from '../../helpers/producers.js';
describe(ReactScriptsJestConfigLoader.name, () => {
let sut: ReactScriptsJestConfigLoader;
let requireResolveStub: sinon.SinonStub;
let requireFromCwdStub: sinon.SinonStubbedMember<typeof requireResolve>;
let createReactJestConfigStub: sinon.SinonStub;
let processEnvMock: NodeJS.ProcessEnv;
beforeEach(() => {
createReactJestConfigStub = sinon.stub();
requireResolveStub = sinon.stub();
requireResolveStub.returns(path.resolve('./node_modules/react-scripts/package.json'));
createReactJestConfigStub.returns({ testPaths: ['example'], watchPlugins: undefined });
requireFromCwdStub = sinon.stub();
requireFromCwdStub.returns(createReactJestConfigStub);
processEnvMock = {
NODE_ENV: undefined,
};
sut = testInjector.injector
.provideValue(pluginTokens.processEnv, processEnvMock)
.provideValue(pluginTokens.resolve, requireResolveStub as unknown as RequireResolve)
.provideValue(pluginTokens.requireFromCwd, requireFromCwdStub)
.injectClass(ReactScriptsJestConfigLoader);
});
it('should load the configuration via the createJestConfig method provided by react-scripts', async () => {
const config = await sut.loadConfig();
expect(requireResolveStub).calledWith('react-scripts/package.json');
expect(requireFromCwdStub).calledWith('react-scripts/scripts/utils/createJestConfig');
expect(createReactJestConfigStub).calledWith(sinon.match.func, process.cwd(), false);
expect(config).deep.eq({ testPaths: ['example'], watchPlugins: undefined });
});
it('should throw an error when react-scripts could not be found', async () => {
// Arrange
const error: NodeJS.ErrnoException = new Error('');
error.code = 'MODULE_NOT_FOUND';
requireResolveStub.throws(error);
// Act & Assert
await expect(sut.loadConfig()).rejectedWith(
'Unable to locate package "react-scripts". This package is required when "jest.projectType" is set to "create-react-app".',
);
});
it('should load "react-scripts/config/env.js" when projectType = create-react-app', async () => {
const options = testInjector.options as JestRunnerOptionsWithStrykerOptions;
options.jest = createJestOptions({ projectType: 'create-react-app' });
await sut.loadConfig();
expect(requireFromCwdStub).calledWith('react-scripts/config/env.js');
});
it("should set process.env.NODE_ENV to 'test' when process.env.NODE_ENV is null", async () => {
await sut.loadConfig();
expect(processEnvMock.NODE_ENV).to.equal('test');
});
it('should keep the value set in process.env.NODE_ENV if not null', async () => {
processEnvMock.NODE_ENV = 'stryker';
await sut.loadConfig();
expect(processEnvMock.NODE_ENV).to.equal('stryker');
});
});
``` | /content/code_sandbox/packages/jest-runner/test/unit/config-loaders/react-scripts-jest-config-loader.spec.ts | xml | 2016-02-12T13:14:28 | 2024-08-15T18:38:25 | stryker-js | stryker-mutator/stryker-js | 2,561 | 770 |
```xml
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ToastComponent } from './toast.component';
import { GlobalService } from '../../../services/global.service';
describe('ToastComponent', () => {
let component: ToastComponent;
let fixture: ComponentFixture<ToastComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ToastComponent],
providers: [GlobalService],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ToastComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
``` | /content/code_sandbox/frontend_v2/src/app/components/utility/toast/toast.component.spec.ts | xml | 2016-10-21T00:51:45 | 2024-08-16T14:41:56 | EvalAI | Cloud-CV/EvalAI | 1,736 | 134 |
```xml
import {Inject, Req} from "@tsed/common";
import {Unauthorized} from "@tsed/exceptions";
import {Arg, OnVerify, Protocol} from "@tsed/passport";
import {GraphQLLocalStrategy} from "graphql-passport";
import {UsersRepository} from "../services/UsersRepository.js";
@Protocol<any>({
name: "graphql-local",
useStrategy: GraphQLLocalStrategy,
settings: {}
})
export class GraphQLProtocol implements OnVerify {
@Inject()
protected repository: UsersRepository;
async $onVerify(@Req() request: Req, @Arg(0) email: string, @Arg(1) password: string) {
const user = await this.repository.authenticate(email, password);
if (!user) {
throw new Unauthorized("Wrong credentials");
}
return user;
}
}
``` | /content/code_sandbox/packages/graphql/typegraphql/test/app/protocols/GraphQLProtocol.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 173 |
```xml
export { default, default as CreateUsername } from "./CreateUsername";
``` | /content/code_sandbox/client/src/core/client/auth/views/CreateUsername/index.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 15 |
```xml
import * as React from 'react';
import { getAccessibilityChecker, TestType } from '../../utils/getAccessibilityChecker';
import { AccessibilityContrastChip } from '../ColorTokens/AccessibilityList';
import { BrandVariants, createLightTheme, Label, Theme, tokens } from '@fluentui/react-components';
import { createDarkThemeWithUpdatedMapping } from '../../utils/getOverridableTokenBrandColors';
export interface AccessibilityPanelProps {
lightThemeOverrides: Partial<Theme>;
darkThemeOverrides: Partial<Theme>;
brand: BrandVariants;
}
export const AccessibilityPanel: React.FC<AccessibilityPanelProps> = props => {
const { lightThemeOverrides, darkThemeOverrides, brand } = props;
const { failedContrastTests: failLight } = getAccessibilityChecker({
...createLightTheme(brand),
...lightThemeOverrides,
});
const { failedContrastTests: failDark } = getAccessibilityChecker({
...createDarkThemeWithUpdatedMapping(brand),
...darkThemeOverrides,
});
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: tokens.spacingVerticalM,
}}
>
<Label>Light mode</Label>
<AccessibilityContrastChip failKeys={Object.keys(failLight)} testType={TestType.contrastRatio} />
<Label style={{ paddingTop: tokens.spacingVerticalXS }}>Dark mode</Label>
<AccessibilityContrastChip failKeys={Object.keys(failDark)} testType={TestType.contrastRatio} />
</div>
);
};
``` | /content/code_sandbox/packages/react-components/theme-designer/src/components/Sidebar/AccessibilityPanel.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 334 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definition"
xmlns="path_to_url"
xmlns:xsi="path_to_url"
xmlns:activiti="path_to_url"
targetNamespace="Examples">
<process id="miSequentialScriptTask">
<startEvent id="theStart" />
<sequenceFlow id="flow1" sourceRef="theStart" targetRef="miScriptTask" />
<scriptTask id="miScriptTask" scriptFormat="groovy">
<multiInstanceLoopCharacteristics isSequential="true">
<loopCardinality>${nrOfLoops}</loopCardinality>
</multiInstanceLoopCharacteristics>
<script>
<![CDATA[
def processInstance = execution.getProcessInstance()
def int sum = processInstance.getVariable("sum")
processInstance.setVariable("sum", sum + loopCounter)
]]>
</script>
</scriptTask>
<sequenceFlow id="flow3" sourceRef="miScriptTask" targetRef="waitState" />
<receiveTask id="waitState" />
<sequenceFlow id="flow4" sourceRef="waitState" targetRef="theEnd" />
<endEvent id="theEnd" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/engine/test/bpmn/multiinstance/MultiInstanceTest.testSequentialScriptTasks.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 281 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
published by the Free Software Foundation. Oracle designates this
particular file as subject to the "Classpath" exception as provided
by Oracle in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
or visit www.oracle.com if you need additional information or have any
questions.
-->
<project basedir="." default="netbeans" name="profiler.attach">
<description>Builds, tests, and runs the project org.graalvm.visualvm.lib.profiler.attach</description>
<import file="nbproject/build-impl.xml"/>
</project>
``` | /content/code_sandbox/visualvm/libs.profiler/profiler.attach/build.xml | xml | 2016-09-12T14:44:30 | 2024-08-16T14:41:50 | visualvm | oracle/visualvm | 2,821 | 265 |
```xml
import {getEphemeralServerTarget} from "@temporalio/core-bridge";
import {Runtime} from "@temporalio/worker";
import {PlatformTest} from "@tsed/common";
import {TemporalClient} from "../src/index.js";
import {Server} from "./helpers/Server.js";
describe("Temporal Client", () => {
let server: any;
let client: TemporalClient;
beforeEach(async () => {
server = await Runtime.instance().createEphemeralServer({type: "time-skipping"});
});
afterEach(async () => {
if (client) {
await client.connection.close();
}
await Runtime.instance().shutdownEphemeralServer(server);
});
it("should provide TemporalClient", async () => {
const server = await Runtime.instance().createEphemeralServer({type: "time-skipping"});
const address = getEphemeralServerTarget(server);
await PlatformTest.bootstrap(Server, {
temporal: {
enabled: true,
connection: {
address
}
}
})();
client = PlatformTest.get<TemporalClient>(TemporalClient);
expect(client).toBeInstanceOf(TemporalClient);
});
});
``` | /content/code_sandbox/packages/third-parties/temporal/test/client.integration.spec.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 252 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/**
* Evaluates the quantile function for a binomial distribution.
*
* ## Notes
*
* - If `r < 0` or `r > 1`, the function returns `NaN`.
*
* @param r - input value
* @returns evaluated quantile function
*/
type Unary = ( r: number ) => number;
/**
* Interface for the quantile function of a binomial distribution.
*/
interface Quantile {
/**
* Evaluates the quantile function for a binomial distribution with number of trials `n` and success probability `p` at a probability `r`.
*
* ## Notes
*
* - If `r < 0` or `r > 1`, the function returns `NaN`.
* - If provided a number of trials `n` which is not a nonnegative integer, the function returns `NaN`.
* - If `p < 0` or `p > 1`, the function returns `NaN`.
*
* @param r - input value
* @param n - number of trials
* @param p - success probability
* @returns evaluated quantile function
*
* @example
* var y = quantile( 0.4, 20, 0.2 );
* // returns 3
*
* @example
* var y = quantile( 0.8, 20, 0.2 );
* // returns 5
*
* @example
* var y = quantile( 0.5, 10, 0.4 );
* // returns 4
*
* @example
* var y = quantile( 0.0, 10, 0.4 );
* // returns 0
*
* @example
* var y = quantile( 1.0, 10, 0.4 );
* // returns 10
*
* @example
* var y = quantile( NaN, 20, 0.5 );
* // returns NaN
*
* @example
* var y = quantile( 0.2, NaN, 0.5 );
* // returns NaN
*
* @example
* var y = quantile( 0.2, 20, NaN );
* // returns NaN
*
* @example
* var y = quantile( 0.5, 1.5, 0.5 );
* // returns NaN
*
* @example
* var y = quantile( 0.5, -2.0, 0.5 );
* // returns NaN
*
* @example
* var y = quantile( 0.5, 20, -1.0 );
* // returns NaN
*
* @example
* var y = quantile( 0.5, 20, 1.5 );
* // returns NaN
*/
( r: number, n: number, p: number ): number;
/**
* Returns a function for evaluating the quantile function for a binomial distribution with number of trials `n` and success probability `p`.
*
* @param n - number of trials
* @param p - success probability
* @returns quantile function
*
* @example
* var myQuantile = quantile.factory( 10, 0.5 );
* var y = myQuantile( 0.1 );
* // returns 3
*
* y = myQuantile( 0.9 );
* // returns 7
*/
factory( n: number, p: number ): Unary;
}
/**
* Binomial distribution quantile function.
*
* @param p - input value
* @param n - number of trials
* @param p - success probability
* @returns evaluated quantile function
*
* @example
* var y = quantile( 0.4, 20, 0.2 );
* // returns 2
*
* y = quantile( 0.8, 20, 0.2 );
* // returns 5
*
* y = quantile( 0.5, 10, 0.4 );
* // returns 4
*
* var myQuantile = quantile.factory( 10, 0.5 );
*
* y = myQuantile( 0.1 );
* // returns 3
*
* y = myQuantile( 0.9 );
* // returns 7
*/
declare var quantile: Quantile;
// EXPORTS //
export = quantile;
``` | /content/code_sandbox/lib/node_modules/@stdlib/stats/base/dists/binomial/quantile/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 1,082 |
```xml
import { pureMerge } from "coral-common/common/lib/utils";
import { DeepPartial } from "coral-framework/types";
/**
* Callbackify turns Fields e.g. `{a: string}`
* to also allow a callback `{a: string | () => string}`
*/
export type Callbackify<T> = T extends object
?
| {
[P in keyof T]: T[P] extends Array<infer U> | undefined
? Array<Callbackify<U>>
: T[P] extends ReadonlyArray<infer V> | undefined
? ReadonlyArray<Callbackify<V>>
: Callbackify<T[P]>;
}
| (() => {
[P in keyof T]: T[P] extends Array<infer U> | undefined
? Array<Callbackify<U>>
: T[P] extends ReadonlyArray<infer V> | undefined
? ReadonlyArray<Callbackify<V>>
: Callbackify<T[P]>;
})
: T | (() => T);
/**
* WithTypename adds `__typename` to allowed props deeply.
*/
export type WithTypename<T> = T extends object
? {
[P in keyof T]: T[P] extends Array<infer U> | undefined
? Array<WithTypename<U>>
: T[P] extends ReadonlyArray<infer V> | undefined
? ReadonlyArray<WithTypename<V>>
: WithTypename<T[P]>;
} & { __typename?: string }
: T;
/**
* Fixture adds typenames and is deeply partial.
*/
export type Fixture<T> = DeepPartial<WithTypename<T>>;
/**
* createFixture lets you input the data of a schema object as deep partial
* including it's `__typename`, merged it with `base` and return it as the
* schema object's type. In the future the result could be trimmed down
* to only include fields that exists in `data` and `base` though to
* type this it seems we need partial generic inferation support.
*/
export default function createFixture<T>(
data: Fixture<T>,
base?: T
): WithTypename<T> {
if (base) {
return pureMerge(base, data) as any;
}
return data as any;
}
``` | /content/code_sandbox/client/src/core/client/framework/testHelpers/createFixture.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 477 |
```xml
import "reflect-metadata"
import { DataSource, Table } from "../../../src"
import {
closeTestingConnections,
createTestingConnections,
reloadTestingDatabases,
} from "../../utils/test-utils"
import { TableExclusion } from "../../../src/schema-builder/table/TableExclusion"
describe("query runner > create exclusion constraint", () => {
let connections: DataSource[]
before(async () => {
connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
enabledDrivers: ["postgres"], // Only PostgreSQL supports exclusion constraints.
schemaCreate: true,
dropSchema: true,
})
})
beforeEach(() => reloadTestingDatabases(connections))
after(() => closeTestingConnections(connections))
it("should correctly create exclusion constraint and revert creation", () =>
Promise.all(
connections.map(async (connection) => {
const queryRunner = connection.createQueryRunner()
await queryRunner.createTable(
new Table({
name: "question",
columns: [
{
name: "id",
type: "int",
isPrimary: true,
},
{
name: "name",
type: "varchar",
},
{
name: "description",
type: "varchar",
},
{
name: "version",
type: "int",
},
],
}),
true,
)
// clear sqls in memory to avoid removing tables when down queries executed.
queryRunner.clearSqlMemory()
const driver = connection.driver
const exclusion1 = new TableExclusion({
expression: `USING gist (${driver.escape("name")} WITH =)`,
})
const exclusion2 = new TableExclusion({
expression: `USING gist (${driver.escape("id")} WITH =)`,
})
await queryRunner.createExclusionConstraints("question", [
exclusion1,
exclusion2,
])
let table = await queryRunner.getTable("question")
table!.exclusions.length.should.be.equal(2)
await queryRunner.executeMemoryDownSql()
table = await queryRunner.getTable("question")
table!.exclusions.length.should.be.equal(0)
await queryRunner.release()
}),
))
})
``` | /content/code_sandbox/test/functional/query-runner/create-exclusion-constraint.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 468 |
```xml
type allowedAudiences = "me" | "organization" | "groupMembers" | "everyone";
export interface IAward {
id: string;
displayName: string;
allowedAudiences: allowedAudiences;
description: string;
issuedDate: string;
issuingAuthority: string;
thumbnailUrl: string;
webUrl: string;
}
``` | /content/code_sandbox/samples/react-graph-profile-awards/src/models/IAward.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 76 |
```xml
import * as assert from 'assert'
import * as sinon from 'sinon'
import * as proxyquire from 'proxyquire'
import * as PgPromise from 'pg-promise'
import { TableDefinition } from '../../src/schemaInterfaces'
import Options from '../../src/options'
const options = new Options({})
const pgp = PgPromise()
describe('PostgresDatabase', () => {
const sandbox = sinon.sandbox.create()
const db = {
query: sandbox.stub(),
each: sandbox.stub(),
map: sandbox.stub()
}
let PostgresDBReflection: any
let PostgresProxy: any
before(() => {
const pgpStub: any = () => db
pgpStub.as = pgp.as
const SchemaPostgres = proxyquire('../../src/schemaPostgres', {
'pg-promise': () => pgpStub
})
PostgresDBReflection = SchemaPostgres.PostgresDatabase
PostgresProxy = new PostgresDBReflection()
})
beforeEach(() => {
sandbox.reset()
})
after(() => {
sandbox.restore()
})
describe('query', () => {
it('calls postgres query', () => {
PostgresProxy.query('SELECT * FROM TEST')
assert.equal(db.query.getCall(0).args[0], 'SELECT * FROM TEST')
})
})
describe('getEnumTypes', () => {
it('writes correct query with schema name', () => {
PostgresProxy.getEnumTypes('schemaName')
assert.equal(db.each.getCall(0).args[0],
'select n.nspname as schema, t.typname as name, e.enumlabel as value ' +
'from pg_type t join pg_enum e on t.oid = e.enumtypid ' +
'join pg_catalog.pg_namespace n ON n.oid = t.typnamespace ' +
'where n.nspname = \'schemaName\' ' +
'order by t.typname asc, e.enumlabel asc;')
assert.deepEqual(db.each.getCall(0).args[1], [])
})
it('writes correct query without schema name', () => {
PostgresProxy.getEnumTypes()
assert.equal(db.each.getCall(0).args[0],
'select n.nspname as schema, t.typname as name, e.enumlabel as value ' +
'from pg_type t join pg_enum e on t.oid = e.enumtypid ' +
'join pg_catalog.pg_namespace n ON n.oid = t.typnamespace ' +
'order by t.typname asc, e.enumlabel asc;')
assert.deepEqual(db.each.getCall(0).args[1], [])
})
it('handles response from db', async () => {
let enums = await PostgresProxy.getEnumTypes()
const callback = db.each.getCall(0).args[2]
const dbResponse = [
{name: 'name', value: 'value1'},
{name: 'name', value: 'value2'}
]
dbResponse.forEach(callback)
assert.deepEqual(enums, {name: ['value1', 'value2']})
})
})
describe('getTableDefinition', () => {
it('writes correct query', () => {
PostgresProxy.getTableDefinition('tableName', 'schemaName')
assert.equal(db.each.getCall(0).args[0],
'SELECT column_name, udt_name, is_nullable ' +
'FROM information_schema.columns ' +
'WHERE table_name = $1 and table_schema = $2')
assert.deepEqual(db.each.getCall(0).args[1], ['tableName', 'schemaName'])
})
it('handles response from db', async () => {
let tableDefinition = await PostgresProxy.getTableDefinition()
const callback = db.each.getCall(0).args[2]
const dbResponse = [
{column_name: 'col1', udt_name: 'int2', is_nullable: 'YES'},
{column_name: 'col2', udt_name: 'text', is_nullable: 'NO'}
]
dbResponse.forEach(callback)
assert.deepEqual(tableDefinition, {
col1: { udtName: 'int2', nullable: true },
col2: { udtName: 'text', nullable: false }
})
})
})
describe('getTableTypes', () => {
const tableTypesSandbox = sinon.sandbox.create()
before(() => {
tableTypesSandbox.stub(PostgresProxy, 'getEnumTypes')
tableTypesSandbox.stub(PostgresProxy, 'getTableDefinition')
tableTypesSandbox.stub(PostgresDBReflection, 'mapTableDefinitionToType')
})
beforeEach(() => {
tableTypesSandbox.reset()
})
after(() => {
tableTypesSandbox.restore()
})
it('gets custom types from enums', async () => {
PostgresProxy.getEnumTypes.returns(Promise.resolve({enum1: [], enum2: []}))
PostgresProxy.getTableDefinition.returns(Promise.resolve({}))
await PostgresProxy.getTableTypes('tableName', 'tableSchema')
assert.deepEqual(PostgresDBReflection.mapTableDefinitionToType.getCall(0).args[1], ['enum1', 'enum2'])
})
it('gets table definitions', async () => {
PostgresProxy.getEnumTypes.returns(Promise.resolve({}))
PostgresProxy.getTableDefinition.returns(Promise.resolve({ table: {
udtName: 'name',
nullable: false
}}))
await PostgresProxy.getTableTypes('tableName', 'tableSchema')
assert.deepEqual(PostgresProxy.getTableDefinition.getCall(0).args, ['tableName', 'tableSchema'])
assert.deepEqual(PostgresDBReflection.mapTableDefinitionToType.getCall(0).args[0], { table: {
udtName: 'name',
nullable: false
}})
})
})
describe('getSchemaTables', () => {
it('writes correct query', () => {
PostgresProxy.getSchemaTables('schemaName')
assert.equal(db.map.getCall(0).args[0],
'SELECT table_name ' +
'FROM information_schema.columns ' +
'WHERE table_schema = $1 ' +
'GROUP BY table_name')
assert.deepEqual(db.map.getCall(0).args[1], ['schemaName'])
})
it('handles response from db', async () => {
await PostgresProxy.getSchemaTables()
const callback = db.map.getCall(0).args[2]
const dbResponse = [
{table_name: 'table1'},
{table_name: 'table2'}
]
const schemaTables = dbResponse.map(callback)
assert.deepEqual(schemaTables, ['table1','table2'])
})
})
describe('mapTableDefinitionToType', () => {
describe('maps to string', () => {
it('bpchar', () => {
const td: TableDefinition = {
column: {
udtName: 'bpchar',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('char', () => {
const td: TableDefinition = {
column: {
udtName: 'char',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('varchar', () => {
const td: TableDefinition = {
column: {
udtName: 'varchar',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('text', () => {
const td: TableDefinition = {
column: {
udtName: 'text',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('citext', () => {
const td: TableDefinition = {
column: {
udtName: 'citext',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('uuid', () => {
const td: TableDefinition = {
column: {
udtName: 'uuid',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('bytea', () => {
const td: TableDefinition = {
column: {
udtName: 'bytea',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('inet', () => {
const td: TableDefinition = {
column: {
udtName: 'inet',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('time', () => {
const td: TableDefinition = {
column: {
udtName: 'time',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('timetz', () => {
const td: TableDefinition = {
column: {
udtName: 'timetz',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('interval', () => {
const td: TableDefinition = {
column: {
udtName: 'interval',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
it('name', () => {
const td: TableDefinition = {
column: {
udtName: 'name',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'string')
})
})
describe('maps to number', () => {
it('int2', () => {
const td: TableDefinition = {
column: {
udtName: 'int2',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'number')
})
it('int4', () => {
const td: TableDefinition = {
column: {
udtName: 'int4',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'number')
})
it('int8', () => {
const td: TableDefinition = {
column: {
udtName: 'int8',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'number')
})
it('float4', () => {
const td: TableDefinition = {
column: {
udtName: 'float4',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'number')
})
it('float8', () => {
const td: TableDefinition = {
column: {
udtName: 'float8',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'number')
})
it('numeric', () => {
const td: TableDefinition = {
column: {
udtName: 'numeric',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'number')
})
it('money', () => {
const td: TableDefinition = {
column: {
udtName: 'money',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'number')
})
it('oid', () => {
const td: TableDefinition = {
column: {
udtName: 'oid',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'number')
})
})
describe('maps to boolean', () => {
it('bool', () => {
const td: TableDefinition = {
column: {
udtName: 'bool',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'boolean')
})
})
describe('maps to Object', () => {
it('json', () => {
const td: TableDefinition = {
column: {
udtName: 'json',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Object')
})
it('jsonb', () => {
const td: TableDefinition = {
column: {
udtName: 'jsonb',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Object')
})
})
describe('maps to Date', () => {
it('date', () => {
const td: TableDefinition = {
column: {
udtName: 'date',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Date')
})
it('timestamp', () => {
const td: TableDefinition = {
column: {
udtName: 'timestamp',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Date')
})
it('timestamptz', () => {
const td: TableDefinition = {
column: {
udtName: 'timestamptz',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Date')
})
})
describe('maps to Array<number>', () => {
it('_int2', () => {
const td: TableDefinition = {
column: {
udtName: '_int2',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<number>')
})
it('_int4', () => {
const td: TableDefinition = {
column: {
udtName: '_int4',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<number>')
})
it('_int8', () => {
const td: TableDefinition = {
column: {
udtName: '_int8',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<number>')
})
it('_float4', () => {
const td: TableDefinition = {
column: {
udtName: '_float4',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<number>')
})
it('_float8', () => {
const td: TableDefinition = {
column: {
udtName: '_float8',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<number>')
})
it('_numeric', () => {
const td: TableDefinition = {
column: {
udtName: '_numeric',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<number>')
})
it('_money', () => {
const td: TableDefinition = {
column: {
udtName: '_money',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<number>')
})
})
describe('maps to Array<boolean>', () => {
it('_bool', () => {
const td: TableDefinition = {
column: {
udtName: '_bool',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'Array<boolean>')
})
})
describe('maps to Array<string>', () => {
it('_varchar', () => {
const td: TableDefinition = {
column: {
udtName: '_varchar',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'Array<string>')
})
it('_text', () => {
const td: TableDefinition = {
column: {
udtName: '_text',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'Array<string>')
})
it('_citext', () => {
const td: TableDefinition = {
column: {
udtName: '_citext',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'Array<string>')
})
it('_uuid', () => {
const td: TableDefinition = {
column: {
udtName: '_uuid',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'Array<string>')
})
it('_bytea', () => {
const td: TableDefinition = {
column: {
udtName: '_bytea',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'Array<string>')
})
})
describe('maps to Array<Object>', () => {
it('_json', () => {
const td: TableDefinition = {
column: {
udtName: '_json',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<Object>')
})
it('_jsonb', () => {
const td: TableDefinition = {
column: {
udtName: '_jsonb',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<Object>')
})
})
describe('maps to Array<Date>', () => {
it('_timestamptz', () => {
const td: TableDefinition = {
column: {
udtName: '_timestamptz',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td,[],options).column.tsType, 'Array<Date>')
})
})
describe('maps to custom', () => {
it('CustomType', () => {
const td: TableDefinition = {
column: {
udtName: 'CustomType',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'CustomType')
})
})
describe('maps to any', () => {
it('UnknownType', () => {
const td: TableDefinition = {
column: {
udtName: 'UnknownType',
nullable: false
}
}
assert.equal(PostgresDBReflection.mapTableDefinitionToType(td, ['CustomType'], options).column.tsType, 'any')
})
})
})
})
``` | /content/code_sandbox/test/unit/schemaPostgres.test.ts | xml | 2016-08-15T17:54:26 | 2024-08-08T15:46:34 | schemats | SweetIQ/schemats | 1,032 | 4,445 |
```xml
export * from "./relationships";
``` | /content/code_sandbox/src/file/relationships/index.ts | xml | 2016-03-26T23:43:56 | 2024-08-16T13:02:47 | docx | dolanmiu/docx | 4,139 | 7 |
```xml
const tree = [
{
List: ['include', 'environment', 'variables', 'relational', 'comparator-i;ascii-numeric', 'spamtest'],
Type: 'Require',
},
{
List: ['fileinto', 'imap4flags'],
Type: 'Require',
},
{
Text: '# Generated: Do not run this script on spam messages',
Type: 'Comment',
},
{
If: {
Tests: [
{
Name: 'vnd.proton.spam-threshold',
Keys: ['*'],
Format: null,
Match: {
Type: 'Matches',
},
Type: 'Environment',
},
{
Value: {
Value: '${1}',
Type: 'VariableString',
},
Flags: [],
Format: {
Type: 'ASCIINumeric',
},
Match: {
Comparator: 'ge',
Type: 'GreaterEqualsValue',
},
Type: 'SpamTest',
},
],
Type: 'AllOf',
},
Then: [
{
Type: 'Return',
},
],
Type: 'If',
},
];
export default { tree, simple: undefined };
``` | /content/code_sandbox/packages/sieve/fixtures/v2SpamOnly.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 262 |
```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>CFBundleDisplayName</key>
<string>BasicPCLTest</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>com.xamarin.BasicPCLTest</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>BasicPCLTest</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>10.15</string>
<string>MM</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
``` | /content/code_sandbox/tests/common/TestProjects/BasicPCLTest/BasicPCLTest/Info.plist | xml | 2016-04-20T18:24:26 | 2024-08-16T13:29:19 | xamarin-macios | xamarin/xamarin-macios | 2,436 | 291 |
```xml
import React, { useMemo, useCallback, useState } from 'react'
import { usePage } from '../../../../../../cloud/lib/stores/pageStore'
import { SerializedUser } from '../../../../../../cloud/interfaces/db/user'
import { FormSelectOption } from '../../../../../../design/components/molecules/Form/atoms/FormSelect'
import styled from '../../../../../../design/lib/styled'
import UserIcon from '../../../../../../cloud/components/UserIcon'
import Select from 'react-select'
import cc from 'classcat'
import {
contextMenuFormItem,
textOverflow,
} from '../../../../../../design/lib/styled/styleFunctions'
import { useI18n } from '../../../../../../cloud/lib/hooks/useI18n'
import { lngKeys } from '../../../../../../cloud/lib/i18n/types'
interface DocAssigneeSelectProps {
disabled?: boolean
defaultValue: string[]
update: (value: string[]) => void
isLoading: boolean
readOnly: boolean
}
const DocAssigneeSelect = ({
disabled = false,
defaultValue,
isLoading,
readOnly,
update,
}: DocAssigneeSelectProps) => {
const { permissions } = usePage()
const [focused, setFocused] = useState(false)
const [value, setValue] = useState(defaultValue)
const { translate } = useI18n()
const options = useMemo(() => {
if (permissions == null) {
return []
}
return permissions.map((permission) => {
return getOptionByUser(permission.user)
})
}, [permissions])
const selectedOptions = useMemo(() => {
if (permissions == null) {
return []
}
const userMap = permissions.reduce((map, permission) => {
const { user } = permission
map.set(user.id, user)
return map
}, new Map())
return getSelectedOptionsByUserId(value, userMap)
}, [permissions, value])
const updateAssignees = useCallback(
(selectedOptions: any) => {
const value = (selectedOptions as FormSelectOption[]).map(
(option) => option.value
)
setValue(value)
update(value)
},
[update, setValue]
)
return (
<SelectContainer>
<Select
isMulti
className={cc([
'form__select',
focused && 'form__select--focused',
disabled && 'form__select--disabled',
readOnly && 'form__select--readOnly',
])}
id='assignee-select'
classNamePrefix='form__select'
isDisabled={disabled}
options={options}
value={selectedOptions}
isClearable={false}
onChange={updateAssignees}
placeholder={translate(lngKeys.Unassigned)}
isLoading={isLoading}
isSearchable={false}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
/>
</SelectContainer>
)
}
const SelectContainer = styled.div`
.form__select--readOnly .form__select__multi-value__remove {
display: none;
}
.form__select .form__select__indicator-separator {
width: 0;
}
.form__select .form__select__dropdown-indicator {
display: none;
}
.form__select .form__select__indicators {
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
}
.form__select .form__select__control,
.form__select .form__select__value-container {
height: 30px !important;
min-height: 30px !important;
background: none !important;
border: 1px solid transparent !important;
}
.form__select .form__select__placeholder {
color: ${({ theme }) => theme.colors.text.subtle};
margin: 0;
}
.form__select .form__select__control {
width: 100%;
position: relative;
&:hover,
&.form__select__control--is-focused {
.form__select__placeholder {
color: ${({ theme }) => theme.colors.text.primary};
}
}
${({ theme }) =>
contextMenuFormItem({ theme }, '.form__select__control--is-focused')}
}
.form__select .form__select__value-container {
align-items: flex-start !important;
flex-wrap: wrap;
padding: 0 !important;
top: 0;
left: 5px;
position: absolute;
width: 100%;
}
.form__select .form__select__multi-value {
position: relative;
height: 100%;
background: none;
margin: 0;
}
.form__select .form__select__multi-value__remove {
height: auto;
position: absolute;
top: 0px;
right: -16px;
background: none !important;
&:hover {
color: ${({ theme }) => theme.colors.variants.primary.text};
}
}
.form__select .form__select__value-container,
.form__select .form__select__multi-value__label,
.form__select .form__select__multi-value__remove {
color: ${({ theme }) => theme.colors.text.primary};
}
.form__select .form__select__menu {
background-color: ${({ theme }) => theme.colors.background.primary};
border: 1px solid ${({ theme }) => theme.colors.border.main};
}
.form__select .form__select__option {
color: ${({ theme }) => theme.colors.text.secondary};
cursor: default;
&.form__select__option--is-disabled {
color: ${({ theme }) => theme.colors.text.subtle};
cursor: not-allowed;
}
&.form__select__option--is-selected,
&:active:not(.form__select__option--is-disabled) {
background-color: ${({ theme }) => theme.colors.variants.primary.base};
color: ${({ theme }) => theme.colors.variants.primary.text};
}
&.form__select__option--is-focused {
transition: 0.2s;
color: ${({ theme }) => theme.colors.text.primary};
background-color: ${({ theme }) => theme.colors.background.tertiary};
}
&:hover {
background-color: ${({ theme }) => theme.colors.background.quaternary};
transition: 0.2s;
}
}
.form__select__multi-value__label {
margin: 0;
padding: 0;
.assignee__item__label {
display: none;
}
}
`
export default DocAssigneeSelect
const ItemContainer = styled.div`
display: flex;
align-items: center;
height: 30px;
.assignee__item__label {
${textOverflow}
}
.assignee__item__icon {
width: 20px;
height: 20px;
font-size: 12px;
line-height: 18px;
margin-right: 4px;
flex-shrink: 0;
}
`
function getOptionByUser(user: SerializedUser): FormSelectOption {
return {
label: (
<ItemContainer>
<UserIcon user={user} className='assignee__item__icon' />
<div className='assignee__item__label'>{user.displayName}</div>
</ItemContainer>
),
value: user.id,
}
}
function getSelectedOptionsByUserId(
value: string[],
userMap: Map<string, SerializedUser>
): FormSelectOption[] {
return value.reduce<FormSelectOption[]>((options, userId) => {
const user = userMap.get(userId)
if (user == null) {
console.warn(`User Id ${userId} does not exist in page props`)
return options
}
options.push(getOptionByUser(user))
return options
}, [])
}
``` | /content/code_sandbox/src/mobile/components/organisms/modals/organisms/DocContextMenu/DocAssigneeSelect.tsx | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 1,700 |
```xml
import * as vscode from 'vscode';
import { DebugConfigurationProvider, DebugConfigOptions } from '../DebugConfigurationProvider';
import { JestExtOutput } from '../JestExt/output-terminal';
import { WorkspaceManager } from '../workspace-manager';
export interface WizardContext {
debugConfigProvider: DebugConfigurationProvider;
wsManager: WorkspaceManager;
vscodeContext: vscode.ExtensionContext;
workspace?: vscode.WorkspaceFolder;
message: JestExtOutput['write'];
verbose?: boolean;
}
export type WizardStatus = 'success' | 'error' | 'abort' | 'exit' | undefined;
export type WizardAction<T> = () => Promise<T>;
interface ActionableComp<T> {
id: number;
action?: WizardAction<T>;
}
export type ActionableMenuItem<T = WizardStatus> = vscode.QuickPickItem & ActionableComp<T>;
export type ActionableButton<T = WizardStatus> = vscode.QuickInputButton & ActionableComp<T>;
export type ActionableMessageItem<T> = vscode.MessageItem & ActionableComp<T>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isActionableButton = (arg: any): arg is ActionableButton<unknown> =>
arg && arg.iconPath && typeof arg.action === 'function';
export type ActionMessageType = 'info' | 'warning' | 'error';
export type AllowBackButton = { enableBackButton?: boolean };
export type Verbose = { verbose?: boolean };
// actionable menu
export type ActionMenuInput<T> = ActionableMenuItem<T> | ActionableButton<T> | undefined;
export type ActionableMenuResult<T = WizardStatus> = T | undefined;
export interface ActionMenuOptions<T = WizardStatus> extends AllowBackButton, Verbose {
title?: string;
placeholder?: string;
value?: string;
rightButtons?: ActionableButton<T>[];
selectItemIdx?: number;
// if true, treat action item/button without action as no-op; otherwise exit with "undefined"
allowNoAction?: boolean;
}
// actionable input box
export type ActionInputResult<T> = T | string | undefined;
export type ActionInput<T> = ActionInputResult<T> | ActionableButton<T> | undefined;
export interface ActionInputBoxOptions<T> extends AllowBackButton, Verbose {
title?: string;
prompt?: string;
value?: string;
rightButtons?: ActionableButton<T>[];
}
export type SetupTask = (context: WizardContext) => Promise<WizardStatus>;
// settings
export interface WizardSettings extends DebugConfigOptions {
absoluteRootPath?: string;
configurations?: vscode.DebugConfiguration[];
}
export interface ConfigEntry {
name: string;
value: unknown;
}
export const WIZARD_HELP_URL =
'path_to_url
``` | /content/code_sandbox/src/setup-wizard/types.ts | xml | 2016-10-09T13:06:02 | 2024-08-13T18:32:04 | vscode-jest | jest-community/vscode-jest | 2,819 | 583 |
```xml
import { Choice } from './choice';
import { Group } from './group';
import { Item } from './item';
export interface State {
choices: Choice[];
groups: Group[];
items: Item[];
loading: boolean;
}
//# sourceMappingURL=state.d.ts.map
``` | /content/code_sandbox/public/types/src/scripts/interfaces/state.d.ts | xml | 2016-03-15T14:02:08 | 2024-08-15T07:08:50 | Choices | Choices-js/Choices | 6,092 | 57 |
```xml
export default function Layout({
children,
slot,
}: {
children: React.ReactNode
slot: React.ReactNode
}) {
return (
<html>
<body>
{children}
{slot}
</body>
</html>
)
}
``` | /content/code_sandbox/test/e2e/app-dir/parallel-routes-root-slot/app/layout.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 58 |
```xml
// Please leave 'en' where it is, as it's our fallback language in case no translation can be found
export const SupportedTranslationLocales: string[] = [
"en",
"af",
"ar",
"az",
"be",
"bg",
"bn",
"bs",
"ca",
"cs",
"cy",
"da",
"de",
"el",
"en-GB",
"en-IN",
"eo",
"es",
"et",
"eu",
"fa",
"fi",
"fil",
"fr",
"gl",
"he",
"hi",
"hr",
"hu",
"id",
"it",
"ja",
"ka",
"km",
"kn",
"ko",
"lv",
"ml",
"mr",
"my",
"nb",
"ne",
"nl",
"nn",
"or",
"pl",
"pt-PT",
"pt-BR",
"ro",
"ru",
"si",
"sk",
"sl",
"sr",
"sv",
"te",
"th",
"tr",
"uk",
"vi",
"zh-CN",
"zh-TW",
];
``` | /content/code_sandbox/apps/web/src/translation-constants.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 295 |
```xml
import type { Logger } from '@apollo/utils.logger';
import type { GraphQLSchema } from 'graphql';
import type {
GatewayExecutor,
GatewayInterface,
GatewayUnsubscriber,
} from '@apollo/server-gateway-interface';
import type { SchemaDerivedData } from '../ApolloServer.js';
import type {
ApolloConfig,
GraphQLSchemaContext,
} from '../externalTypes/index.js';
type SchemaDerivedDataProvider = (
apiSchema: GraphQLSchema,
) => SchemaDerivedData;
/**
* An async-safe class for tracking changes in schemas and schema-derived data.
*
* Specifically, as long as start() is called (and completes) before stop() is
* called, any set of executions of public methods is linearizable.
*
* Note that linearizability in Javascript is trivial if all public methods are
* non-async, but increasingly difficult to guarantee if public methods become
* async. Accordingly, if you believe a public method should be async, think
* carefully on whether it's worth the mental overhead. (E.g. if you wished that
* a callback was async, consider instead resolving a Promise in a non-async
* callback and having your async code wait on the Promise in setTimeout().)
*/
export class SchemaManager {
private readonly logger: Logger;
private readonly schemaDerivedDataProvider: SchemaDerivedDataProvider;
private readonly onSchemaLoadOrUpdateListeners = new Set<
(schemaContext: GraphQLSchemaContext) => void
>();
private isStopped = false;
private schemaDerivedData?: SchemaDerivedData;
private schemaContext?: GraphQLSchemaContext;
// For state that's specific to the mode of operation.
private readonly modeSpecificState:
| {
readonly mode: 'gateway';
readonly gateway: GatewayInterface;
readonly apolloConfig: ApolloConfig;
unsubscribeFromGateway?: GatewayUnsubscriber;
}
| {
readonly mode: 'schema';
readonly apiSchema: GraphQLSchema;
readonly schemaDerivedData: SchemaDerivedData;
};
constructor(
options: (
| { gateway: GatewayInterface; apolloConfig: ApolloConfig }
| { apiSchema: GraphQLSchema }
) & {
logger: Logger;
schemaDerivedDataProvider: SchemaDerivedDataProvider;
},
) {
this.logger = options.logger;
this.schemaDerivedDataProvider = options.schemaDerivedDataProvider;
if ('gateway' in options) {
this.modeSpecificState = {
mode: 'gateway',
gateway: options.gateway,
apolloConfig: options.apolloConfig,
};
} else {
this.modeSpecificState = {
mode: 'schema',
apiSchema: options.apiSchema,
// The caller of the constructor expects us to fail early if the schema
// given is invalid/has errors, so we call the provider here. We also
// pass the result to start(), as the provider can be expensive to call.
schemaDerivedData: options.schemaDerivedDataProvider(options.apiSchema),
};
}
}
/**
* Calling start() will:
* - Start gateway schema fetching (if a gateway was provided).
* - Initialize schema-derived data.
* - Synchronously notify onSchemaLoadOrUpdate() listeners of schema load, and
* asynchronously notify them of schema updates.
* - If we started a gateway, returns the gateway's executor; otherwise null.
*/
public async start(): Promise<GatewayExecutor | null> {
if (this.modeSpecificState.mode === 'gateway') {
const gateway = this.modeSpecificState.gateway;
if (gateway.onSchemaLoadOrUpdate) {
// Use onSchemaLoadOrUpdate, as it reports the core supergraph SDL and
// always reports the initial schema load.
this.modeSpecificState.unsubscribeFromGateway =
gateway.onSchemaLoadOrUpdate((schemaContext) => {
this.processSchemaLoadOrUpdateEvent(schemaContext);
});
} else {
throw new Error(
"Unexpectedly couldn't find onSchemaLoadOrUpdate on gateway",
);
}
const config = await this.modeSpecificState.gateway.load({
apollo: this.modeSpecificState.apolloConfig,
});
return config.executor;
} else {
this.processSchemaLoadOrUpdateEvent(
{
apiSchema: this.modeSpecificState.apiSchema,
},
this.modeSpecificState.schemaDerivedData,
);
return null;
}
}
/**
* Registers a listener for schema load/update events. Note that the latest
* event is buffered, i.e.
* - If registered before start(), this method will throw. (We have no need
* for registration before start(), but this is easy enough to change.)
* - If registered after start() but before stop(), the callback will be first
* called in this method (for whatever the current schema is), and then
* later for updates.
* - If registered after stop(), the callback will never be called.
*
* For gateways, a core supergraph SDL will be provided to the callback.
*
* @param callback The listener to execute on schema load/updates.
*/
public onSchemaLoadOrUpdate(
callback: (schemaContext: GraphQLSchemaContext) => void,
): GatewayUnsubscriber {
if (!this.schemaContext) {
throw new Error('You must call start() before onSchemaLoadOrUpdate()');
}
if (!this.isStopped) {
try {
callback(this.schemaContext);
} catch (e) {
// Note that onSchemaLoadOrUpdate() is currently only called from
// ApolloServer._start(), so we throw here to alert the user early
// that their callback is failing.
throw new Error(
`An error was thrown from an 'onSchemaLoadOrUpdate' listener: ${
(e as Error).message
}`,
);
}
}
this.onSchemaLoadOrUpdateListeners.add(callback);
return () => {
this.onSchemaLoadOrUpdateListeners.delete(callback);
};
}
/**
* Get the schema-derived state for the current schema. This throws if called
* before start() is called.
*/
public getSchemaDerivedData(): SchemaDerivedData {
if (!this.schemaDerivedData) {
throw new Error('You must call start() before getSchemaDerivedData()');
}
return this.schemaDerivedData;
}
/**
* Calling stop() will:
* - Stop gateway schema fetching (if a gateway was provided).
* - Note that this specific step may not succeed if gateway is old.
* - Stop updating schema-derived data.
* - Stop notifying onSchemaLoadOrUpdate() listeners.
*/
public async stop(): Promise<void> {
this.isStopped = true;
if (this.modeSpecificState.mode === 'gateway') {
this.modeSpecificState.unsubscribeFromGateway?.();
await this.modeSpecificState.gateway.stop?.();
}
}
private processSchemaLoadOrUpdateEvent(
schemaContext: GraphQLSchemaContext,
schemaDerivedData?: SchemaDerivedData,
): void {
if (!this.isStopped) {
this.schemaDerivedData =
schemaDerivedData ??
this.schemaDerivedDataProvider(schemaContext.apiSchema);
this.schemaContext = schemaContext;
this.onSchemaLoadOrUpdateListeners.forEach((listener) => {
try {
listener(schemaContext);
} catch (e) {
this.logger.error(
"An error was thrown from an 'onSchemaLoadOrUpdate' listener",
);
this.logger.error(e);
}
});
}
}
}
``` | /content/code_sandbox/packages/server/src/utils/schemaManager.ts | xml | 2016-04-21T09:26:01 | 2024-08-16T19:32:15 | apollo-server | apollographql/apollo-server | 13,742 | 1,582 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="path_to_url" xmlns:xsi="path_to_url" xmlns:xsd="path_to_url" xmlns:activiti="path_to_url" xmlns:bpmndi="path_to_url" xmlns:omgdc="path_to_url" xmlns:omgdi="path_to_url" xmlns:bpmn2="path_to_url" xmlns:dc="path_to_url" xmlns:di="path_to_url" typeLanguage="path_to_url" expressionLanguage="path_to_url" targetNamespace="path_to_url" xsi:schemaLocation="path_to_url BPMN20.xsd" id="Definitions_1">
<process id="terminateEndEventExample" name="Default Process" isExecutable="true">
<startEvent id="start"></startEvent>
<parallelGateway id="ParallelGateway_1"></parallelGateway>
<sequenceFlow id="SequenceFlow_2" sourceRef="start" targetRef="ParallelGateway_1"></sequenceFlow>
<userTask id="preNormalEnd" name="check before normal end"></userTask>
<sequenceFlow id="SequenceFlow_4" sourceRef="ParallelGateway_1" targetRef="preNormalEnd"></sequenceFlow>
<subProcess id="SubProcess_1" name="SubProcess">
<multiInstanceLoopCharacteristics isSequential="false">
<loopCardinality>5</loopCardinality>
</multiInstanceLoopCharacteristics>
<serviceTask id="checkTerminate" name="Service Task" activiti:class="org.activiti.engine.test.bpmn.event.end.TerminateEndEventTest$CountDelegate"></serviceTask>
<sequenceFlow id="SequenceFlow_5" sourceRef="checkTerminate" targetRef="ExclusiveGateway_1"></sequenceFlow>
<endEvent id="EndEvent_5">
<terminateEventDefinition />
</endEvent>
<startEvent id="StartEvent_1"></startEvent>
<sequenceFlow id="SequenceFlow_3" sourceRef="StartEvent_1" targetRef="checkTerminate"></sequenceFlow>
<userTask id="task" name="User Task"></userTask>
<sequenceFlow id="SequenceFlow_12" sourceRef="task" targetRef="EndEvent_5"></sequenceFlow>
<exclusiveGateway id="ExclusiveGateway_1"></exclusiveGateway>
<sequenceFlow id="SequenceFlow_11" sourceRef="ExclusiveGateway_1" targetRef="task">
<conditionExpression xsi:type="tFormalExpression"><![CDATA[${!terminate}]]></conditionExpression>
</sequenceFlow>
<sequenceFlow id="SequenceFlow_8" sourceRef="ExclusiveGateway_1" targetRef="ParallelGateway_2">
<conditionExpression xsi:type="tFormalExpression"><![CDATA[${terminate}]]></conditionExpression>
</sequenceFlow>
<endEvent id="EndEvent_1">
<terminateEventDefinition activiti:terminateAll="true"></terminateEventDefinition>
</endEvent>
<userTask id="UserTask_1" name="User Task"></userTask>
<endEvent id="EndEvent_2"></endEvent>
<sequenceFlow id="SequenceFlow_14" sourceRef="UserTask_1" targetRef="EndEvent_2"></sequenceFlow>
<parallelGateway id="ParallelGateway_2"></parallelGateway>
<sequenceFlow id="SequenceFlow_10" sourceRef="ParallelGateway_2" targetRef="UserTask_1"></sequenceFlow>
<sequenceFlow id="SequenceFlow_15" sourceRef="ParallelGateway_2" targetRef="EndEvent_1"></sequenceFlow>
</subProcess>
<sequenceFlow id="SequenceFlow_6" sourceRef="ParallelGateway_1" targetRef="SubProcess_1"></sequenceFlow>
<endEvent id="EndEvent_3"></endEvent>
<sequenceFlow id="SequenceFlow_7" sourceRef="SubProcess_1" targetRef="EndEvent_3"></sequenceFlow>
<endEvent id="EndEvent_4"></endEvent>
<sequenceFlow id="SequenceFlow_1" sourceRef="preNormalEnd" targetRef="EndEvent_4"></sequenceFlow>
</process>
<bpmndi:BPMNDiagram id="BPMNDiagram_terminateEndEventExample">
<bpmndi:BPMNPlane bpmnElement="terminateEndEventExample" id="BPMNPlane_terminateEndEventExample">
<bpmndi:BPMNShape bpmnElement="start" id="BPMNShape_start">
<omgdc:Bounds height="36.0" width="36.0" x="89.0" y="448.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="ParallelGateway_1" id="BPMNShape_ParallelGateway_1">
<omgdc:Bounds height="50.0" width="50.0" x="175.0" y="441.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="preNormalEnd" id="BPMNShape_preNormalEnd">
<omgdc:Bounds height="50.0" width="110.0" x="254.0" y="518.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="SubProcess_1" id="BPMNShape_SubProcess_1">
<omgdc:Bounds height="314.0" width="660.0" x="260.0" y="170.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="checkTerminate" id="BPMNShape_checkTerminate">
<omgdc:Bounds height="50.0" width="110.0" x="378.0" y="194.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="EndEvent_5" id="BPMNShape_EndEvent_5">
<omgdc:Bounds height="36.0" width="36.0" x="800.0" y="201.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="StartEvent_1" id="BPMNShape_StartEvent_1">
<omgdc:Bounds height="36.0" width="36.0" x="292.0" y="201.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="task" id="BPMNShape_task">
<omgdc:Bounds height="50.0" width="110.0" x="640.0" y="194.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="ExclusiveGateway_1" id="BPMNShape_ExclusiveGateway_1">
<omgdc:Bounds height="50.0" width="50.0" x="540.0" y="194.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="EndEvent_1" id="BPMNShape_EndEvent_1">
<omgdc:Bounds height="36.0" width="36.0" x="839.0" y="310.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="UserTask_1" id="BPMNShape_UserTask_1">
<omgdc:Bounds height="50.0" width="110.0" x="691.0" y="393.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="EndEvent_2" id="BPMNShape_EndEvent_2">
<omgdc:Bounds height="36.0" width="36.0" x="851.0" y="400.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="ParallelGateway_2" id="BPMNShape_ParallelGateway_2">
<omgdc:Bounds height="50.0" width="50.0" x="591.0" y="345.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="EndEvent_3" id="BPMNShape_EndEvent_3">
<omgdc:Bounds height="36.0" width="36.0" x="1009.0" y="328.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="EndEvent_4" id="BPMNShape_EndEvent_4">
<omgdc:Bounds height="36.0" width="36.0" x="414.0" y="525.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_2" id="BPMNEdge_SequenceFlow_2">
<omgdi:waypoint x="125.0" y="466.0"></omgdi:waypoint>
<omgdi:waypoint x="175.0" y="466.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_4" id="BPMNEdge_SequenceFlow_4">
<omgdi:waypoint x="200.0" y="491.0"></omgdi:waypoint>
<omgdi:waypoint x="200.0" y="542.0"></omgdi:waypoint>
<omgdi:waypoint x="254.0" y="543.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_5" id="BPMNEdge_SequenceFlow_5">
<omgdi:waypoint x="488.0" y="219.0"></omgdi:waypoint>
<omgdi:waypoint x="540.0" y="219.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_3" id="BPMNEdge_SequenceFlow_3">
<omgdi:waypoint x="328.0" y="219.0"></omgdi:waypoint>
<omgdi:waypoint x="378.0" y="219.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_12" id="BPMNEdge_SequenceFlow_12">
<omgdi:waypoint x="750.0" y="219.0"></omgdi:waypoint>
<omgdi:waypoint x="800.0" y="219.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_11" id="BPMNEdge_SequenceFlow_11">
<omgdi:waypoint x="590.0" y="219.0"></omgdi:waypoint>
<omgdi:waypoint x="640.0" y="219.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_8" id="BPMNEdge_SequenceFlow_8">
<omgdi:waypoint x="565.0" y="244.0"></omgdi:waypoint>
<omgdi:waypoint x="565.0" y="370.0"></omgdi:waypoint>
<omgdi:waypoint x="591.0" y="370.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_14" id="BPMNEdge_SequenceFlow_14">
<omgdi:waypoint x="801.0" y="418.0"></omgdi:waypoint>
<omgdi:waypoint x="851.0" y="418.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_10" id="BPMNEdge_SequenceFlow_10">
<omgdi:waypoint x="616.0" y="395.0"></omgdi:waypoint>
<omgdi:waypoint x="615.0" y="419.0"></omgdi:waypoint>
<omgdi:waypoint x="665.0" y="419.0"></omgdi:waypoint>
<omgdi:waypoint x="691.0" y="418.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_15" id="BPMNEdge_SequenceFlow_15">
<omgdi:waypoint x="616.0" y="345.0"></omgdi:waypoint>
<omgdi:waypoint x="619.0" y="328.0"></omgdi:waypoint>
<omgdi:waypoint x="839.0" y="328.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_6" id="BPMNEdge_SequenceFlow_6">
<omgdi:waypoint x="200.0" y="441.0"></omgdi:waypoint>
<omgdi:waypoint x="200.0" y="345.0"></omgdi:waypoint>
<omgdi:waypoint x="260.0" y="327.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_7" id="BPMNEdge_SequenceFlow_7">
<omgdi:waypoint x="920.0" y="327.0"></omgdi:waypoint>
<omgdi:waypoint x="1009.0" y="346.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="SequenceFlow_1" id="BPMNEdge_SequenceFlow_1">
<omgdi:waypoint x="364.0" y="543.0"></omgdi:waypoint>
<omgdi:waypoint x="414.0" y="543.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>
``` | /content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/engine/test/bpmn/event/end/TerminateEndEventTest.testTerminateInSubProcessConcurrentMultiInstanceTerminateAll.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 3,553 |
```xml
import chalk from 'chalk';
import { Tree, ProjectConfiguration, logger } from '@nx/devkit';
interface Options<T extends ProjectConfiguration> {
title: string;
projects: Map<string, T>;
shouldProcessPackage: (tree: Tree, project: ProjectConfiguration) => boolean;
isMigratedCheck: (tree: Tree, project: ProjectConfiguration) => boolean;
projectInfoFormat?: (data: StatData<T>) => string;
}
type StatData<T extends ProjectConfiguration> = T & { projectName: string };
export function printStats<T extends ProjectConfiguration>(tree: Tree, options: Options<T>) {
const { isMigratedCheck, projectInfoFormat, shouldProcessPackage, title, projects } = {
projectInfoFormat: defaultProjectInfoFormat,
...options,
};
const stats = {
migrated: { application: [] as Array<StatData<T>>, library: [] as Array<StatData<T>> },
notMigrated: { application: [] as Array<StatData<T>>, library: [] as Array<StatData<T>> },
};
projects.forEach((project, projectName) => {
if (!project.projectType) {
throw new Error(`${projectName}: is missing "projectType" categorization in project.json!`);
}
if (!shouldProcessPackage(tree, project)) {
return;
}
if (isMigratedCheck(tree, project)) {
stats.migrated[project.projectType].push({ projectName, ...project });
return;
}
stats.notMigrated[project.projectType].push({ projectName, ...project });
});
const heading = printTitle(`${title} migration stats:`);
logger.info(heading);
logger.info(chalk.reset.inverse.bold.green(` Migrated: `));
logger.info(`Libs: (${stats.migrated.library.length})`);
logger.info(stats.migrated.library.map(projectInfoFormat).join('\n'));
logger.info(`Apps (${stats.migrated.application.length}):`);
logger.info(stats.migrated.application.map(projectInfoFormat).join('\n'));
logger.info(chalk.reset.hex('#FFF').bgHex('#FF8800').bold(` Not Migrated: `));
logger.info(`Libs (${stats.notMigrated.library.length}):`);
logger.info(stats.notMigrated.library.map(projectInfoFormat).join('\n'));
logger.info(`Apps (${stats.notMigrated.application.length}):`);
logger.info(stats.notMigrated.application.map(projectInfoFormat).join('\n'));
return tree;
}
const printTitle = (title: string) => `${chalk.cyan('>')} ${chalk.inverse(chalk.bold(chalk.cyan(` ${title} `)))}\n`;
function defaultProjectInfoFormat<T extends ProjectConfiguration>(data: StatData<T>) {
return `- ${data.projectName}`;
}
``` | /content/code_sandbox/tools/workspace-plugin/src/generators/print-stats.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 581 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webview"></WebView>
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/fragment_top.xml | xml | 2016-03-24T06:20:39 | 2024-08-15T11:37:10 | remusic | aa112901/remusic | 6,266 | 86 |
```xml
import React from 'react';
import { Rubik_Puddles } from 'next/font/google';
import localFont from 'next/font/local';
const rubik = Rubik_Puddles({
subsets: ['latin'],
variable: '--font-latin-rubik',
weight: '400',
});
export const localRubikStorm = localFont({
src: '/fonts/RubikStorm-Regular.ttf',
variable: '--font-rubik-storm',
});
type FontProps = {
variant: 'className' | 'style' | 'variable';
};
export default function Font({ variant }: FontProps) {
switch (variant) {
case 'className':
return (
<div>
<h1 className={rubik.className}>Google Rubik Puddles</h1>
<h1 className={localRubikStorm.className}>Google Local Rubik Storm</h1>
</div>
);
case 'style':
return (
<div>
<h1 style={rubik.style}>Google Rubik Puddles</h1>
<h1 style={localRubikStorm.style}>Google Local Rubik Storm</h1>
</div>
);
case 'variable':
return (
<div>
<div className={rubik.variable}>
<h1
style={{
fontFamily: 'var(--font-latin-rubik)',
fontStyle: rubik.style.fontStyle,
fontWeight: rubik.style.fontWeight,
}}
>
Google Rubik Puddles
</h1>
</div>
<div className={localRubikStorm.variable}>
<h1
style={{
fontFamily: 'var(--font-rubik-storm)',
fontStyle: localRubikStorm.style.fontStyle,
fontWeight: localRubikStorm.style.fontWeight,
}}
>
Google Local Rubik Storm
</h1>
</div>
</div>
);
default:
return null;
}
}
``` | /content/code_sandbox/code/frameworks/experimental-nextjs-vite/template/stories/Font.tsx | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 424 |
```xml
export interface Subscriber {
/**
* Subscribe to incoming events.
*
* @param {Function} callback
* @return {void}
*/
subscribe(callback: Function): Promise<any>;
/**
* Unsubscribe from incoming events
*
* @return {Promise}
*/
unsubscribe(): Promise<any>;
}
``` | /content/code_sandbox/src/subscribers/subscriber.ts | xml | 2016-05-14T23:52:18 | 2024-08-10T15:38:49 | laravel-echo-server | tlaverdure/laravel-echo-server | 2,645 | 72 |
```xml
import clsx from 'clsx';
import { createContext, PropsWithChildren, Ref, useContext } from 'react';
const Context = createContext<null | boolean>(null);
Context.displayName = 'WidgetContext';
export function useWidgetContext() {
const context = useContext(Context);
if (context == null) {
throw new Error('Should be inside a Widget component');
}
}
export function Widget({
children,
className,
mRef,
id,
'aria-label': ariaLabel,
}: PropsWithChildren<{
className?: string;
mRef?: Ref<HTMLDivElement>;
id?: string;
'aria-label'?: string;
}>) {
return (
<Context.Provider value>
<section
id={id}
className={clsx('widget', className)}
ref={mRef}
aria-label={ariaLabel}
>
{children}
</section>
</Context.Provider>
);
}
``` | /content/code_sandbox/app/react/components/Widget/Widget.tsx | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 198 |
```xml
import fs from 'fs-extra';
// @ts-ignore
import Jimp from 'jimp-compact';
import path from 'path';
import stream from 'stream';
import type { ReadableStream } from 'stream/web';
import tempDir from 'temp-dir';
import uniqueString from 'unique-string';
import util from 'util';
// cache downloaded images into memory
const cacheDownloadedKeys: Record<string, string> = {};
function stripQueryParams(url: string): string {
return url.split('?')[0].split('#')[0];
}
function temporaryDirectory() {
const directory = path.join(tempDir, uniqueString());
fs.mkdirSync(directory);
return directory;
}
export async function downloadOrUseCachedImage(url: string): Promise<string> {
if (url in cacheDownloadedKeys) {
return cacheDownloadedKeys[url];
}
if (url.startsWith('http')) {
cacheDownloadedKeys[url] = await downloadImage(url);
} else {
cacheDownloadedKeys[url] = url;
}
return cacheDownloadedKeys[url];
}
export async function downloadImage(url: string): Promise<string> {
const outputPath = temporaryDirectory();
const response = await fetch(url);
if (!response.ok) {
throw new Error(`It was not possible to download image from '${url}'`);
}
if (!response.body) {
throw new Error(`No response received from '${url}'`);
}
// Download to local file
const streamPipeline = util.promisify(stream.pipeline);
const localPath = path.join(outputPath, path.basename(stripQueryParams(url)));
// Type casting is required, see: path_to_url
const readableBody = stream.Readable.fromWeb(response.body as ReadableStream<Uint8Array>);
await streamPipeline(readableBody, fs.createWriteStream(localPath));
// If an image URL doesn't have a name, get the mime type and move the file.
const img = await Jimp.read(localPath);
const mime = img.getMIME().split('/').pop()!;
if (!localPath.endsWith(mime)) {
const newPath = path.join(outputPath, `image.${mime}`);
await fs.move(localPath, newPath);
return newPath;
}
return localPath;
}
``` | /content/code_sandbox/packages/@expo/image-utils/src/Download.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 476 |
```xml
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import { getTimezoneOffset } from "date-fns-tz";
import type { Timezone, TimezoneWithoutOffset } from "./timezoneTypes";
/**
* Augment hard-coded timezone information stored in this package with its current offset relative to UTC,
* adjusted for daylight saving using the current date.
*
* @see path_to_url#gettimezoneoffset
*/
export function lookupTimezoneOffset(tz: TimezoneWithoutOffset, date?: Date): Timezone {
const offsetInMs = getTimezoneOffset(tz.ianaCode, date);
if (isNaN(offsetInMs)) {
throw new Error(`Unable to lookup offset for invalid timezone '${tz.ianaCode}'`);
}
const isPositiveOffset = offsetInMs >= 0;
const offsetInMinutes = Math.abs(offsetInMs) / 1000 / 60;
const offsetHours = Math.trunc(offsetInMinutes / 60)
.toString()
.padStart(2, "0");
const offsetMinutes = (offsetInMinutes % 60).toString().padEnd(2, "0");
return {
...tz,
offset: `${isPositiveOffset ? "+" : "-"}${offsetHours}:${offsetMinutes}`,
};
}
``` | /content/code_sandbox/packages/datetime/src/common/timezoneOffsetUtils.ts | xml | 2016-10-25T21:17:50 | 2024-08-16T15:14:48 | blueprint | palantir/blueprint | 20,593 | 294 |
```xml
// Type definitions for iview 3.3.1
// Project: path_to_url
// Definitions by: yangdan
// Definitions: path_to_url
import Vue, { VNode } from 'vue';
export declare class Upload extends Vue {
/**
*
*/
action?: string;
/**
*
* @default {}
*/
headers?: object;
/**
*
* @default false
*/
multiple?: boolean;
/**
*
* @default false
*/
paste?: boolean;
/**
*
* @default false
*/
disabled?: boolean;
/**
*
*/
data?: object;
/**
*
* @default file
*/
name?: string;
/**
* cookie
* @default false
*/
'with-credentials'?: boolean;
/**
*
* @default true
*/
'show-upload-list'?: boolean;
/**
* selectdrag
* @default select
*/
type?: 'select' | 'drag';
/**
*
*/
accept?: string;
/**
* accept
* format
* accept input accept
*
* @default []
*/
format?: string[];
/**
* kb
*/
'max-size'?: number;
/**
* false Promise
*/
'before-upload'?: Function;
/**
* event, file, fileList
*/
'on-progress'?: Function;
/**
* response, file, fileList
*/
'on-success'?: Function;
/**
* error, file, fileList
*/
'on-error'?: Function;
/**
* file file.response
*/
'on-preview'?: Function;
/**
* file, fileList
*/
'on-remove'?: Function;
/**
* file, fileList
*/
'on-format-error'?: Function;
/**
* file, fileList
*/
'on-exceeded-size'?: Function;
/**
*
* [
* {
* name?: 'img1.jpg',
* url?: 'path_to_url
* },
* {
* name?: 'img2.jpg',
* url?: 'path_to_url
* }
* ]
*/
'default-file-list'?: string[];
/**
*
*/
'clearFiles'(): void;
/**
* slot
*/
$slots: {
/**
*
*/
'': VNode[];
/**
*
*/
tip: VNode[];
};
}
``` | /content/code_sandbox/types/upload.d.ts | xml | 2016-07-28T01:52:59 | 2024-08-16T10:15:08 | iview | iview/iview | 23,980 | 598 |
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"path_to_url" >
<!--
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
-->
<mapper namespace="org.apache.guacamole.auth.jdbc.user.UserRecordMapper" >
<!-- Result mapper for system permissions -->
<resultMap id="UserRecordResultMap" type="org.apache.guacamole.auth.jdbc.base.ActivityRecordModel">
<id column="history_id" property="recordID" jdbcType="INTEGER"/>
<result column="remote_host" property="remoteHost" jdbcType="VARCHAR"/>
<result column="user_id" property="userID" jdbcType="INTEGER"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="start_date" property="startDate" jdbcType="TIMESTAMP"/>
<result column="end_date" property="endDate" jdbcType="TIMESTAMP"/>
</resultMap>
<!-- Insert the given user record -->
<insert id="insert" useGeneratedKeys="true" keyProperty="record.recordID"
parameterType="org.apache.guacamole.auth.jdbc.base.ActivityRecordModel">
INSERT INTO [guacamole_user_history] (
remote_host,
user_id,
username,
start_date,
end_date
)
VALUES (
#{record.remoteHost,jdbcType=VARCHAR},
(SELECT user_id FROM [guacamole_user]
JOIN [guacamole_entity] ON [guacamole_user].entity_id = [guacamole_entity].entity_id
WHERE
[guacamole_entity].name = #{record.username,jdbcType=VARCHAR}
AND [guacamole_entity].type = 'USER'),
#{record.username,jdbcType=VARCHAR},
#{record.startDate,jdbcType=TIMESTAMP},
#{record.endDate,jdbcType=TIMESTAMP}
)
</insert>
<!-- Update the given user record, assigning an end date -->
<update id="updateEndDate" parameterType="org.apache.guacamole.auth.jdbc.base.ActivityRecordModel">
UPDATE [guacamole_user_history]
SET end_date = #{record.endDate,jdbcType=TIMESTAMP}
WHERE history_id = #{record.recordID,jdbcType=INTEGER}
</update>
<!-- Search for specific user records -->
<select id="search" resultMap="UserRecordResultMap">
SELECT TOP (#{limit,jdbcType=INTEGER})
[guacamole_user_history].history_id,
[guacamole_user_history].remote_host,
[guacamole_user_history].user_id,
[guacamole_user_history].username,
[guacamole_user_history].start_date,
[guacamole_user_history].end_date
FROM [guacamole_user_history]
<!-- Search terms -->
<where>
<if test="identifier != null">
[guacamole_user_history].username = #{identifier,jdbcType=VARCHAR}
</if>
<foreach collection="terms" item="term" open=" AND " separator=" AND ">
(
[guacamole_user_history].user_id IN (
SELECT user_id
FROM [guacamole_user]
JOIN [guacamole_entity] ON [guacamole_user].entity_id = [guacamole_entity].entity_id
WHERE
CHARINDEX(#{term.term,jdbcType=VARCHAR}, [guacamole_entity].name) > 0
AND [guacamole_entity].type = 'USER'),
)
<if test="term.startDate != null and term.endDate != null">
OR start_date BETWEEN #{term.startDate,jdbcType=TIMESTAMP} AND #{term.endDate,jdbcType=TIMESTAMP}
</if>
)
</foreach>
</where>
<!-- Bind sort property enum values for sake of readability -->
<bind name="START_DATE" value="@org.apache.guacamole.net.auth.ActivityRecordSet$SortableProperty@START_DATE"/>
<!-- Sort predicates -->
<foreach collection="sortPredicates" item="sortPredicate"
open="ORDER BY " separator=", ">
<choose>
<when test="sortPredicate.property == START_DATE">[guacamole_user_history].start_date</when>
<otherwise>1</otherwise>
</choose>
<if test="sortPredicate.descending">DESC</if>
</foreach>
</select>
<!-- Search for specific user records -->
<select id="searchReadable" resultMap="UserRecordResultMap">
SELECT TOP (#{limit,jdbcType=INTEGER})
[guacamole_user_history].history_id,
[guacamole_user_history].remote_host,
[guacamole_user_history].user_id,
[guacamole_user_history].username,
[guacamole_user_history].start_date,
[guacamole_user_history].end_date
FROM [guacamole_user_history]
<!-- Search terms -->
<where>
<!-- Restrict to readable users -->
[guacamole_connection_history].user_id IN (
<include refid="org.apache.guacamole.auth.jdbc.user.UserMapper.getReadableIDs">
<property name="entityID" value="#{user.entityID,jdbcType=INTEGER}"/>
<property name="groups" value="effectiveGroups"/>
</include>
)
<if test="identifier != null">
AND [guacamole_entity].name = #{identifier,jdbcType=VARCHAR}
</if>
<foreach collection="terms" item="term" open=" AND " separator=" AND ">
(
[guacamole_user_history].user_id IN (
SELECT user_id
FROM [guacamole_user]
JOIN [guacamole_entity] ON [guacamole_user].entity_id = [guacamole_entity].entity_id
WHERE
CHARINDEX(#{term.term,jdbcType=VARCHAR}, [guacamole_entity].name) > 0
AND [guacamole_entity].type = 'USER'
)
<if test="term.startDate != null and term.endDate != null">
OR start_date BETWEEN #{term.startDate,jdbcType=TIMESTAMP} AND #{term.endDate,jdbcType=TIMESTAMP}
</if>
)
</foreach>
</where>
<!-- Bind sort property enum values for sake of readability -->
<bind name="START_DATE" value="@org.apache.guacamole.net.auth.ActivityRecordSet$SortableProperty@START_DATE"/>
<!-- Sort predicates -->
<foreach collection="sortPredicates" item="sortPredicate"
open="ORDER BY " separator=", ">
<choose>
<when test="sortPredicate.property == START_DATE">[guacamole_user_history].start_date</when>
<otherwise>1</otherwise>
</choose>
<if test="sortPredicate.descending">DESC</if>
</foreach>
</select>
</mapper>
``` | /content/code_sandbox/extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-sqlserver/src/main/resources/org/apache/guacamole/auth/jdbc/user/UserRecordMapper.xml | xml | 2016-03-22T07:00:06 | 2024-08-16T13:03:48 | guacamole-client | apache/guacamole-client | 1,369 | 1,557 |
```xml
import { Node } from 'slate'
export const input = [
{
text: '',
},
]
export const test = value => {
return Node.isNodeList(value)
}
export const output = true
``` | /content/code_sandbox/packages/slate/test/interfaces/Node/isNodeList/full-text.tsx | xml | 2016-06-18T01:52:42 | 2024-08-16T18:43:42 | slate | ianstormtaylor/slate | 29,492 | 46 |
```xml
import type { CachePolicy } from '@apollo/cache-control-types';
import { newCachePolicy } from '../cachePolicy.js';
import { describe, it, expect, beforeEach } from '@jest/globals';
describe('newCachePolicy', () => {
let cachePolicy: CachePolicy;
beforeEach(() => {
cachePolicy = newCachePolicy();
});
it('starts uncacheable', () => {
expect(cachePolicy.maxAge).toBeUndefined();
expect(cachePolicy.scope).toBeUndefined();
});
it('restricting maxAge positive makes restricted', () => {
cachePolicy.restrict({ maxAge: 10 });
});
it('restricting maxAge 0 makes restricted', () => {
cachePolicy.restrict({ maxAge: 0 });
});
it('restricting scope to private makes restricted', () => {
cachePolicy.restrict({ scope: 'PRIVATE' });
});
it('returns lowest max age value', () => {
cachePolicy.restrict({ maxAge: 10 });
cachePolicy.restrict({ maxAge: 20 });
expect(cachePolicy.maxAge).toBe(10);
});
it('returns lowest max age value in other order', () => {
cachePolicy.restrict({ maxAge: 20 });
cachePolicy.restrict({ maxAge: 10 });
expect(cachePolicy.maxAge).toBe(10);
});
it('maxAge 0 if any cache hint has a maxAge of 0', () => {
cachePolicy.restrict({ maxAge: 120 });
cachePolicy.restrict({ maxAge: 0 });
cachePolicy.restrict({ maxAge: 20 });
expect(cachePolicy.maxAge).toBe(0);
});
it('returns undefined if first cache hint has a maxAge of 0', () => {
cachePolicy.restrict({ maxAge: 0 });
cachePolicy.restrict({ maxAge: 20 });
expect(cachePolicy.maxAge).toBe(0);
});
it('only restricting maxAge keeps scope undefined', () => {
cachePolicy.restrict({ maxAge: 10 });
expect(cachePolicy.scope).toBeUndefined();
});
it('returns PRIVATE scope if any cache hint has PRIVATE scope', () => {
cachePolicy.restrict({
maxAge: 10,
scope: 'PUBLIC',
});
cachePolicy.restrict({
maxAge: 10,
scope: 'PRIVATE',
});
expect(cachePolicy).toHaveProperty('scope', 'PRIVATE');
});
it('policyIfCacheable', () => {
expect(cachePolicy.policyIfCacheable()).toBeNull();
cachePolicy.restrict({ scope: 'PRIVATE' });
expect(cachePolicy.scope).toBe('PRIVATE');
expect(cachePolicy.policyIfCacheable()).toBeNull();
cachePolicy.restrict({ maxAge: 10 });
expect(cachePolicy).toMatchObject({
maxAge: 10,
scope: 'PRIVATE',
});
expect(cachePolicy.policyIfCacheable()).toStrictEqual({
maxAge: 10,
scope: 'PRIVATE',
});
cachePolicy.restrict({ maxAge: 0 });
expect(cachePolicy).toMatchObject({
maxAge: 0,
scope: 'PRIVATE',
});
expect(cachePolicy.policyIfCacheable()).toBeNull();
});
it('replace', () => {
cachePolicy.restrict({ maxAge: 10, scope: 'PRIVATE' });
cachePolicy.replace({ maxAge: 20, scope: 'PUBLIC' });
expect(cachePolicy).toMatchObject({
maxAge: 20,
scope: 'PUBLIC',
});
});
});
``` | /content/code_sandbox/packages/server/src/__tests__/cachePolicy.test.ts | xml | 2016-04-21T09:26:01 | 2024-08-16T19:32:15 | apollo-server | apollographql/apollo-server | 13,742 | 768 |
```xml
<vector xmlns:android="path_to_url"
android:width="16dp"
android:height="16dp"
android:viewportHeight="16"
android:viewportWidth="16">
<group>
<clip-path android:pathData="M0,0h16v16h-16z" />
<path
android:fillColor="#ffffff"
android:pathData="M10.5,5C10.224,5 10,5.224 10,5.5V11.5C10,11.776 10.224,12 10.5,12C10.776,12 11,11.776 11,11.5V5.5C11,5.224 10.776,5 10.5,5Z" />
<path
android:fillColor="#ffffff"
android:pathData="M5,5.5C5,5.224 5.224,5 5.5,5C5.776,5 6,5.224 6,5.5V11.5C6,11.776 5.776,12 5.5,12C5.224,12 5,11.776 5,11.5V5.5Z" />
<path
android:fillColor="#ffffff"
android:pathData="M8,5C7.724,5 7.5,5.224 7.5,5.5V11.5C7.5,11.776 7.724,12 8,12C8.276,12 8.5,11.776 8.5,11.5V5.5C8.5,5.224 8.276,5 8,5Z" />
<path
android:fillColor="#ffffff"
android:fillType="evenOdd"
android:pathData="M5.329,1.724C5.244,1.893 5.071,2 4.882,2H0.5C0.224,2 0,2.224 0,2.5C0,2.776 0.224,3 0.5,3H2.08C2.08,3.051 2.082,3.102 2.086,3.153L2.932,14.153C3.012,15.195 3.881,16 4.926,16H11.074C12.119,16 12.988,15.195 13.068,14.153L13.914,3.153C13.918,3.102 13.92,3.051 13.92,3H15.5C15.776,3 16,2.776 16,2.5C16,2.224 15.776,2 15.5,2H11.118C10.929,2 10.755,1.893 10.671,1.724L10.224,0.829C9.97,0.321 9.45,0 8.882,0H7.118C6.55,0 6.03,0.321 5.776,0.829L5.329,1.724ZM7.118,1C6.929,1 6.756,1.107 6.671,1.276L6.309,2H9.691L9.329,1.276C9.244,1.107 9.071,1 8.882,1H7.118ZM3.08,3H12.92C12.92,3.025 12.919,3.051 12.917,3.077L12.071,14.077C12.031,14.598 11.597,15 11.074,15H4.926C4.403,15 3.969,14.598 3.929,14.077L3.083,3.077C3.081,3.051 3.08,3.025 3.08,3Z" />
</group>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_send_pending_delete.xml | xml | 2016-04-30T16:43:17 | 2024-08-16T19:45:08 | android | bitwarden/android | 6,085 | 925 |
```xml
// Feel free to extend this interface
// depending on your app specific config.
export interface EnvConfig {
API?: string;
ENV?: string;
}
export interface IPlatforms {
WEB: string;
MOBILE_NATIVE: string;
MOBILE_HYBRID: string;
DESKTOP: string;
}
export class Config {
public static PageClass: any;
public static DEBUG = {
LEVEL_1: false, // .info only
LEVEL_2: false, // .warn only
LEVEL_3: false, // .error only
LEVEL_4: false // .log + all the above
};
// supported platforms
public static PLATFORMS: IPlatforms = {
WEB: 'web',
MOBILE_NATIVE: 'mobile_native',
MOBILE_HYBRID: 'mobile_hybrid',
DESKTOP: 'desktop'
};
// current target (defaults to web)
public static PLATFORM_TARGET: string = Config.PLATFORMS.WEB;
// convenient platform checks
public static IS_WEB(): boolean {
return Config.PLATFORM_TARGET === Config.PLATFORMS.WEB;
}
public static IS_MOBILE_NATIVE(): boolean {
return Config.PLATFORM_TARGET === Config.PLATFORMS.MOBILE_NATIVE;
}
public static IS_MOBILE_HYBRID(): boolean {
return Config.PLATFORM_TARGET === Config.PLATFORMS.MOBILE_HYBRID;
}
public static IS_DESKTOP(): boolean {
return Config.PLATFORM_TARGET === Config.PLATFORMS.DESKTOP;
}
public static ENVIRONMENT(): EnvConfig {
try {
return JSON.parse('<%= ENV_CONFIG %>');
} catch (exp) {
return {};
}
}
// supported languages
public static GET_SUPPORTED_LANGUAGES() {
return [
{ code: 'en', title: 'English' },
{ code: 'es', title: 'Spanish' },
{ code: 'fr', title: 'French' },
{ code: 'ru', title: 'Russian' },
{ code: 'bg', title: 'Bulgarian' }
];
}
public static IS_DEBUG_MODE(): boolean {
for (let key in Config.DEBUG) {
if (Config.DEBUG[key]) {
// if any level is on, debug mode is on
return true;
}
}
return false;
}
// reset debug defaults
public static RESET() {
for (let key in Config.DEBUG) {
Config.DEBUG[key] = false;
}
}
}
``` | /content/code_sandbox/src/client/app/modules/core/utils/config.ts | xml | 2016-01-27T07:12:46 | 2024-08-15T11:32:04 | angular-seed-advanced | NathanWalker/angular-seed-advanced | 2,261 | 547 |
```xml
import React from 'react';
import resources from './locales';
import DownloadReport from './containers/DownloadReport';
import ReportModule from '../ReportModule';
export default new ReportModule({
localization: [{ ns: 'ExcelReport', resources }],
reportComponent: [<DownloadReport />],
});
``` | /content/code_sandbox/modules/reports/client-react/excel/index.tsx | xml | 2016-09-08T16:44:45 | 2024-08-16T06:17:16 | apollo-universal-starter-kit | sysgears/apollo-universal-starter-kit | 1,684 | 59 |
```xml
import type { ConfigurationChangeEvent, MessageItem, TreeViewVisibilityChangeEvent } from 'vscode';
import { Disposable, ThemeIcon, TreeItem, TreeItemCollapsibleState, Uri, window } from 'vscode';
import type { OpenWalkthroughCommandArgs } from '../commands/walkthroughs';
import type { LaunchpadViewConfig, ViewFilesLayout } from '../config';
import { Commands, experimentalBadge } from '../constants';
import type { Container } from '../container';
import { AuthenticationRequiredError } from '../errors';
import { GitUri, unknownGitUri } from '../git/gitUri';
import type { FocusCommandArgs } from '../plus/focus/focus';
import type { FocusGroup, FocusItem } from '../plus/focus/focusProvider';
import { focusGroupIconMap, focusGroupLabelMap, groupAndSortFocusItems } from '../plus/focus/focusProvider';
import { createCommand, executeCommand } from '../system/command';
import { configuration } from '../system/configuration';
import { CacheableChildrenViewNode } from './nodes/abstract/cacheableChildrenViewNode';
import type { ClipboardType, ViewNode } from './nodes/abstract/viewNode';
import { ContextValues, getViewNodeId } from './nodes/abstract/viewNode';
import { GroupingNode } from './nodes/groupingNode';
import { getPullRequestChildren, getPullRequestTooltip } from './nodes/pullRequestNode';
import { ViewBase } from './viewBase';
import { registerViewCommand } from './viewCommands';
export class LaunchpadItemNode extends CacheableChildrenViewNode<'launchpad-item', LaunchpadView> {
readonly repoPath: string | undefined;
constructor(
view: LaunchpadView,
protected override readonly parent: ViewNode,
private readonly group: FocusGroup,
public readonly item: FocusItem,
) {
const repoPath = item.openRepository?.repo?.path;
super('launchpad-item', repoPath != null ? GitUri.fromRepoPath(repoPath) : unknownGitUri, view, parent);
this.updateContext({ launchpadGroup: group, launchpadItem: item });
this._uniqueId = getViewNodeId(this.type, this.context);
this.repoPath = repoPath;
}
override get id(): string {
return this._uniqueId;
}
override toClipboard(type?: ClipboardType): string {
const url = this.getUrl();
switch (type) {
case 'markdown':
return `[${this.item.underlyingPullRequest.id}](${url}) ${this.item.underlyingPullRequest.title}`;
default:
return url;
}
}
override getUrl(): string {
return this.item.url ?? this.item.underlyingPullRequest.url;
}
get pullRequest() {
return this.item.type === 'pullrequest' ? this.item.underlyingPullRequest : undefined;
}
async getChildren(): Promise<ViewNode[]> {
if (this.children == null) {
const children = await getPullRequestChildren(
this.view,
this,
this.item.underlyingPullRequest,
this.item.openRepository?.repo ?? this.repoPath,
);
this.children = children;
}
return this.children;
}
getTreeItem(): TreeItem {
const lpi = this.item;
const item = new TreeItem(
lpi.title.length > 60 ? `${lpi.title.substring(0, 60)}...` : lpi.title,
TreeItemCollapsibleState.Collapsed,
);
item.contextValue = ContextValues.LaunchpadItem;
item.description = `\u00a0 ${lpi.repository.owner.login}/${lpi.repository.name}#${lpi.id} \u00a0 ${
lpi.codeSuggestionsCount > 0 ? ` $(gitlens-code-suggestion) ${lpi.codeSuggestionsCount}` : ''
}`;
item.iconPath = lpi.author?.avatarUrl != null ? Uri.parse(lpi.author.avatarUrl) : undefined;
item.command = createCommand<[Omit<FocusCommandArgs, 'command'>]>(Commands.ShowLaunchpad, 'Open in Launchpad', {
source: 'launchpad-view',
state: {
item: { ...this.item, group: this.group },
},
} satisfies Omit<FocusCommandArgs, 'command'>);
if (lpi.type === 'pullrequest') {
item.contextValue += '+pr';
item.tooltip = getPullRequestTooltip(lpi.underlyingPullRequest);
}
return item;
}
}
export class LaunchpadViewNode extends CacheableChildrenViewNode<
'launchpad',
LaunchpadView,
GroupingNode | LaunchpadItemNode
> {
constructor(view: LaunchpadView) {
super('launchpad', unknownGitUri, view);
}
async getChildren(): Promise<(GroupingNode | LaunchpadItemNode)[]> {
if (this.children == null) {
const children: (GroupingNode | LaunchpadItemNode)[] = [];
this.view.message = undefined;
const hasIntegrations = await this.view.container.focus.hasConnectedIntegration();
if (!hasIntegrations) {
return [];
}
try {
const result = await this.view.container.focus.getCategorizedItems();
if (!result.items?.length) {
this.view.message = 'All done! Take a vacation.';
return [];
}
const uiGroups = groupAndSortFocusItems(result.items);
for (const [ui, groupItems] of uiGroups) {
if (!groupItems.length) continue;
const icon = focusGroupIconMap.get(ui)!;
children.push(
new GroupingNode(
this.view,
focusGroupLabelMap.get(ui)!,
groupItems.map(i => new LaunchpadItemNode(this.view, this, ui, i)),
TreeItemCollapsibleState.Collapsed,
undefined,
undefined,
new ThemeIcon(icon.substring(2, icon.length - 1)),
),
);
}
} catch (ex) {
if (!(ex instanceof AuthenticationRequiredError)) throw ex;
}
this.children = children;
}
return this.children;
}
getTreeItem(): TreeItem {
const item = new TreeItem('Launchpad', TreeItemCollapsibleState.Expanded);
return item;
}
}
export class LaunchpadView extends ViewBase<'launchpad', LaunchpadViewNode, LaunchpadViewConfig> {
protected readonly configKey = 'launchpad';
private _disposable: Disposable | undefined;
constructor(container: Container) {
super(container, 'launchpad', 'Launchpad', 'launchpadView');
this.description = experimentalBadge;
}
override dispose() {
this._disposable?.dispose();
super.dispose();
}
protected getRoot() {
return new LaunchpadViewNode(this);
}
protected override onVisibilityChanged(e: TreeViewVisibilityChangeEvent): void {
if (this._disposable == null) {
this._disposable = Disposable.from(
this.container.integrations.onDidChangeConnectionState(() => this.refresh(), this),
this.container.focus.onDidRefresh(() => this.refresh(), this),
);
}
super.onVisibilityChanged(e);
}
override async show(options?: { preserveFocus?: boolean | undefined }): Promise<void> {
if (!configuration.get('views.launchpad.enabled')) {
const confirm: MessageItem = { title: 'Enable' };
const cancel: MessageItem = { title: 'Cancel', isCloseAffordance: true };
const result = await window.showInformationMessage(
'Would you like to try the new experimental Launchpad view?',
{
modal: true,
detail: 'Launchpad organizes your pull requests into actionable groups to help you focus and keep your team unblocked.',
},
confirm,
cancel,
);
if (result !== confirm) return;
await configuration.updateEffective('views.launchpad.enabled', true);
}
return super.show(options);
}
override get canReveal(): boolean {
return false;
}
protected registerCommands(): Disposable[] {
void this.container.viewCommands;
return [
registerViewCommand(
this.getQualifiedCommand('info'),
() =>
executeCommand<OpenWalkthroughCommandArgs>(Commands.OpenWalkthrough, {
step: 'launchpad',
source: 'launchpad-view',
detail: 'info',
}),
this,
),
registerViewCommand(
this.getQualifiedCommand('copy'),
() => executeCommand(Commands.ViewsCopy, this.activeSelection, this.selection),
this,
),
registerViewCommand(
this.getQualifiedCommand('refresh'),
() =>
window.withProgress({ location: { viewId: this.id } }, () =>
this.container.focus.getCategorizedItems({ force: true }),
),
this,
),
registerViewCommand(
this.getQualifiedCommand('setFilesLayoutToAuto'),
() => this.setFilesLayout('auto'),
this,
),
registerViewCommand(
this.getQualifiedCommand('setFilesLayoutToList'),
() => this.setFilesLayout('list'),
this,
),
registerViewCommand(
this.getQualifiedCommand('setFilesLayoutToTree'),
() => this.setFilesLayout('tree'),
this,
),
registerViewCommand(this.getQualifiedCommand('setShowAvatarsOn'), () => this.setShowAvatars(true), this),
registerViewCommand(this.getQualifiedCommand('setShowAvatarsOff'), () => this.setShowAvatars(false), this),
];
}
protected override filterConfigurationChanged(e: ConfigurationChangeEvent) {
const changed = super.filterConfigurationChanged(e);
if (
!changed &&
!configuration.changed(e, 'defaultDateFormat') &&
!configuration.changed(e, 'defaultDateLocale') &&
!configuration.changed(e, 'defaultDateShortFormat') &&
!configuration.changed(e, 'defaultDateSource') &&
!configuration.changed(e, 'defaultDateStyle') &&
!configuration.changed(e, 'defaultGravatarsStyle') &&
!configuration.changed(e, 'defaultTimeFormat')
) {
return false;
}
return true;
}
private setFilesLayout(layout: ViewFilesLayout) {
return configuration.updateEffective(`views.${this.configKey}.files.layout` as const, layout);
}
private setShowAvatars(enabled: boolean) {
return configuration.updateEffective(`views.${this.configKey}.avatars` as const, enabled);
}
}
``` | /content/code_sandbox/src/views/launchpadView.ts | xml | 2016-08-08T14:50:30 | 2024-08-15T21:25:09 | vscode-gitlens | gitkraken/vscode-gitlens | 8,889 | 2,242 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- -->
</configuration>
``` | /content/code_sandbox/spring-boot-demo-05-2/src/main/resources/log4j2-prod.xml | xml | 2016-08-22T02:54:02 | 2024-08-09T03:02:00 | spring-boot-demo | roncoo/spring-boot-demo | 1,718 | 25 |
```xml
#include <Security/Security.h>
int main() {
return static_cast<int>(kSecAccessControlTouchIDCurrentSet);
}
``` | /content/code_sandbox/cmake/compiler-checks/macos/control_touch_id_support.mm | xml | 2016-02-28T15:52:40 | 2024-08-16T19:26:56 | keepassxc | keepassxreboot/keepassxc | 20,477 | 28 |
```xml
import 'mocha';
import chai = require("chai");
import cronstrue from "../src/cronstrue";
let assert = chai.assert;
describe("Cronstrue", function () {
describe("every", function () {
it("* * * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every second");
});
it("* * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute");
});
it("0 * * * * (verbose)", function () {
assert.equal(cronstrue.toString("0 * * * *", { verbose: true }), "Every hour, every day");
});
it("* * * * * (verbose)", function () {
assert.equal(cronstrue.toString("* * * * *", { verbose: true }), "Every minute, every hour, every day");
});
it("*/1 * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute");
});
it("*/5 * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every 5 minutes");
});
it("0 0/1 * * * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute");
});
it("0 0 * * * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every hour");
});
it("0 0 0/1 * * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every hour");
});
it("* * * 3 *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, only in March");
});
it("* * * 3,6 *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, only in March and June");
});
it("* * * * * * 2013", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every second, only in 2013");
});
it("* * * * * 2013", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, only in 2013");
});
it("* * * * * 2013,2014", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, only in 2013 and 2014");
});
});
describe("interval", function () {
it("*/45 * * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every 45 seconds");
});
it("*/5 * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every 5 minutes");
});
it("*/10 * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every 10 minutes");
});
it("0 */5 * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every 5 minutes");
});
it("0 9-17 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every hour, between 09:00 AM and 05:00 PM");
});
it("0 * ? * 2/1 *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every hour, Tuesday through Saturday");
});
it("0 * ? * 1/1", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every hour, Monday through Saturday");
});
it("0 * ? * 2/1", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every hour, Tuesday through Saturday");
});
it("0 52 13 ? * 3/1", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 01:52 PM, Wednesday through Saturday");
});
});
describe("ranges", function () {
it("0 23 ? * MON-FRI", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 11:00 PM, Monday through Friday");
});
it("30 11 * * 1-5", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 11:30 AM, Monday through Friday");
});
it("0-10 11 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute between 11:00 AM and 11:10 AM");
});
it("23 12 * Jan-Mar *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:23 PM, January through March");
});
it("23 12 * JAN-FEB *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:23 PM, January through February");
});
it("1 1,3-4 * * *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 1 minutes past the hour, at 01:00 AM and 03:00 AM through 04:59 AM"
);
});
it("* 0 */4 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every second, at 0 minutes past the hour, every 4 hours");
});
it("*/10 0 * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every 10 seconds, at 0 minutes past the hour");
});
it("* 0 0 * * *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"Every second, at 0 minutes past the hour, between 12:00 AM and 12:00 AM"
);
});
it("* 0 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, between 12:00 AM and 12:59 AM");
});
it("* 0 * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every second, at 0 minutes past the hour");
});
});
describe("at", function () {
it("30 11 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: 3
}), "At 02:30 PM");
});
it("31 10 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: 5.5
}), "At 04:01 PM");
});
it("29 10 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: 5.5
}), "At 03:59 PM");
});
it("30 10 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: 5.5
}), "At 04:00 PM");
});
it("31 10 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: -1.5
}), "At 09:01 AM");
});
it("29 10 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: -1.5
}), "At 08:59 AM");
});
it("30 10 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: -1.5
}), "At 09:00 AM");
});
it("30 11 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: 3,
use24HourTimeFormat: true
}), "At 14:30");
});
it("30 3 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: -5,
use24HourTimeFormat: true
}), "At 22:30");
});
it("10 11 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: -4,
verbose: true
}), "At 07:10 AM, every day");
});
it("30 22 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: 5,
use24HourTimeFormat: true
}), "At 03:30");
});
it("5 1 * * 1", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: -2,
}), "At 11:05 PM, only on Sunday");
});
it("5 23 * * 1", function () {
assert.equal(cronstrue.toString(this.test?.title as string, {
tzOffset: 2,
}), "At 01:05 AM, only on Tuesday");
});
it("30 11 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 11:30 AM");
});
it("23 12 * * SUN", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:23 PM, only on Sunday");
});
it("30 02 14 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 02:02:30 PM");
});
it("0 0 6 1/1 * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 06:00 AM");
});
it("0 5 0/1 * * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 5 minutes past the hour");
});
it("46 9 * * 1", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 09:46 AM, only on Monday");
});
it("46 9 * * 7", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 09:46 AM, only on Sunday", "7 should mean Sunday");
});
it("23 12 15 * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:23 PM, on day 15 of the month");
});
it("23 12 * JAN *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:23 PM, only in January");
});
it("23 12 ? JAN *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:23 PM, only in January");
});
it("0 7 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 07:00 AM", "trailing space");
});
it("30 14,16 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 02:30 PM and 04:30 PM");
});
it("30 6,14,16 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 06:30 AM, 02:30 PM and 04:30 PM");
});
it("0 * 31 * 1", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every hour, on day 31 of the month, and on Monday");
});
it("0 45 12 22,17,6,30,26 * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:45 PM, on day 6, 17, 22, 26, and 30 of the month");
});
});
describe("weekday", function () {
it("* * LW * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the last weekday of the month");
});
it("* * WL * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the last weekday of the month");
});
it("* * 1W * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the first weekday of the month");
});
it("* * 13W * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the weekday nearest day 13 of the month");
});
it("* * W1 * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the first weekday of the month");
});
it("* * 5W * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the weekday nearest day 5 of the month");
});
it("* * W5 * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the weekday nearest day 5 of the month");
});
});
describe("last", function () {
it("* * * * 4L", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the last Thursday of the month");
});
it("*/5 * L JAN *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"Every 5 minutes, on the last day of the month, only in January"
);
});
it("0 20 15,L * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 08:00 PM, on day 15 and the last day of the month");
});
it("0 20 1-10,20-L * *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 08:00 PM, on day 1 through 10 and 20 through the last day of the month"
);
});
it("0 15 10 * * L", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 10:15 AM, only on Saturday");
});
it("0 15 10 L * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 10:15 AM, on the last day of the month");
});
it("0 0 0 L-5 * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:00 AM, 5 days before the last day of the month");
});
});
describe("dayOfWeekStartIndexZero=false", function () {
it("23 12 * * 1#2", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { dayOfWeekStartIndexZero: false }),
"At 12:23 PM, on the second Sunday of the month"
);
});
it("* * * ? * 2-6/2", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { dayOfWeekStartIndexZero: false }),
"Every second, every 2 days of the week, Monday through Friday"
);
});
it("* * * ? * 7", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { dayOfWeekStartIndexZero: false }),
"Every second, only on Saturday"
);
});
it("* * * ? * 1,2,3,4,5", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { dayOfWeekStartIndexZero: false }),
"Every second, only on Sunday, Monday, Tuesday, Wednesday, and Thursday"
);
});
it("0 * ? * 1/1", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { dayOfWeekStartIndexZero: false }),
"Every hour, Sunday through Saturday"
);
});
it("0 * ? * 2/1", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { dayOfWeekStartIndexZero: false }),
"Every hour, Monday through Saturday"
);
});
});
describe("monthStartIndexZero=true", function () {
it("* * * 7 *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { monthStartIndexZero: true }),
"Every minute, only in August"
);
});
it("30 * * 6-8 *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { monthStartIndexZero: true }),
"At 30 minutes past the hour, July through September"
);
});
it("30 * * 1-10/2 *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { monthStartIndexZero: true }),
"At 30 minutes past the hour, every 2 months, February through November"
);
});
it("30 * * 4,5,6 *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { monthStartIndexZero: true }),
"At 30 minutes past the hour, only in May, June, and July"
);
});
it("30 * * JAN *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string, { monthStartIndexZero: true }),
"At 30 minutes past the hour, only in January"
);
});
});
describe("non-trivial expressions", function () {
it("*/5 15 * * MON-FRI", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"Every 5 minutes, between 03:00 PM and 03:59 PM, Monday through Friday"
);
});
it("* * * * MON#3", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the third Monday of the month");
});
it("* * * * MON#3,THU#1", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every minute, on the third Monday and first Thursday of the month");
});
it("5-10 * * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Seconds 5 through 10 past the minute");
});
it("5-10 30-35 10-12 * * *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"Seconds 5 through 10 past the minute, minutes 30 through 35 past the hour, between 10:00 AM and 12:59 PM"
);
});
it("30 */5 * * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 30 seconds past the minute, every 5 minutes");
});
it("10 0/5 * * * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 10 seconds past the minute, every 5 minutes");
});
it("2-59/3 1,9,22 11-26 1-6 ?", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"Every 3 minutes, minutes 2 through 59 past the hour, at 01:00 AM, 09:00 AM, and 10:00 PM, between day 11 and 26 of the month, January through June"
);
});
it("23 12 * JAN-FEB * 2013-2014", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:23 PM, January through February, 2013 through 2014");
});
it("23 12 * JAN-MAR * 2013-2015", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:23 PM, January through March, 2013 through 2015");
});
it("12-50 0-10 6 * * * 2022", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"Seconds 12 through 50 past the minute, minutes 0 through 10 past the hour, at 06:00 AM, only in 2022"
);
});
it("0 0/30 8-9 5,20 * ?", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"Every 30 minutes, between 08:00 AM and 09:59 AM, on day 5 and 20 of the month"
);
});
it("23 12 * * SUN#2", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:23 PM, on the second Sunday of the month");
});
it("0 25 7-19/8 ? * *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 25 minutes past the hour, every 8 hours, between 07:00 AM and 07:59 PM"
);
});
it("0 25 7-20/13 ? * *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 25 minutes past the hour, every 13 hours, between 07:00 AM and 08:59 PM"
);
});
it("0 0 8 1/3 * ? *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 08:00 AM, every 3 days");
});
it("0 15 10 ? * */3", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 10:15 AM, every 3 days of the week");
});
it("* * * ? * 1-5/2", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every second, every 2 days of the week, Monday through Friday");
});
it("0 5 7 2 1/3 ? *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 07:05 AM, on day 2 of the month, every 3 months");
});
it("0 15 6 1 1 ? 1/2", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 06:15 AM, on day 1 of the month, only in January, every 2 years"
);
});
it("2,4-5 1 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 2 and 4 through 5 minutes past the hour, at 01:00 AM");
});
it("2,26-28 18 * * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 2 and 26 through 28 minutes past the hour, at 06:00 PM");
});
it("5/30 * * * * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every 30 seconds, starting at 5 seconds past the minute");
});
it("0 5/30 * * * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every 30 minutes, starting at 5 minutes past the hour");
});
it("* * 5/8 * * ?", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every second, every 8 hours, starting at 05:00 AM");
});
it("0 5 7 2/3 * ? *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 07:05 AM, every 3 days, starting on day 2 of the month");
});
it("0 5 7 ? 3/2 ? *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 07:05 AM, every 2 months, March through December");
});
it("0 5 7 ? * 2/3 *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 07:05 AM, every 3 days of the week, Tuesday through Saturday"
);
});
it("0 5 7 ? * ? 2016/4", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 07:05 AM, every 4 years, 2016 through 9999");
});
it("0 30 10-13 ? * wed,FRI", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 30 minutes past the hour, between 10:00 AM and 01:59 PM, only on Wednesday and Friday"
);
});
it("0 00 10 ? * MON-THU,SUN *", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 10:00 AM, only on Monday through Thursday and Sunday");
});
it("0 0 0 1,2,3 * WED,FRI", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 12:00 AM, on day 1, 2, and 3 of the month, and on Wednesday and Friday"
);
});
it("0 2,16 1,8,15,22 * 1,2", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 02:00 AM and 04:00 PM, on day 1, 8, 15, and 22 of the month, and on Monday and Tuesday"
);
});
it("0 */4,6 * * * ", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 0 minutes past the hour, every 4 hours and at 06:00 AM");
});
it("5 30 6,14,16 5 * *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"At 5 seconds past the minute, at 30 minutes past the hour, at 06:00 AM, 02:00 PM, and 04:00 PM, on day 5 of the month"
);
});
it("0-20/3 9 * * *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"Every 3 minutes, minutes 0 through 20 past the hour, between 09:00 AM and 09:59 AM"
);
});
it("5-45/10,*/5,9 * * * *", function () {
assert.equal(
cronstrue.toString(this.test?.title as string),
"Every 10 minutes, minutes 5 through 45 past the hour, every 5 minutes, and at 9 minutes past the hour"
);
});
});
describe("@ expressions", function () {
it("@yearly", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:00 AM, on day 1 of the month, only in January");
});
it("@annually", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:00 AM, on day 1 of the month, only in January");
});
it("@monthly", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:00 AM, on day 1 of the month");
});
it("@weekly", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:00 AM, only on Sunday");
});
it("@daily", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:00 AM");
});
it("@midnight", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "At 12:00 AM");
});
it("@hourly", function () {
assert.equal(cronstrue.toString(this.test?.title as string), "Every hour");
});
});
describe("verbose", function () {
it("30 4 1 * *", function () {
assert.equal(cronstrue.toString(this.test?.title as string, { verbose: true }), "At 04:30 AM, on day 1 of the month");
});
it("0 13 * * 1", function () {
assert.equal(cronstrue.toString(this.test?.title as string, { verbose: true }), "At 01:00 PM, only on Monday");
});
});
describe("errors", function () {
it('second out of range', function () {
assert.throws(function () {
cronstrue.toString("61 * * * * *");
}, "seconds part must be >= 0 and <= 59")
});
it('minute out of range', function () {
assert.throws(function () {
cronstrue.toString("0 -1 * * * *");
}, "minutes part must be >= 0 and <= 59")
});
it('hour out of range', function () {
assert.throws(function () {
cronstrue.toString("0 0 24 * * *");
}, "hours part must be >= 0 and <= 23")
});
it('dayOfMonth out of range', function () {
assert.throws(function () {
cronstrue.toString("0 0 0 32 * *");
}, "DOM part must be >= 1 and <= 31")
});
it('month out of range', function () {
assert.throws(function () {
cronstrue.toString("0 0 0 1 13 *", { monthStartIndexZero: false });
}, "month part must be >= 1 and <= 12")
assert.throws(function () {
cronstrue.toString("0 0 0 1 13 *", { monthStartIndexZero: true });
}, "month part must be >= 0 and <= 11")
});
it('dayOfWeek out of range', function () {
assert.throws(function () {
cronstrue.toString("0 0 0 1 12 8", { dayOfWeekStartIndexZero: true });
}, "DOW part must be >= 0 and <= 6");
assert.throws(function () {
cronstrue.toString("0 0 0 1 12 8", { dayOfWeekStartIndexZero: false });
}, "DOW part must be >= 1 and <= 7");
});
it("garbage expression", function () {
assert.throws(function () {
cronstrue.toString("sdlksldksldksd");
}, "Error: Expression has only 1 part. At least 5 parts are required.");
});
it("empty expression", function () {
assert.throws(function () {
cronstrue.toString("");
}, "Error: cron expression is empty");
});
it("null expression", function () {
assert.throws(function () {
cronstrue.toString(null as any as string);
}, "Error: cron expression is empty");
});
it("undefined expression", function () {
assert.throws(function () {
cronstrue.toString("");
}, "Error: cron expression is empty");
});
it("'W' list is invalid", function () {
assert.throws(function () {
cronstrue.toString("0 30 14 1W,15W * ? *");
}, "Error: The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");
});
it("garbage expression with option (throwExceptionOnParseError = false)", function () {
assert.equal(
cronstrue.toString("garbage", { throwExceptionOnParseError: false }),
"An error occured when generating the expression description. Check the cron expression syntax."
);
});
});
});
``` | /content/code_sandbox/test/cronstrue.ts | xml | 2016-06-14T21:46:51 | 2024-08-15T07:46:18 | cRonstrue | bradymholt/cRonstrue | 1,261 | 7,570 |
```xml
import {
BlurMask,
vec,
Canvas,
Circle,
Fill,
Group,
polar2Canvas,
mix,
} from '@shopify/react-native-skia';
import { useEffect, useMemo } from 'react';
import { StyleSheet, useWindowDimensions } from 'react-native';
import {
Easing,
cancelAnimation,
useDerivedValue,
useSharedValue,
withRepeat,
withTiming,
type SharedValue,
} from 'react-native-reanimated';
const c1 = '#61bea2';
const c2 = '#529ca0';
interface RingProps {
index: number;
progress: SharedValue<number>;
}
const Ring = ({ index, progress }: RingProps) => {
const { width, height } = useWindowDimensions();
const R = width / 4;
const center = useMemo(() => vec(width / 2, height / 2 - 64), [height, width]);
const theta = (index * (2 * Math.PI)) / 6;
const transform = useDerivedValue(() => {
const { x, y } = polar2Canvas({ theta, radius: progress.value * R }, { x: 0, y: 0 });
const scale = mix(progress.value, 0.3, 1);
return [{ translateX: x }, { translateY: y }, { scale }];
}, [progress, R]);
return (
<Circle c={center} r={R} color={index % 2 ? c1 : c2} origin={center} transform={transform} />
);
};
export default function SkiaScreenImpl() {
const { width, height } = useWindowDimensions();
const center = useMemo(() => vec(width / 2, height / 2 - 64), [height, width]);
const progress = useLoop({
duration: 3000,
});
const transform = useDerivedValue(
() => [{ rotate: mix(progress.value, -Math.PI, 0) }],
[progress]
);
return (
<Canvas style={styles.container}>
<Fill color="rgb(36,43,56)" />
<Group origin={center} transform={transform} blendMode="screen">
<BlurMask style="solid" blur={40} />
{new Array(6).fill(0).map((_, index) => {
return <Ring key={index} index={index} progress={progress} />;
})}
</Group>
</Canvas>
);
}
const useLoop = ({ duration }: { duration: number }) => {
const progress = useSharedValue(0);
useEffect(() => {
progress.value = withRepeat(
withTiming(1, { duration, easing: Easing.inOut(Easing.ease) }),
-1,
true
);
return () => {
cancelAnimation(progress);
};
}, [duration, progress]);
return progress;
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
``` | /content/code_sandbox/apps/native-component-list/src/screens/Skia/Breathe.tsx | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 642 |
```xml
import path from 'path';
import { testInjector } from '@stryker-mutator/test-helpers';
import { expect } from 'chai';
import { FilePreprocessor, createPreprocessor } from '../../../src/sandbox/index.js';
import { FileSystemTestDouble } from '../../helpers/file-system-test-double.js';
import { serializeTSConfig } from '../../helpers/producers.js';
import { Project } from '../../../src/fs/index.js';
describe(createPreprocessor.name, () => {
let fsTestDouble: FileSystemTestDouble;
let sut: FilePreprocessor;
beforeEach(() => {
fsTestDouble = new FileSystemTestDouble();
sut = testInjector.injector.injectFunction(createPreprocessor);
});
it('should rewrite tsconfig files', async () => {
// Arrange
const tsconfigFileName = path.resolve('tsconfig.json');
const tsconfigInput = serializeTSConfig({ extends: '../tsconfig.settings.json' });
fsTestDouble.files[tsconfigFileName] = tsconfigInput;
const project = new Project(fsTestDouble, fsTestDouble.toFileDescriptions());
// Act
await sut.preprocess(project);
// Assert
expect(await project.files.get(tsconfigFileName)!.readContent()).eq(serializeTSConfig({ extends: '../../../tsconfig.settings.json' }));
});
it('should disable type checking for .ts files', async () => {
const fileName = path.resolve('src/app.ts');
fsTestDouble.files[fileName] = 'foo.bar()';
const project = new Project(fsTestDouble, fsTestDouble.toFileDescriptions());
await sut.preprocess(project);
expect(await project.files.get(fileName)!.readContent()).eq('// @ts-nocheck\nfoo.bar()');
});
it('should strip // @ts-expect-error (see path_to_url async () => {
const fileName = path.resolve('src/app.ts');
fsTestDouble.files[fileName] = '// @ts-expect-error\nfoo.bar()';
const project = new Project(fsTestDouble, fsTestDouble.toFileDescriptions());
await sut.preprocess(project);
expect(await project.files.get(fileName)!.readContent()).eq('// @ts-nocheck\n// \nfoo.bar()');
});
});
``` | /content/code_sandbox/packages/core/test/unit/sandbox/create-preprocessor.spec.ts | xml | 2016-02-12T13:14:28 | 2024-08-15T18:38:25 | stryker-js | stryker-mutator/stryker-js | 2,561 | 466 |
```xml
/**
* need to update test environment so trackEmissions works appropriately
* @jest-environment ../shared/test.environment.ts
*/
import { mock } from "jest-mock-extended";
import { firstValueFrom, of } from "rxjs";
import { Jsonify } from "type-fest";
import { trackEmissions, awaitAsync } from "../../../../spec";
import { FakeStorageService } from "../../../../spec/fake-storage.service";
import { LogService } from "../../abstractions/log.service";
import { KeyDefinition, globalKeyBuilder } from "../key-definition";
import { StateDefinition } from "../state-definition";
import { DefaultGlobalState } from "./default-global-state";
class TestState {
date: Date;
static fromJSON(jsonState: Jsonify<TestState>) {
if (jsonState == null) {
return null;
}
return Object.assign(new TestState(), jsonState, {
date: new Date(jsonState.date),
});
}
}
const testStateDefinition = new StateDefinition("fake", "disk");
const cleanupDelayMs = 10;
const testKeyDefinition = new KeyDefinition<TestState>(testStateDefinition, "fake", {
deserializer: TestState.fromJSON,
cleanupDelayMs,
});
const globalKey = globalKeyBuilder(testKeyDefinition);
describe("DefaultGlobalState", () => {
let diskStorageService: FakeStorageService;
let globalState: DefaultGlobalState<TestState>;
const logService = mock<LogService>();
const newData = { date: new Date() };
beforeEach(() => {
diskStorageService = new FakeStorageService();
globalState = new DefaultGlobalState(testKeyDefinition, diskStorageService, logService);
});
afterEach(() => {
jest.resetAllMocks();
});
describe("state$", () => {
it("should emit when storage updates", async () => {
const emissions = trackEmissions(globalState.state$);
await diskStorageService.save(globalKey, newData);
await awaitAsync();
expect(emissions).toEqual([
null, // Initial value
newData,
]);
});
it("should not emit when update key does not match", async () => {
const emissions = trackEmissions(globalState.state$);
await diskStorageService.save("wrong_key", newData);
expect(emissions).toHaveLength(0);
});
it("should emit initial storage value on first subscribe", async () => {
const initialStorage: Record<string, TestState> = {};
initialStorage[globalKey] = TestState.fromJSON({
date: "2022-09-21T13:14:17.648Z",
});
diskStorageService.internalUpdateStore(initialStorage);
const state = await firstValueFrom(globalState.state$);
expect(diskStorageService.mock.get).toHaveBeenCalledTimes(1);
expect(diskStorageService.mock.get).toHaveBeenCalledWith("global_fake_fake", undefined);
expect(state).toBeTruthy();
});
it("should not emit twice if there are two listeners", async () => {
const emissions = trackEmissions(globalState.state$);
const emissions2 = trackEmissions(globalState.state$);
await awaitAsync();
expect(emissions).toEqual([
null, // Initial value
]);
expect(emissions2).toEqual([
null, // Initial value
]);
});
});
describe("update", () => {
it("should save on update", async () => {
const result = await globalState.update((state) => {
return newData;
});
expect(diskStorageService.mock.save).toHaveBeenCalledTimes(1);
expect(result).toEqual(newData);
});
it("should emit once per update", async () => {
const emissions = trackEmissions(globalState.state$);
await awaitAsync(); // storage updates are behind a promise
await globalState.update((state) => {
return newData;
});
await awaitAsync();
expect(emissions).toEqual([
null, // Initial value
newData,
]);
});
it("should provided combined dependencies", async () => {
const emissions = trackEmissions(globalState.state$);
await awaitAsync(); // storage updates are behind a promise
const combinedDependencies = { date: new Date() };
await globalState.update(
(state, dependencies) => {
expect(dependencies).toEqual(combinedDependencies);
return newData;
},
{
combineLatestWith: of(combinedDependencies),
},
);
await awaitAsync();
expect(emissions).toEqual([
null, // Initial value
newData,
]);
});
it("should not update if shouldUpdate returns false", async () => {
const emissions = trackEmissions(globalState.state$);
await awaitAsync(); // storage updates are behind a promise
const result = await globalState.update(
(state) => {
return newData;
},
{
shouldUpdate: () => false,
},
);
expect(diskStorageService.mock.save).not.toHaveBeenCalled();
expect(emissions).toEqual([null]); // Initial value
expect(result).toBeNull();
});
it("should provide the update callback with the current State", async () => {
const emissions = trackEmissions(globalState.state$);
await awaitAsync(); // storage updates are behind a promise
// Seed with interesting data
const initialData = { date: new Date(2020, 1, 1) };
await globalState.update((state, dependencies) => {
return initialData;
});
await awaitAsync();
await globalState.update((state) => {
expect(state).toEqual(initialData);
return newData;
});
await awaitAsync();
expect(emissions).toEqual([
null, // Initial value
initialData,
newData,
]);
});
it("should give initial state for update call", async () => {
const initialStorage: Record<string, TestState> = {};
const initialState = TestState.fromJSON({
date: "2022-09-21T13:14:17.648Z",
});
initialStorage[globalKey] = initialState;
diskStorageService.internalUpdateStore(initialStorage);
const emissions = trackEmissions(globalState.state$);
await awaitAsync(); // storage updates are behind a promise
const newState = {
...initialState,
date: new Date(initialState.date.getFullYear(), initialState.date.getMonth() + 1),
};
const actual = await globalState.update((existingState) => newState);
await awaitAsync();
expect(actual).toEqual(newState);
expect(emissions).toHaveLength(2);
expect(emissions).toEqual(expect.arrayContaining([initialState, newState]));
});
});
describe("update races", () => {
test("subscriptions during an update should receive the current and latest data", async () => {
const oldData = { date: new Date(2019, 1, 1) };
await globalState.update(() => {
return oldData;
});
const initialData = { date: new Date(2020, 1, 1) };
await globalState.update(() => {
return initialData;
});
await awaitAsync();
const emissions = trackEmissions(globalState.state$);
await awaitAsync();
expect(emissions).toEqual([initialData]);
let emissions2: TestState[];
const originalSave = diskStorageService.save.bind(diskStorageService);
diskStorageService.save = jest.fn().mockImplementation(async (key: string, obj: any) => {
emissions2 = trackEmissions(globalState.state$);
await originalSave(key, obj);
});
const val = await globalState.update(() => {
return newData;
});
await awaitAsync(10);
expect(val).toEqual(newData);
expect(emissions).toEqual([initialData, newData]);
expect(emissions2).toEqual([initialData, newData]);
});
test("subscription during an aborted update should receive the last value", async () => {
// Seed with interesting data
const initialData = { date: new Date(2020, 1, 1) };
await globalState.update(() => {
return initialData;
});
await awaitAsync();
const emissions = trackEmissions(globalState.state$);
await awaitAsync();
expect(emissions).toEqual([initialData]);
let emissions2: TestState[];
const val = await globalState.update(
() => {
return newData;
},
{
shouldUpdate: () => {
emissions2 = trackEmissions(globalState.state$);
return false;
},
},
);
await awaitAsync();
expect(val).toEqual(initialData);
expect(emissions).toEqual([initialData]);
expect(emissions2).toEqual([initialData]);
});
test("updates should wait until previous update is complete", async () => {
trackEmissions(globalState.state$);
await awaitAsync(); // storage updates are behind a promise
const originalSave = diskStorageService.save.bind(diskStorageService);
diskStorageService.save = jest
.fn()
.mockImplementationOnce(async () => {
let resolved = false;
await Promise.race([
globalState.update(() => {
// deadlocks
resolved = true;
return newData;
}),
awaitAsync(100), // limit test to 100ms
]);
expect(resolved).toBe(false);
})
.mockImplementation(originalSave);
await globalState.update((state) => {
return newData;
});
});
});
describe("cleanup", () => {
function assertClean() {
expect(diskStorageService["updatesSubject"]["observers"]).toHaveLength(0);
}
it("should cleanup after last subscriber", async () => {
const subscription = globalState.state$.subscribe();
await awaitAsync(); // storage updates are behind a promise
subscription.unsubscribe();
// Wait for cleanup
await awaitAsync(cleanupDelayMs * 2);
assertClean();
});
it("should not cleanup if there are still subscribers", async () => {
const subscription1 = globalState.state$.subscribe();
const sub2Emissions: TestState[] = [];
const subscription2 = globalState.state$.subscribe((v) => sub2Emissions.push(v));
await awaitAsync(); // storage updates are behind a promise
subscription1.unsubscribe();
// Wait for cleanup
await awaitAsync(cleanupDelayMs * 2);
expect(diskStorageService["updatesSubject"]["observers"]).toHaveLength(1);
// Still be listening to storage updates
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
diskStorageService.save(globalKey, newData);
await awaitAsync(); // storage updates are behind a promise
expect(sub2Emissions).toEqual([null, newData]);
subscription2.unsubscribe();
// Wait for cleanup
await awaitAsync(cleanupDelayMs * 2);
assertClean();
});
it("can re-initialize after cleanup", async () => {
const subscription = globalState.state$.subscribe();
await awaitAsync();
subscription.unsubscribe();
// Wait for cleanup
await awaitAsync(cleanupDelayMs * 2);
const emissions = trackEmissions(globalState.state$);
await awaitAsync();
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
diskStorageService.save(globalKey, newData);
await awaitAsync();
expect(emissions).toEqual([null, newData]);
});
it("should not cleanup if a subscriber joins during the cleanup delay", async () => {
const subscription = globalState.state$.subscribe();
await awaitAsync();
await diskStorageService.save(globalKey, newData);
await awaitAsync();
subscription.unsubscribe();
expect(diskStorageService["updatesSubject"]["observers"]).toHaveLength(1);
// Do not wait long enough for cleanup
await awaitAsync(cleanupDelayMs / 2);
expect(diskStorageService["updatesSubject"]["observers"]).toHaveLength(1);
});
it("state$ observables are durable to cleanup", async () => {
const observable = globalState.state$;
let subscription = observable.subscribe();
await diskStorageService.save(globalKey, newData);
await awaitAsync();
subscription.unsubscribe();
// Wait for cleanup
await awaitAsync(cleanupDelayMs * 2);
subscription = observable.subscribe();
await diskStorageService.save(globalKey, newData);
await awaitAsync();
expect(await firstValueFrom(observable)).toEqual(newData);
});
});
});
``` | /content/code_sandbox/libs/common/src/platform/state/implementations/default-global-state.spec.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 2,705 |
```xml
export interface IPropertyPaneHTMLHostProps {
html: string;
}
``` | /content/code_sandbox/samples/react-enhanced-powerapps/src/controls/PropertyPaneHTML/IPropertyPaneHTMLHostProps.tsx | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 17 |
```xml
<ResourceDictionary xmlns="path_to_url"
xmlns:x="path_to_url"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:controls="clr-namespace:Xamarin.Forms.Platform.WPF.Controls">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Xamarin.Forms.Platform.WPF;component/Assets/Converters.xaml" />
</ResourceDictionary.MergedDictionaries>
<DataTemplate x:Key="TitleDefaultTemplate" >
<TextBlock DataContext="{Binding}"
Text="{Binding}"
FontFamily="Segoe UI"
FontSize="26"
TextOptions.TextFormattingMode="Ideal"
TextWrapping="WrapWithOverflow"
Foreground="Black"/>
</DataTemplate>
<Style TargetType="controls:FormsContentDialog">
<Setter Property="IsTabStop" Value="False" />
<Setter Property="Width" Value="500" />
<Setter Property="Height" Value="Auto" />
<Setter Property="TitleTemplate" Value="{StaticResource TitleDefaultTemplate}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="controls:FormsContentDialog">
<Border BorderBrush="{DynamicResource AccentColor}" Background="#FFF2F2F2" BorderThickness="2">
<Grid Margin="24">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" MinHeight="150" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- title -->
<ContentControl x:Name="Title"
Content="{TemplateBinding Title}"
ContentTemplate="{TemplateBinding TitleTemplate}"
IsTabStop="False">
</ContentControl>
<!-- content -->
<ContentPresenter x:Name="Content" Margin="0,20"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
Grid.Row="1" >
<ContentPresenter.Resources>
<DataTemplate DataType="{x:Type System:String}" >
<TextBlock Text="{Binding}"
FontFamily="Segoe UI"
FontSize="16"
TextOptions.TextFormattingMode="Ideal"
TextWrapping="Wrap"
Foreground="Black"/>
</DataTemplate>
</ContentPresenter.Resources>
</ContentPresenter>
<!-- buttons -->
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="PART_PrimaryButton" Content="{TemplateBinding PrimaryButtonText}"
Height="50"
MinWidth="140"
Margin="4,0,0,0"
BorderBrush="Transparent"
Command="{x:Static controls:FormsContentDialog.PrimaryButtonRoutedCommand}">
</Button>
<Button x:Name="PART_SecondaryButton" Content="{TemplateBinding SecondaryButtonText}"
Height="50"
MinWidth="140"
Margin="4,0,0,0"
BorderBrush="Transparent"
Command="{x:Static controls:FormsContentDialog.SecondaryButtonRoutedCommand}"/>
</StackPanel>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPrimaryButtonEnabled" Value="false">
<Setter TargetName="PART_PrimaryButton" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="PrimaryButtonText" Value="{x:Static System:String.Empty}">
<Setter TargetName="PART_PrimaryButton" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="PrimaryButtonText" Value="{x:Null}">
<Setter TargetName="PART_PrimaryButton" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="IsSecondaryButtonEnabled" Value="false">
<Setter TargetName="PART_SecondaryButton" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="SecondaryButtonText" Value="{x:Static System:String.Empty}">
<Setter TargetName="PART_SecondaryButton" Property="Visibility" Value="Collapsed" />
</Trigger>
<Trigger Property="SecondaryButtonText" Value="{x:Null}">
<Setter TargetName="PART_SecondaryButton" Property="Visibility" Value="Collapsed" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
``` | /content/code_sandbox/Xamarin.Forms.Platform.WPF/Themes/FormsContentDialog.xaml | xml | 2016-03-18T15:52:03 | 2024-08-16T16:25:43 | Xamarin.Forms | xamarin/Xamarin.Forms | 5,637 | 935 |
```xml
import * as React from 'react';
import createSvgIcon from '../utils/createSvgIcon';
const LineIcon = createSvgIcon({
svg: ({ classes }) => (
<svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false">
<path d="M2029 1939l-90 90L19 109l90-90 1920 1920z" />
</svg>
),
displayName: 'LineIcon',
});
export default LineIcon;
``` | /content/code_sandbox/packages/react-icons-mdl2/src/components/LineIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 119 |
```xml
<project xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<groupId>com.journaldev.hsqldb</groupId>
<artifactId>HSQLDB-Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.4.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<release>10</release>
</configuration>
</plugin>
</plugins>
</build>
</project>
``` | /content/code_sandbox/HSQLDB-Example/pom.xml | xml | 2016-05-02T05:43:21 | 2024-08-16T06:51:39 | journaldev | WebJournal/journaldev | 1,314 | 220 |
```xml
import { InjectionToken } from '@angular/core';
export const LOADER_DELAY = new InjectionToken<number>('LOADER_DELAY');
``` | /content/code_sandbox/npm/ng-packs/packages/core/src/lib/tokens/lodaer-delay.token.ts | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 26 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="io.github.project_travel_mate.utilities.ChecklistActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="@+id/checklist_root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
``` | /content/code_sandbox/Android/app/src/main/res/layout/activity_check_list.xml | xml | 2016-01-30T13:42:30 | 2024-08-12T19:21:10 | Travel-Mate | project-travel-mate/Travel-Mate | 1,292 | 264 |
```xml
// Fake interfaces that are required for web workers to work around
// tsconfig's DOM and WebWorker lib options being mutally exclusive.
// path_to_url
interface DedicatedWorkerGlobalScope {}
``` | /content/code_sandbox/typings/webworker.fix.d.ts | xml | 2016-01-19T10:50:01 | 2024-08-12T21:05:24 | pythonVSCode | DonJayamanne/pythonVSCode | 2,078 | 41 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ExpandingCollection">
<attr name="cardWidth" format="dimension" />
<attr name="cardHeight" format="dimension" />
<attr name="cardHeaderHeightExpanded" format="dimension" />
</declare-styleable>
</resources>
``` | /content/code_sandbox/expanding-collection/src/main/res/values/attrs.xml | xml | 2016-10-06T13:30:26 | 2024-08-15T19:22:08 | expanding-collection-android | Ramotion/expanding-collection-android | 2,022 | 79 |
```xml
import sinon from 'sinon';
import { testInjector } from '@stryker-mutator/test-helpers';
import { ParserContext } from '../../src/parsers/parser-context.js';
import { PrinterContext } from '../../src/printers/index.js';
import { TransformerContext } from '../../src/transformers/index.js';
import { createTransformerOptions } from './factories.js';
export function parserContextStub(): sinon.SinonStubbedInstance<ParserContext> {
return {
parse: sinon.stub<any>(),
};
}
export function printerContextStub(): sinon.SinonStubbedInstance<PrinterContext> {
return {
print: sinon.stub(),
};
}
export function transformerContextStub(overrides?: Partial<TransformerContext>): sinon.SinonStubbedInstance<TransformerContext> {
return {
...overrides,
transform: sinon.stub(),
mutateDescription: true,
options: createTransformerOptions(),
logger: testInjector.logger,
};
}
``` | /content/code_sandbox/packages/instrumenter/test/helpers/stubs.ts | xml | 2016-02-12T13:14:28 | 2024-08-15T18:38:25 | stryker-js | stryker-mutator/stryker-js | 2,561 | 196 |
```xml
import "reflect-metadata"
import { Post } from "./entity/Post"
import { DataSource } from "../../../../../src/data-source/DataSource"
import {
closeTestingConnections,
createTestingConnections,
reloadTestingDatabases,
} from "../../../../utils/test-utils"
describe("database schema > column collation > cockroach", () => {
let connections: DataSource[]
before(async () => {
connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
enabledDrivers: ["cockroachdb"],
})
})
beforeEach(() => reloadTestingDatabases(connections))
after(() => closeTestingConnections(connections))
it("should correctly create column with collation option", () =>
Promise.all(
connections.map(async (connection) => {
const postRepository = connection.getRepository(Post)
const queryRunner = connection.createQueryRunner()
const table = await queryRunner.getTable("post")
await queryRunner.release()
const post = new Post()
post.id = 1
post.name = "Post"
await postRepository.save(post)
table!
.findColumnByName("name")!
.collation!.should.be.equal("en_US")
}),
))
})
``` | /content/code_sandbox/test/functional/database-schema/column-collation/cockroach/column-collation-cockroach.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 260 |
```xml
import {ErrorDTO} from './Error';
export class Message<T> {
public error: ErrorDTO = null;
public result: T = null;
constructor(error: ErrorDTO, result: T) {
this.error = error;
this.result = result;
}
}
``` | /content/code_sandbox/src/common/entities/Message.ts | xml | 2016-03-12T11:46:41 | 2024-08-16T19:56:44 | pigallery2 | bpatrik/pigallery2 | 1,727 | 60 |
```xml
export interface ITab {
id: string;
name: string;
icon: React.ReactElement;
}
``` | /content/code_sandbox/samples/react-my-dashboard/src/src/models/ITab.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 25 |
```xml
type A = {
// commentA
[a in A]: string;
}
type B = {
/* commentB */ [b in B]: string
}
type C = {
[/* commentC */ c in C]: string
}
type D = {
[d /* commentD */ in D]: string
}
type E = {
[e in /* commentE */ E]: string
}
type F = {
[f in F /* commentF */]: string
}
type G = {
[g in G] /* commentG */: string
}
type H = { /* commentH */ [h in H]: string }
type I = { [/* commentI */ i in I]: string }
type J = { [j /* commentJ */ in J]: string }
type K = { [k in /* commentK */ K]: string }
type L = { [l in L /* commentL */]: string }
type M = { [m in M] /* commentG */: string }
``` | /content/code_sandbox/tests/format/typescript/comments/mapped_types.ts | xml | 2016-11-29T17:13:37 | 2024-08-16T17:29:57 | prettier | prettier/prettier | 48,913 | 213 |
```xml
import {Column, Entity, ManyToOne, PrimaryGeneratedColumn} from 'typeorm';
import {SharingDTO} from '../../../../common/entities/SharingDTO';
import {UserEntity} from './UserEntity';
import {UserDTO} from '../../../../common/entities/UserDTO';
@Entity()
export class SharingEntity implements SharingDTO {
@PrimaryGeneratedColumn({unsigned: true})
id: number;
@Column()
sharingKey: string;
@Column()
path: string;
@Column({type: 'text', nullable: true})
password: string;
@Column('bigint', {
unsigned: true,
transformer: {
from: (v) => parseInt(v, 10),
to: (v) => v,
},
})
expires: number;
@Column('bigint', {
unsigned: true,
transformer: {
from: (v) => parseInt(v, 10),
to: (v) => v,
},
})
timeStamp: number;
@Column()
includeSubfolders: boolean;
@ManyToOne(() => UserEntity, {onDelete: 'CASCADE', nullable: false})
creator: UserDTO;
}
``` | /content/code_sandbox/src/backend/model/database/enitites/SharingEntity.ts | xml | 2016-03-12T11:46:41 | 2024-08-16T19:56:44 | pigallery2 | bpatrik/pigallery2 | 1,727 | 245 |
```xml
<fxlayout help_file="SubtractIno.pdf">
<page name="Subtract Ino">
<control>opacity</control>
<control>clipping_mask</control>
<control>alpha_rendering</control>
<separator/>
<control>colorSpaceMode</control>
<vbox modeSensitive="colorSpaceMode" mode="1">
<control>gamma</control>
<control>gammaAdjust</control>
<control>premultiplied</control>
</vbox>
</page>
</fxlayout>
``` | /content/code_sandbox/stuff/profiles/layouts/fxs/STD_inoSubtractFx.xml | xml | 2016-03-18T17:55:48 | 2024-08-15T18:11:38 | opentoonz | opentoonz/opentoonz | 4,445 | 120 |
```xml
export type ReactRouterFeatureOptions = {
/**
* The React module.
*
* This is needed for the react router feature to wrap subapp's component inside
* the Router component.
*/
React: Partial<{ createElement: unknown }>;
/**
* A custom browser history object and control which Router to use.
*
* - If it's `true`, or not specified, then `Router` is used with history from `createBrowserHistory`
* from path_to_url and the same history object will be shared
* among all subapps
* - If it's a valid object, then it's assumed to be a history object and used with `Router`
* - Finally fallback to use `BrowserRouter`, which internally uses its own history object that's not
* shared with other subapps.
*/
history?: boolean | unknown; // eslint-disable-line @typescript-eslint/ban-types
};
export const _id = "router-provider";
export const _subId = "react-router";
//
// re-export react-router-dom as ReactRouterDom etc
//
export * as ReactRouterDom from "react-router-dom";
export * from "react-router-dom";
//
// re-export react-router as ReactRouter
//
export * as ReactRouter from "react-router";
``` | /content/code_sandbox/packages/xarc-react-router/src/common/index.ts | xml | 2016-09-06T19:02:39 | 2024-08-11T11:43:11 | electrode | electrode-io/electrode | 2,103 | 274 |
```xml
<?xml version="1.0" encoding="utf-8"?>
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<resources>
<!-- Link Preview dimensions -->
<dimen name="link_preview_overlay_radius">7dp</dimen>
</resources>
``` | /content/code_sandbox/libraries_res/content_res/src/main/res/values/dimens.xml | xml | 2016-07-04T07:28:36 | 2024-08-15T05:20:42 | AndroidChromium | JackyAndroid/AndroidChromium | 3,090 | 70 |
```xml
import type { InternalStoreDocType, PlainJsonError } from '../../types/index.d.ts';
export type RxMigrationStatus = {
collectionName: string;
status: 'RUNNING' | 'DONE' | 'ERROR';
error?: PlainJsonError;
/**
* Counters so that you can display
* the migration state to your user in the UI
* and show a loading bar.
*/
count: {
/**
* Total amount of documents that
* have to be migrated
*/
total: number;
/**
* Amount of documents that have been migrated already
* = success + purged
*/
handled: number;
/**
* Total percentage [0-100]
*/
percent: number;
};
};
/**
* To be shared between browser tabs,
* the migration status is written into a document in the internal storage of the database.
*/
export type RxMigrationStatusDocument = InternalStoreDocType<RxMigrationStatus>;
export type MigrationStatusUpdate = (before: RxMigrationStatus) => RxMigrationStatus;
``` | /content/code_sandbox/dist/types/plugins/migration-schema/migration-types.d.ts | xml | 2016-12-02T19:34:42 | 2024-08-16T15:47:20 | rxdb | pubkey/rxdb | 21,054 | 227 |
```xml
import PackagesGraphEdge from './PackagesGraphEdge';
import { DefaultDependencyKind, DependencyKind, Package } from '../Packages';
/**
* A graph node that refers to the single package.
*/
export default class PackagesGraphNode {
/**
* The package represented by the node.
*/
pkg: Package;
/**
* The package name.
*/
name: string;
/**
* Indicates how deep the node is placed in the graph.
* Depth of nodes without incoming edges is equal to `0`.
*/
depth: number = 0;
/**
* Edges connecting this node with its dependencies.
*/
outgoingEdges: PackagesGraphEdge[] = [];
/**
* Edges connecting this node with its dependents.
*/
incomingEdges: PackagesGraphEdge[] = [];
constructor(pkg: Package) {
this.pkg = pkg;
this.name = pkg.packageName;
}
getOutgoingEdgeForNode(node: PackagesGraphNode): PackagesGraphEdge | null {
return this.outgoingEdges.find((edge) => edge.destination === node) ?? null;
}
getIncomingEdgeForNode(node: PackagesGraphNode): PackagesGraphEdge | null {
return this.incomingEdges.find((edge) => edge.origin === node) ?? null;
}
getAllDependentEdges(kinds: DependencyKind[] = DefaultDependencyKind): PackagesGraphEdge[] {
const allDependentEdges = this.incomingEdges
.map((edge) => {
if (!edge.isCyclic && kinds.includes(edge.getDominantKind())) {
return [edge, ...edge.origin.getAllDependentEdges(kinds)];
}
return [];
})
.flat();
return [...new Set(allDependentEdges)];
}
getAllDependents(kinds: DependencyKind[] = DefaultDependencyKind): PackagesGraphNode[] {
return [...new Set(this.getAllDependentEdges(kinds).map((edge) => edge.origin))];
}
getAllDependencyEdges(kinds: DependencyKind[] = DefaultDependencyKind): PackagesGraphEdge[] {
const allDependencyEdges = this.outgoingEdges
.map((edge) => {
if (!edge.isCyclic && kinds.includes(edge.getDominantKind())) {
return [edge, ...edge.destination.getAllDependencyEdges(kinds)];
}
return [];
})
.flat();
return [...new Set(allDependencyEdges)];
}
getAllDependencies(kinds: DependencyKind[] = DefaultDependencyKind): PackagesGraphNode[] {
return [...new Set(this.getAllDependencyEdges(kinds).map((edge) => edge.destination))];
}
getOutgoingEdgesOfKinds(kinds: DependencyKind[]): PackagesGraphEdge[] {
return this.outgoingEdges.filter((edge) => {
return kinds.some((kind) => edge.isOfKind(kind));
});
}
isDependentOf(node: PackagesGraphNode): boolean {
return !!this.getOutgoingEdgeForNode(node);
}
isDependencyOf(node: PackagesGraphNode): boolean {
return !!this.getIncomingEdgeForNode(node);
}
}
``` | /content/code_sandbox/tools/src/packages-graph/PackagesGraphNode.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 639 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\PowerShell.Common.props"/>
<PropertyGroup>
<Description>PowerShell top-level project with .NET CLI host</Description>
<AssemblyName>pwsh</AssemblyName>
<OutputType>Exe</OutputType>
<TieredCompilation>true</TieredCompilation>
<TieredCompilationQuickJit>true</TieredCompilationQuickJit>
<TieredCompilationQuickJitForLoops>true</TieredCompilationQuickJitForLoops>
<RuntimeIdentifiers>linux-x64;osx-x64;</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\powershell\Program.cs" Exclude="bin\**;obj\**;**\*.xproj;packages\**" />
<Content Include="..\Modules\Unix\**\*;..\Modules\Shared\**\*" >
<Link>Modules\%(RecursiveDir)\%(FileName)%(Extension)</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="..\Schemas\PSMaml\*">
<Link>Schemas\PSMaml\%(FileName)%(Extension)</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="..\..\LICENSE.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="..\..\ThirdPartyNotices.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="..\..\assets\default.help.txt">
<Link>en-US\default.help.txt</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Microsoft.PowerShell.SDK\Microsoft.PowerShell.SDK.csproj" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/src/powershell-unix/powershell-unix.csproj | xml | 2016-01-13T23:41:35 | 2024-08-16T19:59:07 | PowerShell | PowerShell/PowerShell | 44,388 | 529 |
```xml
'use client';
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { Image } from './Image';
import { ImageBackgroundProps } from './Image.types';
export function ImageBackground({ style, imageStyle, children, ...props }: ImageBackgroundProps) {
return (
<View style={style}>
<Image {...props} style={[StyleSheet.absoluteFill, imageStyle]} />
{children}
</View>
);
}
``` | /content/code_sandbox/packages/expo-image/src/ImageBackground.tsx | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 97 |
```xml
<!--
Description: entry id
-->
<feed xmlns="path_to_url">
<entry>
<id>path_to_url
</entry>
</feed>
``` | /content/code_sandbox/testdata/translator/atom/feed_item_guid_-_atom10_feed_entry_id.xml | xml | 2016-01-23T02:44:34 | 2024-08-16T15:16:03 | gofeed | mmcdole/gofeed | 2,547 | 35 |
```xml
import React from 'react';
import { Text } from 'react-native';
import { render } from '@testing-library/react-native';
import withTheme from '../withTheme';
describe('withTheme', () => {
it('passes theme props to function component', () => {
const Component = withTheme(() => <Text testID="myText" />);
const { queryByTestId } = render(<Component />);
const wrapper = queryByTestId('myText')!.parent!.parent!;
expect(Object.keys(wrapper.props)).toContain('theme');
});
it('passes theme props to class component', () => {
class Component extends React.Component {
render() {
return <Text testID="myText" />;
}
}
const WrappedComponent = withTheme(Component);
const { queryByTestId } = render(<WrappedComponent />);
const wrapper = queryByTestId('myText')!.parent!.parent!;
expect(Object.keys(wrapper.props)).toContain('theme');
});
it('should have static methods', () => {
class Component extends React.Component {
static navigationOptions = {
title: 'Hey',
};
render() {
return <Text />;
}
}
const WrappedComponent = withTheme(Component);
expect(WrappedComponent.navigationOptions).toEqual({
title: 'Hey',
});
});
it('should render class components', () => {
class Component extends React.Component {
hello = () => {
return 'Hey';
};
render() {
return <Text testID="myText" />;
}
}
const WrappedComponent = withTheme(Component);
const { queryByTestId } = render(<WrappedComponent />);
const instanceMethods = queryByTestId('myText')!.parent!.parent!.instance;
expect(instanceMethods.hello()).toBe('Hey');
});
});
``` | /content/code_sandbox/packages/themed/src/config/__tests__/withTheme.test.tsx | xml | 2016-09-08T14:21:41 | 2024-08-16T10:11:29 | react-native-elements | react-native-elements/react-native-elements | 24,875 | 382 |
```xml
import { useState, useMemo } from 'react'
import cloneDeep from 'lodash/cloneDeep'
import { sankey as d3Sankey } from 'd3-sankey'
import { useTheme, usePropertyAccessor, useValueFormatter } from '@nivo/core'
import { useOrdinalColorScale, useInheritedColor } from '@nivo/colors'
import { sankeyAlignmentFromProp } from './props'
import {
DefaultLink,
DefaultNode,
SankeyAlignFunction,
SankeyCommonProps,
SankeyDataProps,
SankeyLinkDatum,
SankeyNodeDatum,
SankeySortFunction,
} from './types'
const getId = <N extends DefaultNode>(node: N) => node.id
export const computeNodeAndLinks = <N extends DefaultNode, L extends DefaultLink>({
data: _data,
formatValue,
layout,
alignFunction,
sortFunction,
linkSortMode,
nodeThickness,
nodeSpacing,
nodeInnerPadding,
width,
height,
getColor,
getLabel,
}: {
data: SankeyDataProps<N, L>['data']
formatValue: (value: number) => string
layout: SankeyCommonProps<N, L>['layout']
alignFunction: SankeyAlignFunction
sortFunction: null | undefined | SankeySortFunction<N, L>
linkSortMode: null | undefined
nodeThickness: SankeyCommonProps<N, L>['nodeThickness']
nodeSpacing: SankeyCommonProps<N, L>['nodeSpacing']
nodeInnerPadding: SankeyCommonProps<N, L>['nodeInnerPadding']
width: number
height: number
getColor: (node: Omit<SankeyNodeDatum<N, L>, 'color' | 'label'>) => string
getLabel: (node: Omit<SankeyNodeDatum<N, L>, 'color' | 'label'>) => string
}) => {
const sankey = d3Sankey()
.nodeAlign(alignFunction)
// @ts-ignore: this method signature is incorrect in current @types/d3-sankey
.nodeSort(sortFunction)
// @ts-ignore: this method is not available in current @types/d3-sankey
.linkSort(linkSortMode)
.nodeWidth(nodeThickness)
.nodePadding(nodeSpacing)
.size(layout === 'horizontal' ? [width, height] : [height, width])
.nodeId(getId)
// deep clone is required as the sankey diagram mutates data
// we need a different identity for correct updates
const data = cloneDeep(_data) as unknown as {
nodes: SankeyNodeDatum<N, L>[]
links: SankeyLinkDatum<N, L>[]
}
sankey(data)
data.nodes.forEach(node => {
node.color = getColor(node)
node.label = getLabel(node)
node.formattedValue = formatValue(node.value)
if (layout === 'horizontal') {
node.x = node.x0 + nodeInnerPadding
node.y = node.y0
node.width = Math.max(node.x1 - node.x0 - nodeInnerPadding * 2, 0)
node.height = Math.max(node.y1 - node.y0, 0)
} else {
node.x = node.y0
node.y = node.x0 + nodeInnerPadding
node.width = Math.max(node.y1 - node.y0, 0)
node.height = Math.max(node.x1 - node.x0 - nodeInnerPadding * 2, 0)
const oldX0 = node.x0
const oldX1 = node.x1
node.x0 = node.y0
node.x1 = node.y1
node.y0 = oldX0
node.y1 = oldX1
}
})
data.links.forEach(link => {
link.formattedValue = formatValue(link.value)
link.color = link.source.color
// @ts-ignore
link.pos0 = link.y0
// @ts-ignore
link.pos1 = link.y1
// @ts-ignore
link.thickness = link.width
// @ts-ignore
delete link.y0
// @ts-ignore
delete link.y1
// @ts-ignore
delete link.width
})
return data
}
export const useSankey = <N extends DefaultNode, L extends DefaultLink>({
data,
valueFormat,
layout,
width,
height,
sort,
align,
colors,
nodeThickness,
nodeSpacing,
nodeInnerPadding,
nodeBorderColor,
label,
labelTextColor,
}: {
data: SankeyDataProps<N, L>['data']
valueFormat?: SankeyCommonProps<N, L>['valueFormat']
layout: SankeyCommonProps<N, L>['layout']
width: number
height: number
sort: SankeyCommonProps<N, L>['sort']
align: SankeyCommonProps<N, L>['align']
colors: SankeyCommonProps<N, L>['colors']
nodeThickness: SankeyCommonProps<N, L>['nodeThickness']
nodeSpacing: SankeyCommonProps<N, L>['nodeSpacing']
nodeInnerPadding: SankeyCommonProps<N, L>['nodeInnerPadding']
nodeBorderColor: SankeyCommonProps<N, L>['nodeBorderColor']
label: SankeyCommonProps<N, L>['label']
labelTextColor: SankeyCommonProps<N, L>['labelTextColor']
}) => {
const [currentNode, setCurrentNode] = useState<SankeyNodeDatum<N, L> | null>(null)
const [currentLink, setCurrentLink] = useState<SankeyLinkDatum<N, L> | null>(null)
const sortFunction = useMemo(() => {
if (sort === 'auto') return undefined
if (sort === 'input') return null
if (sort === 'ascending') {
return (a: SankeyNodeDatum<N, L>, b: SankeyNodeDatum<N, L>) => a.value - b.value
}
if (sort === 'descending') {
return (a: SankeyNodeDatum<N, L>, b: SankeyNodeDatum<N, L>) => b.value - a.value
}
return sort
}, [sort])
// If "input" sorting is used, apply this setting to links, too.
// (In d3, `null` means input sorting and `undefined` is the default)
const linkSortMode = sort === 'input' ? null : undefined
const alignFunction = useMemo(() => {
if (typeof align === 'function') return align
return sankeyAlignmentFromProp(align)
}, [align])
const theme = useTheme()
const getColor = useOrdinalColorScale(colors, 'id')
const getNodeBorderColor = useInheritedColor(nodeBorderColor, theme)
const getLabel = usePropertyAccessor<Omit<SankeyNodeDatum<N, L>, 'color' | 'label'>, string>(
label
)
const getLabelTextColor = useInheritedColor(labelTextColor, theme)
const formatValue = useValueFormatter<number>(valueFormat)
const { nodes, links } = useMemo(
() =>
computeNodeAndLinks<N, L>({
data,
formatValue,
layout,
alignFunction,
sortFunction,
linkSortMode,
nodeThickness,
nodeSpacing,
nodeInnerPadding,
width,
height,
getColor,
getLabel,
}),
[
data,
formatValue,
layout,
alignFunction,
sortFunction,
linkSortMode,
nodeThickness,
nodeSpacing,
nodeInnerPadding,
width,
height,
getColor,
getLabel,
]
)
const legendData = useMemo(
() =>
nodes.map(node => ({
id: node.id,
label: node.label,
color: node.color,
})),
[nodes]
)
return {
nodes,
links,
legendData,
getNodeBorderColor,
currentNode,
setCurrentNode,
currentLink,
setCurrentLink,
getLabelTextColor,
}
}
``` | /content/code_sandbox/packages/sankey/src/hooks.ts | xml | 2016-04-16T03:27:56 | 2024-08-16T03:38:37 | nivo | plouc/nivo | 13,010 | 1,777 |
```xml
import { __ } from '@erxes/ui/src/utils/core';
import React from 'react';
import { ModalFooter } from '@erxes/ui/src/styles/main';
import Button from '@erxes/ui/src/components/Button';
import { ILeadIntegration } from '@erxes/ui-leads/src/types';
import { ITrigger } from '../../../../types';
import Select from 'react-select';
import FormGroup from '@erxes/ui/src/components/form/Group';
import ControlLabel from '@erxes/ui/src/components/form/Label';
type Props = {
closeModal: () => void;
closeParentModal?: () => void;
formIntegrations: ILeadIntegration[];
activeTrigger: ITrigger;
contentId?: string;
addTrigger: (value: string, contentId?: string, triggerId?: string) => void;
};
type State = {
activeIntegrationId: string;
formId: string;
};
class FormSubmit extends React.Component<Props, State> {
constructor(props) {
super(props);
this.state = {
activeIntegrationId: props.activeTrigger.config
? props.activeTrigger.config.contentId
: '',
formId: ''
};
}
onSave = () => {
const {
addTrigger,
activeTrigger,
closeParentModal,
closeModal
} = this.props;
const { formId } = this.state;
addTrigger(activeTrigger.type, formId, activeTrigger.id);
closeParentModal ? closeParentModal() : closeModal();
};
onChangeForm = option => {
const form = this.props.formIntegrations.find(e => e._id === option.value);
if (!form) {
return;
}
this.setState({
formId: (form || ({} as any)).formId,
activeIntegrationId: option.value
});
};
render() {
const { formIntegrations } = this.props;
const selectOptions = (array: ILeadIntegration[] = []) => {
return array.map(item => ({ value: item._id, label: item.name }));
};
const selectedValue = formIntegrations.find(
item => (item || ({} as any)).formId === this.state.activeIntegrationId
);
const value = selectedValue
? selectedValue._id
: this.state.activeIntegrationId;
return (
<>
<FormGroup>
<ControlLabel required={true}>{__('Select form')}</ControlLabel>
<Select
required={true}
value={selectOptions(formIntegrations).find((o) => o.value === value)}
options={selectOptions(formIntegrations)}
onChange={this.onChangeForm}
placeholder={__('Select')}
/>
</FormGroup>
<ModalFooter>
<Button
btnStyle="simple"
type="button"
onClick={this.props.closeModal}
icon="times-circle"
>
{__('Cancel')}
</Button>
<Button btnStyle="success" icon="checked-1" onClick={this.onSave}>
Save
</Button>
</ModalFooter>
</>
);
}
}
export default FormSubmit;
``` | /content/code_sandbox/packages/plugin-automations-ui/src/components/forms/triggers/subForms/FormSubmit.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 660 |
```xml
import type { ActionHandler } from "@Core/ActionHandler";
import type { Logger } from "@Core/Logger";
import type { SearchResultItemAction } from "@common/Core";
import { WorkflowActionArgumentDecoder } from "./Utility";
import type { WorkflowActionHandler } from "./WorkflowActionHandler";
export class WorkflowHandler implements ActionHandler {
public readonly id = "Workflow";
public constructor(
private readonly logger: Logger,
private readonly workflowActionHandlers: Record<string, WorkflowActionHandler>,
) {}
public async invokeAction(action: SearchResultItemAction): Promise<void> {
const workflowActions = WorkflowActionArgumentDecoder.decodeArgument(action.argument);
const promises = workflowActions
.filter((workflow) => Object.keys(this.workflowActionHandlers).includes(workflow.handlerId))
.map((workflow) => this.workflowActionHandlers[workflow.handlerId].invokeWorkflowAction(workflow));
const promiseResults = await Promise.allSettled(promises);
for (const promiseResult of promiseResults) {
if (promiseResult.status === "rejected") {
this.logger.error(`Unable to invoke workflow action. Reason: ${promiseResult.reason}`);
}
}
}
}
``` | /content/code_sandbox/src/main/Extensions/Workflow/WorkflowHandler.ts | xml | 2016-10-11T04:59:52 | 2024-08-16T11:53:31 | ueli | oliverschwendener/ueli | 3,543 | 244 |
```xml
import * as Blockly from "blockly";
import { ConstantProvider } from "./constants";
export class CollapsedInputRow extends Blockly.blockRendering.InputRow {
constructor(constants: ConstantProvider) {
super(constants);
this.type |= Blockly.blockRendering.Types.INPUT_ROW | Blockly.blockRendering.Types.getType("COLLAPSED_INPUT_ROW");
}
measure(): void {
this.width = this.minWidth;
this.height = this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT;
}
}
export function isCollapsedInputRow(row: Blockly.blockRendering.Row): row is CollapsedInputRow {
return !!(row.type & Blockly.blockRendering.Types.getType("COLLAPSED_INPUT_ROW"));
}
``` | /content/code_sandbox/pxtblocks/plugins/renderer/collapsedInputRow.ts | xml | 2016-01-24T19:35:52 | 2024-08-16T16:39:39 | pxt | microsoft/pxt | 2,069 | 140 |
```xml
<?xml version="1.0" encoding="utf-8" ?>
<services version="1.0">
<admin version="2.0">
<adminserver hostalias="node1"/>
<slobroks>
<slobrok hostalias="node1"/>
<slobrok hostalias="node2"/>
</slobroks>
</admin>
<container version="1.0">
<nodes>
<node hostalias="node1" />
</nodes>
<search/>
<document-api/>
</container>
<content id="music" version="1.0">
<redundancy>1</redundancy>
<documents>
<document type="music" mode="index" />
</documents>
<nodes>
<node hostalias="node1" distribution-key="0" />
</nodes>
</content>
</services>
``` | /content/code_sandbox/config-model/src/test/cfg/application/app_complicated_deployment_spec/services.xml | xml | 2016-06-03T20:54:20 | 2024-08-16T15:32:01 | vespa | vespa-engine/vespa | 5,524 | 200 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.