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 { defineComponent, h } from 'vue'
import { parseQuery } from 'vue-router'
import { resolve } from 'pathe'
import destr from 'destr'
// @ts-expect-error virtual file
import { devRootDir } from '#build/nuxt.config.mjs'
export default (url: string) => defineComponent({
name: 'NuxtTestComponentWrapper',
async setup (props, { attrs }) {
const query = parseQuery(new URL(url, 'path_to_url
const urlProps = query.props ? destr<Record<string, any>>(query.props as string) : {}
const path = resolve(query.path as string)
if (!path.startsWith(devRootDir)) {
throw new Error(`[nuxt] Cannot access path outside of project root directory: \`${path}\`.`)
}
const comp = await import(/* @vite-ignore */ path as string).then(r => r.default)
return () => [
h('div', 'Component Test Wrapper for ' + path),
h('div', { id: 'nuxt-component-root' }, [
h(comp, { ...attrs, ...props, ...urlProps }),
]),
]
},
})
``` | /content/code_sandbox/packages/nuxt/src/app/components/test-component-wrapper.ts | xml | 2016-10-26T11:18:47 | 2024-08-16T19:32:46 | nuxt | nuxt/nuxt | 53,705 | 257 |
```xml
import { useState, useEffect, useRef } from 'react';
import { toast, ToastItem, Id } from 'react-toastify';
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
export interface NotificationCenterItem<Data = {}>
extends Optional<ToastItem<Data>, 'content' | 'data' | 'status'> {
read: boolean;
createdAt: number;
}
export type SortFn<Data> = (
l: NotificationCenterItem<Data>,
r: NotificationCenterItem<Data>
) => number;
export type FilterFn<Data = {}> = (
item: NotificationCenterItem<Data>
) => boolean;
export interface UseNotificationCenterParams<Data = {}> {
/**
* initial data to rehydrate the notification center
*/
data?: NotificationCenterItem<Data>[];
/**
* By default, the notifications are sorted from the newest to the oldest using
* the `createdAt` field. Use this to provide your own sort function
*
* Usage:
* ```
* // old notifications first
* useNotificationCenter({
* sort: ((l, r) => l.createdAt - r.createdAt)
* })
* ```
*/
sort?: SortFn<Data>;
/**
* Keep the toast that meets the condition specified in the callback function.
*
* Usage:
* ```
* // keep only the toasts when hidden is set to false
* useNotificationCenter({
* filter: item => item.data.hidden === false
* })
* ```
*/
filter?: FilterFn<Data>;
}
export interface UseNotificationCenter<Data> {
/**
* Contains all the notifications
*/
notifications: NotificationCenterItem<Data>[];
/**
* Clear all notifications
*/
clear(): void;
/**
* Mark all notification as read
*/
markAllAsRead(): void;
/**
* Mark all notification as read or not.
*
* Usage:
* ```
* markAllAsRead(false) // mark all notification as not read
*
* markAllAsRead(true) // same as calling markAllAsRead()
* ```
*/
markAllAsRead(read?: boolean): void;
/**
* Mark one or more notifications as read.
*
* Usage:
* ```
* markAsRead("anId")
* markAsRead(["a","list", "of", "id"])
* ```
*/
markAsRead(id: Id | Id[]): void;
/**
* Mark one or more notifications as read.The second parameter let you mark the notification as read or not.
*
* Usage:
* ```
* markAsRead("anId", false)
* markAsRead(["a","list", "of", "id"], false)
*
* markAsRead("anId", true) // same as markAsRead("anId")
* ```
*/
markAsRead(id: Id | Id[], read?: boolean): void;
/**
* Remove one or more notifications
*
* Usage:
* ```
* remove("anId")
* remove(["a","list", "of", "id"])
* ```
*/
remove(id: Id | Id[]): void;
/**
* Push a notification to the notification center.
* Returns null when an item with the given id already exists
*
* Usage:
* ```
* const id = add({id: "id", content: "test", data: { foo: "hello" } })
*
* // Return the id of the notification, generate one if none provided
* const id = add({ data: {title: "a title", text: "some text"} })
* ```
*/
add(item: Partial<NotificationCenterItem<Data>>): Id | null;
/**
* Update the notification that match the id
* Returns null when no matching notification found
*
* Usage:
* ```
* const id = update("anId", {content: "test", data: { foo: "hello" } })
*
* // It's also possible to update the id
* const id = update("anId"m { id:"anotherOne", data: {title: "a title", text: "some text"} })
* ```
*/
update(id: Id, item: Partial<NotificationCenterItem<Data>>): Id | null;
/**
* Retrieve one or more notifications
*
* Usage:
* ```
* find("anId")
* find(["a","list", "of", "id"])
* ```
*/
find(id: Id): NotificationCenterItem<Data> | undefined;
/**
* Retrieve one or more notifications
*
* Usage:
* ```
* find("anId")
* find(["a","list", "of", "id"])
* ```
*/
find(id: Id[]): NotificationCenterItem<Data>[] | undefined;
/**
* Retrieve the count for unread notifications
*/
unreadCount: number;
/**
* Sort notifications using the newly provided function
*
* Usage:
* ```
* // old notifications first
* sort((l, r) => l.createdAt - r.createdAt)
* ```
*/
sort(sort: SortFn<Data>): void;
}
export function useNotificationCenter<Data = {}>(
params: UseNotificationCenterParams<Data> = {}
): UseNotificationCenter<Data> {
const sortFn = useRef(params.sort || defaultSort);
const filterFn = useRef(params.filter || null);
const [notifications, setNotifications] = useState<
NotificationCenterItem<Data>[]
>(() => {
if (params.data) {
return filterFn.current
? params.data.filter(filterFn.current).sort(sortFn.current)
: [...params.data].sort(sortFn.current);
}
return [];
});
useEffect(() => {
return toast.onChange(item => {
if (item.status === 'added' || item.status === 'updated') {
const newItem = decorate(item as NotificationCenterItem<Data>);
if (filterFn.current && !filterFn.current(newItem)) return;
setNotifications(prev => {
let nextState: NotificationCenterItem<Data>[] = [];
const updateIdx = prev.findIndex(v => v.id === newItem.id);
if (updateIdx !== -1) {
nextState = prev.slice();
Object.assign(nextState[updateIdx], newItem, {
createdAt: Date.now()
});
} else if (prev.length === 0) {
nextState = [newItem];
} else {
nextState = [newItem, ...prev];
}
return nextState.sort(sortFn.current);
});
}
});
}, []);
const remove = (id: Id | Id[]) => {
setNotifications(prev =>
prev.filter(
Array.isArray(id) ? v => !id.includes(v.id) : v => v.id !== id
)
);
};
const clear = () => {
setNotifications([]);
};
const markAllAsRead = (read = true) => {
setNotifications(prev =>
prev.map(v => {
v.read = read;
return v;
})
);
};
const markAsRead = (id: Id | Id[], read = true) => {
let map = (v: NotificationCenterItem<Data>) => {
if (v.id === id) v.read = read;
return v;
};
if (Array.isArray(id)) {
map = v => {
if (id.includes(v.id)) v.read = read;
return v;
};
}
setNotifications(prev => prev.map(map));
};
const find = (id: Id | Id[]) => {
return Array.isArray(id)
? notifications.filter(v => id.includes(v.id))
: notifications.find(v => v.id === id);
};
const add = (item: Partial<NotificationCenterItem<Data>>) => {
if (notifications.find(v => v.id === item.id)) return null;
const newItem = decorate(item);
setNotifications(prev => [...prev, newItem].sort(sortFn.current));
return newItem.id;
};
const update = (id: Id, item: Partial<NotificationCenterItem<Data>>) => {
const index = notifications.findIndex(v => v.id === id);
if (index !== -1) {
setNotifications(prev => {
const nextState = [...prev];
Object.assign(nextState[index], item, {
createdAt: item.createdAt || Date.now()
});
return nextState.sort(sortFn.current);
});
return item.id as Id;
}
return null;
};
const sort = (compareFn: SortFn<Data>) => {
sortFn.current = compareFn;
setNotifications(prev => prev.slice().sort(compareFn));
};
return {
notifications,
clear,
markAllAsRead,
markAsRead,
add,
update,
remove,
// @ts-ignore fixme: overloading issue
find,
sort,
get unreadCount() {
return notifications.reduce(
(prev, cur) => (!cur.read ? prev + 1 : prev),
0
);
}
};
}
export function decorate<Data>(
item: NotificationCenterItem<Data> | Partial<NotificationCenterItem<Data>>
) {
if (item.id == null) item.id = Date.now().toString(36).substring(2, 9);
if (!item.createdAt) item.createdAt = Date.now();
if (item.read == null) item.read = false;
return item as NotificationCenterItem<Data>;
}
// newest to oldest
function defaultSort<Data>(
l: NotificationCenterItem<Data>,
r: NotificationCenterItem<Data>
) {
return r.createdAt - l.createdAt;
}
``` | /content/code_sandbox/src/addons/use-notification-center/useNotificationCenter.ts | xml | 2016-11-08T12:32:52 | 2024-08-16T13:26:40 | react-toastify | fkhadra/react-toastify | 12,467 | 2,069 |
```xml
/**
* @file Feedback controller
* @module module/feedback/controller
* @author Surmon <path_to_url
*/
import _trim from 'lodash/trim'
import _isUndefined from 'lodash/isUndefined'
import { Controller, Get, Put, Post, Delete, Query, Body, UseGuards } from '@nestjs/common'
import { Throttle, seconds } from '@nestjs/throttler'
import { AdminOnlyGuard } from '@app/guards/admin-only.guard'
import { ExposePipe } from '@app/pipes/expose.pipe'
import { Responser } from '@app/decorators/responser.decorator'
import { QueryParams, QueryParamsResult } from '@app/decorators/queryparams.decorator'
import { PaginateResult, PaginateQuery, PaginateOptions } from '@app/utils/paginate'
import { EmailService } from '@app/processors/helper/helper.service.email'
import { numberToBoolean } from '@app/transformers/value.transformer'
import { FeedbackPaginateQueryDTO, FeedbacksDTO } from './feedback.dto'
import { Feedback, FeedbackBase } from './feedback.model'
import { FeedbackService } from './feedback.service'
import * as APP_CONFIG from '@app/app.config'
@Controller('feedback')
export class FeedbackController {
constructor(
private readonly emailService: EmailService,
private readonly feedbackService: FeedbackService
) {}
@Get()
@UseGuards(AdminOnlyGuard)
@Responser.paginate()
@Responser.handle('Get feedbacks')
getFeedbacks(@Query(ExposePipe) query: FeedbackPaginateQueryDTO): Promise<PaginateResult<Feedback>> {
const { sort, page, per_page, ...filters } = query
const paginateQuery: PaginateQuery<Feedback> = {}
const paginateOptions: PaginateOptions = { page, perPage: per_page, dateSort: sort }
// target ID
if (!_isUndefined(filters.tid)) {
paginateQuery.tid = filters.tid
}
// emotion
if (!_isUndefined(filters.emotion)) {
paginateQuery.emotion = filters.emotion
}
// marked
if (!_isUndefined(filters.marked)) {
paginateQuery.marked = numberToBoolean(filters.marked)
}
// search
if (filters.keyword) {
const trimmed = _trim(filters.keyword)
const keywordRegExp = new RegExp(trimmed, 'i')
paginateQuery.$or = [
{ content: keywordRegExp },
{ user_name: keywordRegExp },
{ user_email: keywordRegExp },
{ remark: keywordRegExp }
]
}
return this.feedbackService.paginator(paginateQuery, paginateOptions)
}
@Post()
@Throttle({ default: { ttl: seconds(30), limit: 5 } })
@Responser.handle('Create feedback')
async createFeedback(
@Body() feedback: FeedbackBase,
@QueryParams() { visitor }: QueryParamsResult
): Promise<Feedback> {
const result = await this.feedbackService.create(feedback, visitor)
const subject = `You have a new feedback`
const texts = [
`${subject} on ${result.tid}.`,
`Author: ${result.user_name || 'Anonymous user'}`,
`Emotion: ${result.emotion_emoji} ${result.emotion_text} (${result.emotion})`,
`Feedback: ${result.content}`
]
this.emailService.sendMailAs(APP_CONFIG.APP.FE_NAME, {
to: APP_CONFIG.APP.ADMIN_EMAIL,
subject,
text: texts.join('\n'),
html: texts.map((text) => `<p>${text}</p>`).join('\n')
})
return result
}
@Delete()
@UseGuards(AdminOnlyGuard)
@Responser.handle('Delete feedbacks')
deleteFeedbacks(@Body() body: FeedbacksDTO) {
return this.feedbackService.batchDelete(body.feedback_ids)
}
@Put(':id')
@UseGuards(AdminOnlyGuard)
@Responser.handle('Update feedback')
putFeedback(@QueryParams() { params }: QueryParamsResult, @Body() feedback: Feedback): Promise<Feedback> {
return this.feedbackService.update(params.id, feedback)
}
@Delete(':id')
@UseGuards(AdminOnlyGuard)
@Responser.handle('Delete feedback')
deleteFeedback(@QueryParams() { params }: QueryParamsResult) {
return this.feedbackService.delete(params.id)
}
}
``` | /content/code_sandbox/src/modules/feedback/feedback.controller.ts | xml | 2016-02-13T08:16:02 | 2024-08-12T08:34:20 | nodepress | surmon-china/nodepress | 1,421 | 963 |
```xml
import { Contract, ISimpleTxForm, ITxConfig, ITxReceipt, Network, StoreAccount } from '@types';
export enum ABIItemType {
FUNCTION = 'function',
EVENT = 'event',
CONSTRUCTOR = 'constructor'
}
// @todo: Add remaining types / use string insteand of enum
export enum ABIFieldType {
STRING = 'string',
BOOL = 'bool',
UINT8 = 'uint8',
UINT256 = 'uint256',
ADDRESS = 'address'
}
export interface ABIField {
name: string;
type: ABIFieldType;
value?: string;
indexed?: boolean;
displayName?: string;
}
export enum StateMutabilityType {
PURE = 'pure ',
VIEW = 'view',
NONPAYABLE = 'nonpayable',
PAYABLE = 'payable'
}
export interface ABIItem {
stateMutability?: StateMutabilityType;
name: string;
type: ABIItemType;
payable?: boolean; // Deprecated, use stateMutability
constant?: boolean; // Deprecated, use stateMutability
anonymous?: boolean;
payAmount: string;
inputs: ABIField[];
outputs: ABIField[];
}
export interface InteractWithContractState extends Omit<ISimpleTxForm, 'account'> {
network: Network;
contractAddress: string;
contract: Contract | undefined;
contracts: Contract[];
abi: string;
customContractName: string;
showGeneratedForm: boolean;
submitedFunction: ABIItem;
data: string;
txConfig: ITxConfig;
txReceipt: ITxReceipt | undefined;
addressOrDomainInput: string;
account?: StoreAccount;
}
``` | /content/code_sandbox/src/features/InteractWithContracts/types.ts | xml | 2016-12-04T01:35:27 | 2024-08-14T21:41:58 | MyCrypto | MyCryptoHQ/MyCrypto | 1,347 | 363 |
```xml
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<dataset>
<metadata>
<column name="name" />
<column name="type" />
<column name="props" />
</metadata>
</dataset>
``` | /content/code_sandbox/test/e2e/sql/src/test/resources/cases/rql/dataset/dbtbl_with_readwrite_splitting/show_unused_sharding_auditors.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 110 |
```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 { ComponentFixture, TestBed } from '@angular/core/testing';
import { AdapterEditerComponent } from './adapter-editer.component';
describe('AdapterEditerComponent', () => {
let component: AdapterEditerComponent;
let fixture: ComponentFixture<AdapterEditerComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ AdapterEditerComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AdapterEditerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
``` | /content/code_sandbox/maxkey-web-frontend/maxkey-web-mgt-app/src/app/routes/config/adapters/adapter-editer/adapter-editer.component.spec.ts | xml | 2016-11-16T03:06:50 | 2024-08-16T09:22:42 | MaxKey | dromara/MaxKey | 1,423 | 173 |
```xml
import { expect } from 'vitest';
import { toOutput } from './matchers';
interface ToOutputMatchers<R = unknown> {
toOutput: (test: string, timeout?: number) => Promise<R>;
}
declare module 'vitest' {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Assertion<T = any> extends ToOutputMatchers<T> {}
}
expect.extend({ toOutput });
``` | /content/code_sandbox/packages/cli/test/mocks/matchers/index.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 88 |
```xml
import { find } from '@microsoft/sp-lodash-subset';
import { IWebPartContext } from '@microsoft/sp-webpart-base';
export class VisioService {
private _webPartContext: IWebPartContext;
private _url = "";
/**
* gets the url of the Visio document to embed
* @returns a string with the document url
*/
get url(): string {
return this._url;
}
/**
* sets the url of the Visio document to embed
* @param url the url of the document
*/
set url(url: string) {
// apis are enabled for EmbedView action only
url = url.replace("action=view", "action=embedview");
url = url.replace("action=interactivepreview", "action=embedview");
url = url.replace("action=default", "action=embedview");
url = url.replace("action=edit", "action=embedview");
this._url = url;
}
private _session: OfficeExtension.EmbeddedSession = null;
private _shapes: Visio.Shape[] = [];
private _selectedShape: Visio.Shape;
private _documentLoadComplete = false;
private _pageLoadComplete = false;
/**
* gets a pre-loaded collection of relevant shapes from the diagram
*/
public get shapes(): Visio.Shape[] {
return this._shapes;
}
// delegate functions passed from the react component
public onSelectionChanged: (selectedShape: Visio.Shape) => void;
public getAllShapes: (shapes: Visio.Shape[]) => void;
/**
* class constructor
* @param webPartContext the context of the web part
*/
constructor(webPartContext: IWebPartContext) {
// set web part context
this._webPartContext = webPartContext;
}
/**
* initialize session by embedding the Visio diagram on the page
* @returns returns a promise
*/
private async _init(): Promise<any> {
// initialize communication between the developer frame and the Visio Online frame
this._session = new OfficeExtension.EmbeddedSession(
this._url, {
id: "embed-iframe",
container: document.getElementById("iframeHost"),
width: "100%",
height: "600px"
}
);
await this._session.init();
console.log("Session successfully initialized");
}
/**
* function to add custom event handlers
* @returns returns a promise
*/
private _addCustomEventHandlers = async (): Promise<any> => {
try {
await Visio.run(this._session, async (context: Visio.RequestContext) => {
var doc: Visio.Document = context.document;
// on document load complete
const onDocumentLoadCompleteEventResult: OfficeExtension.EventHandlerResult<Visio.DocumentLoadCompleteEventArgs> =
doc.onDocumentLoadComplete.add(
this._onDocumentLoadComplete
);
// on page load complete
const onPageLoadCompleteEventResult: OfficeExtension.EventHandlerResult<Visio.PageLoadCompleteEventArgs> =
doc.onPageLoadComplete.add(
this._onPageLoadComplete
);
// on selection changed
const onSelectionChangedEventResult: OfficeExtension.EventHandlerResult<Visio.SelectionChangedEventArgs> =
doc.onSelectionChanged.add(
this._onSelectionChanged
);
await context.sync();
console.log("Document Load Complete handler attached");
});
} catch (error) {
this.logError(error);
}
}
/**
* method executed after a on document load complete event is triggered
* @param args event arguments
* @returns returns a promise
*/
private _onDocumentLoadComplete = async (args: Visio.DocumentLoadCompleteEventArgs): Promise<void> => {
// only execute if not executed yet
if (!this._documentLoadComplete) {
try {
console.log("Document Loaded Event: " + JSON.stringify(args));
// set internal flag to prevent event from running again if triggered twice
this._documentLoadComplete = true;
await Visio.run(this._session, async (context: Visio.RequestContext) => {
var doc: Visio.Document = context.document;
// disable Hyperlinks on embed diagram
doc.view.disableHyperlinks = true;
// hide diagram boundary on embed diagram
doc.view.hideDiagramBoundary = true;
await context.sync();
});
} catch (error) {
this.logError(error);
}
}
}
/**
* method executed after a on page load event is triggered
* @param args event arguments
* @returns returns a promise
*/
private _onPageLoadComplete = async (args: Visio.PageLoadCompleteEventArgs): Promise<void> => {
// only execute if not executed yet
if (!this._pageLoadComplete) {
try {
console.log("Page Loaded Event: " + JSON.stringify(args));
// set internal flag to prevent event from running again if triggered twice
this._pageLoadComplete = true;
// get all relevant shapes and populate the class variable
this._shapes = await this._getAllShapes();
// call delegate function from the react component
this.getAllShapes(this._shapes);
} catch (error) {
this.logError(error);
}
}
}
/**
* method executed after a on selection change event is triggered
* @param args event arguments
* @returns returns a promise
*/
private _onSelectionChanged = async (args: Visio.SelectionChangedEventArgs): Promise<void> => {
try {
console.log("Selection Changed Event " + JSON.stringify(args));
if (args.shapeNames.length > 0 && this._shapes && this._shapes.length > 0) {
// get name of selected item
const selectedShapeText: string = args.shapeNames[0];
// find selected shape on the list of pre-loaded shapes
this._selectedShape = find(this._shapes,
s => s.name === selectedShapeText
);
// call delegate function from the react component
this.onSelectionChanged(this._selectedShape);
} else {
// shape was deselected
this._selectedShape = null;
}
} catch (error) {
this.logError(error);
}
}
/**
* select a shape on the visio diagram
* @param name the name of the shape to select
*/
public selectShape = async (name: string): Promise<void> => {
try {
// find the correct shape from the pre-loaded list of shapes
// check the ShapeData item with the 'Name' key
const shape: Visio.Shape = find(this._shapes,
s => (find(s.shapeDataItems.items, i => i.label === "Name").value === name)
);
// only select shape if not the currently selected one
if (this._selectedShape === null
|| this._selectedShape === undefined
|| (this._selectedShape && this._selectedShape.name !== shape.name)) {
await Visio.run(this._session, async (context: Visio.RequestContext) => {
const page: Visio.Page = context.document.getActivePage();
const shapesCollection: Visio.ShapeCollection = page.shapes;
shapesCollection.load();
await context.sync();
const diagramShape: Visio.Shape = shapesCollection.getItem(shape.name);
// select shape on diagram
diagramShape.select = true;
await context.sync();
console.log(`Selected shape '${shape.name}' in diagram`);
this._selectedShape = shape;
});
} else {
console.log(`Shape '${shape.name}' is already selected in diagram`);
}
} catch (error) {
this.logError(error);
}
}
/**
* get all shapes from page
* @returns returns a promise
*/
private _getAllShapes = async (): Promise<Visio.Shape[]> => {
console.log("Getting all shapes");
try {
let shapes: Visio.Shape[];
await Visio.run(this._session, async (context: Visio.RequestContext) => {
const page: Visio.Page = context.document.getActivePage();
const shapesCollection: Visio.ShapeCollection = page.shapes;
shapesCollection.load();
await context.sync();
// load all required properties for each shape
for (let i: number = 0; i < shapesCollection.items.length; i++) {
shapesCollection.items[i].shapeDataItems.load();
shapesCollection.items[i].hyperlinks.load();
}
await context.sync();
shapes = shapesCollection.items;
return shapes;
});
return shapes;
} catch (error) {
this.logError(error);
}
}
/**
* initializes the embed session and attaches event handlers
* this is the function that should be called to start the session
* @param docUrl embed url of the document
* @returns returns a promise
*/
public load = async (docUrl: string): Promise<void> => {
console.log("Start loading Visio data");
try {
// sets the url, modifying it if required - uses set method to re-use logic
this.url = docUrl;
// init
await this._init();
// add custom onDocumentLoadComplete event handler
await this._addCustomEventHandlers();
// trigger document and page loaded event handlers manually as sometimes Visio fails to trigger them
// we are sending a null event, which is fine in this case as we don't need any of the event data
// this is randomly happening on chrome, but seems to always fail on IE...
// this._onDocumentLoadComplete(null);
// this._onPageLoadComplete(null);
} catch (error) {
this.logError(error);
}
}
/**
* generate embed url for a document
* @param docId the list item ID of the target document
*/
private generateEmbedUrl = async (itemProperties: any): Promise<string> => {
let url: string = "";
try {
// check if data was returned
if (itemProperties) {
// generate required URL
const siteUrl: string = this._webPartContext.pageContext.site.absoluteUrl;
const sourceDoc: string = encodeURIComponent(itemProperties.File.ContentTag.split(",")[0]);
const fileName: string = encodeURIComponent(itemProperties.File.Name);
if (siteUrl && sourceDoc && fileName) {
url = `${siteUrl}/_layouts/15/Doc.aspx?sourcedoc=${sourceDoc}&file=${fileName}&action=default`;
}
}
} catch (error) {
console.error(error);
}
return url;
}
/**
* log error
* @param error error object
*/
private logError = (error: any): void => {
console.error("Error");
if (error instanceof OfficeExtension.Error) {
console.error("Debug info: ", JSON.stringify(error.debugInfo));
} else {
console.error(error);
}
}
}
``` | /content/code_sandbox/samples/react-visio/src/shared/services/VisioService.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 2,372 |
```xml
import { bold, cyan, red, yellow } from './picocolors'
import path from 'path'
import { hasNecessaryDependencies } from './has-necessary-dependencies'
import type { NecessaryDependencies } from './has-necessary-dependencies'
import semver from 'next/dist/compiled/semver'
import { CompileError } from './compile-error'
import * as log from '../build/output/log'
import { getTypeScriptIntent } from './typescript/getTypeScriptIntent'
import type { TypeCheckResult } from './typescript/runTypeCheck'
import { writeAppTypeDeclarations } from './typescript/writeAppTypeDeclarations'
import { writeConfigurationDefaults } from './typescript/writeConfigurationDefaults'
import { installDependencies } from './install-dependencies'
import { isCI } from '../telemetry/ci-info'
import { missingDepsError } from './typescript/missingDependencyError'
const requiredPackages = [
{
file: 'typescript/lib/typescript.js',
pkg: 'typescript',
exportsRestrict: true,
},
{
file: '@types/react/index.d.ts',
pkg: '@types/react',
exportsRestrict: true,
},
{
file: '@types/node/index.d.ts',
pkg: '@types/node',
exportsRestrict: true,
},
]
export async function verifyTypeScriptSetup({
dir,
distDir,
cacheDir,
intentDirs,
tsconfigPath,
typeCheckPreflight,
disableStaticImages,
hasAppDir,
hasPagesDir,
}: {
dir: string
distDir: string
cacheDir?: string
tsconfigPath: string
intentDirs: string[]
typeCheckPreflight: boolean
disableStaticImages: boolean
hasAppDir: boolean
hasPagesDir: boolean
}): Promise<{ result?: TypeCheckResult; version: string | null }> {
const resolvedTsConfigPath = path.join(dir, tsconfigPath)
try {
// Check if the project uses TypeScript:
const intent = await getTypeScriptIntent(dir, intentDirs, tsconfigPath)
if (!intent) {
return { version: null }
}
// Ensure TypeScript and necessary `@types/*` are installed:
let deps: NecessaryDependencies = await hasNecessaryDependencies(
dir,
requiredPackages
)
if (deps.missing?.length > 0) {
if (isCI) {
// we don't attempt auto install in CI to avoid side-effects
// and instead log the error for installing needed packages
missingDepsError(dir, deps.missing)
}
console.log(
bold(
yellow(
`It looks like you're trying to use TypeScript but do not have the required package(s) installed.`
)
) +
'\n' +
'Installing dependencies' +
'\n\n' +
bold(
'If you are not trying to use TypeScript, please remove the ' +
cyan('tsconfig.json') +
' file from your package root (and any TypeScript files in your pages directory).'
) +
'\n'
)
await installDependencies(dir, deps.missing, true).catch((err) => {
if (err && typeof err === 'object' && 'command' in err) {
console.error(
`Failed to install required TypeScript dependencies, please install them manually to continue:\n` +
(err as any).command +
'\n'
)
}
throw err
})
deps = await hasNecessaryDependencies(dir, requiredPackages)
}
// Load TypeScript after we're sure it exists:
const tsPath = deps.resolved.get('typescript')!
const ts = (await Promise.resolve(
require(tsPath)
)) as typeof import('typescript')
if (semver.lt(ts.version, '4.5.2')) {
log.warn(
`Minimum recommended TypeScript version is v4.5.2, older versions can potentially be incompatible with Next.js. Detected: ${ts.version}`
)
}
// Reconfigure (or create) the user's `tsconfig.json` for them:
await writeConfigurationDefaults(
ts,
resolvedTsConfigPath,
intent.firstTimeSetup,
hasAppDir,
distDir,
hasPagesDir
)
// Write out the necessary `next-env.d.ts` file to correctly register
// Next.js' types:
await writeAppTypeDeclarations({
baseDir: dir,
imageImportsEnabled: !disableStaticImages,
hasPagesDir,
hasAppDir,
})
let result
if (typeCheckPreflight) {
const { runTypeCheck } = require('./typescript/runTypeCheck')
// Verify the project passes type-checking before we go to webpack phase:
result = await runTypeCheck(
ts,
dir,
distDir,
resolvedTsConfigPath,
cacheDir,
hasAppDir
)
}
return { result, version: ts.version }
} catch (err) {
// These are special errors that should not show a stack trace:
if (err instanceof CompileError) {
console.error(red('Failed to compile.\n'))
console.error(err.message)
process.exit(1)
}
/**
* verifyTypeScriptSetup can be either invoked directly in the main thread (during next dev / next lint)
* or run in a worker (during next build). In the latter case, we need to print the error message, as the
* parent process will only receive an `Jest worker encountered 1 child process exceptions, exceeding retry limit`.
*/
// we are in a worker, print the error message and exit the process
if (process.env.JEST_WORKER_ID) {
if (err instanceof Error) {
console.error(err.message)
} else {
console.error(err)
}
process.exit(1)
}
// we are in the main thread, throw the error and it will be handled by the caller
throw err
}
}
``` | /content/code_sandbox/packages/next/src/lib/verify-typescript-setup.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 1,290 |
```xml
import * as vscode from 'vscode';
import { HoverRequest, LanguageClient } from 'vscode-languageclient';
export class SignatureHelpProvider implements vscode.SignatureHelpProvider {
private languageClient: LanguageClient;
private previousFunctionPosition?: vscode.Position;
constructor(lc: LanguageClient) {
this.languageClient = lc;
}
public provideSignatureHelp(
document: vscode.TextDocument,
position: vscode.Position,
token: vscode.CancellationToken,
context: vscode.SignatureHelpContext,
): vscode.ProviderResult<vscode.SignatureHelp> {
// the current signature help provider uses the hover information from RLS
// and it only has a string representation of the function signature.
// This check makes sure we can easily show the tooltip for multiple parameters, separated by `,`
if (context.triggerCharacter === '(') {
this.previousFunctionPosition = position;
return this.provideHover(
this.languageClient,
document,
position,
token,
).then(hover => this.hoverToSignatureHelp(hover, position, document));
} else if (context.triggerCharacter === ',') {
if (
this.previousFunctionPosition &&
position.line === this.previousFunctionPosition.line
) {
return this.provideHover(
this.languageClient,
document,
this.previousFunctionPosition,
token,
).then(hover => this.hoverToSignatureHelp(hover, position, document));
} else {
return null;
}
} else {
if (context.isRetrigger === false) {
this.previousFunctionPosition = undefined;
}
return null;
}
}
private provideHover(
lc: LanguageClient,
document: vscode.TextDocument,
position: vscode.Position,
token: vscode.CancellationToken,
): Promise<vscode.Hover> {
return new Promise((resolve, reject) => {
lc.sendRequest(
HoverRequest.type,
lc.code2ProtocolConverter.asTextDocumentPositionParams(
document,
position.translate(0, -1),
),
token,
).then(
data => resolve(lc.protocol2CodeConverter.asHover(data)),
error => reject(error),
);
});
}
private hoverToSignatureHelp(
hover: vscode.Hover,
position: vscode.Position,
document: vscode.TextDocument,
): vscode.SignatureHelp | undefined {
/*
The contents of a hover result has the following structure:
contents:Array[2]
0:Object
value:"
```rust
pub fn write(output: &mut dyn Write, args: Arguments) -> Result
```
"
1:Object
value:"The `write` function takes an output stream, and an `Arguments` struct
that can be precompiled with the `format_args!` macro.
The arguments will be formatted according to the specified format string
into the output stream provided.
# Examples
RLS uses the function below to create the tooltip contents shown above:
fn create_tooltip(
the_type: String,
doc_url: Option<String>,
context: Option<String>,
docs: Option<String>,
) -> Vec<MarkedString> {}
This means the first object is the type - function signature,
but for the following, there is no way of certainly knowing which is the
function documentation that we want to display in the tooltip.
Assuming the context is never populated for a function definition (this might be wrong
and needs further validation, but initial tests show it to hold true in most cases), and
we also assume that most functions contain rather documentation, than just a URL without
any inline documentation, we check the length of contents, and we assume that if there are:
- two objects, they are the signature and docs, and docs is contents[1]
- three objects, they are the signature, URL and docs, and docs is contents[2]
- four objects -- all of them, docs is contents[3]
See path_to_url#L487-L508.
*/
// we remove the markdown formatting for the label, as it only accepts strings
const label = (hover.contents[0] as vscode.MarkdownString).value
.replace('```rust', '')
.replace('```', '');
// the signature help tooltip is activated on `(` or `,`
// here we make sure the label received is for a function,
// and that we are not showing the hover for the same line
// where we are declaring a function.
if (
!label.includes('fn') ||
document.lineAt(position.line).text.includes('fn ')
) {
return undefined;
}
const doc =
hover.contents.length > 1
? (hover.contents.slice(-1)[0] as vscode.MarkdownString)
: undefined;
const si = new vscode.SignatureInformation(label, doc);
// without parsing the function definition, we don't have a way to get more info on parameters.
// If RLS supports signature help requests in the future, we can update this.
si.parameters = [];
const sh = new vscode.SignatureHelp();
sh.signatures[0] = si;
sh.activeSignature = 0;
return sh;
}
}
``` | /content/code_sandbox/src/providers/signatureHelpProvider.ts | xml | 2016-09-02T22:57:33 | 2024-07-31T15:03:56 | vscode-rust | rust-lang/vscode-rust | 1,388 | 1,120 |
```xml
<resources>
<item name="ic_menu_delete" type="drawable">@android:drawable/ic_menu_delete</item>
<item name="ic_menu_gallery" type="drawable">@android:drawable/ic_menu_gallery</item>
<item name="ic_menu_slideshow" type="drawable">@android:drawable/ic_menu_slideshow</item>
<item name="ic_menu_manage" type="drawable">@android:drawable/ic_menu_manage</item>
<item name="ic_menu_share" type="drawable">@android:drawable/ic_menu_share</item>
<item name="ic_menu_send" type="drawable">@android:drawable/ic_menu_send</item>
<item name="cl_inspeckage" type="drawable">#375a7f</item>
</resources>
``` | /content/code_sandbox/app/src/main/res/values/drawables.xml | xml | 2016-02-28T22:59:51 | 2024-08-15T00:26:58 | Inspeckage | ac-pm/Inspeckage | 2,789 | 163 |
```xml
export * from '@storybook/core/index';
export type * from '@storybook/core/index';
``` | /content/code_sandbox/code/lib/cli/core/index.d.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 18 |
```xml
import ContactsDAO from './sql';
export default () => ({
Query: {
async report(obj: any, arg: any, { Contacts }: { Contacts: ContactsDAO }) {
return Contacts.getContacts();
},
},
});
``` | /content/code_sandbox/modules/reports/server-ts/resolvers.ts | xml | 2016-09-08T16:44:45 | 2024-08-16T06:17:16 | apollo-universal-starter-kit | sysgears/apollo-universal-starter-kit | 1,684 | 49 |
```xml
<Project>
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
</PropertyGroup>
<PropertyGroup Label="Package Versions">
<BenchmarkDotNetPackageVersion>0.10.13</BenchmarkDotNetPackageVersion>
<GoogleProtobufPackageVersion>3.1.0</GoogleProtobufPackageVersion>
<InternalAspNetCoreAnalyzersPackageVersion>3.0.0-preview-181113-11</InternalAspNetCoreAnalyzersPackageVersion>
<InternalAspNetCoreSdkPackageVersion>3.0.0-build-20181114.5</InternalAspNetCoreSdkPackageVersion>
<MessagePackPackageVersion>1.7.3.4</MessagePackPackageVersion>
<MicrosoftAspNetCoreAppPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreAppPackageVersion>
<MicrosoftAspNetCoreAuthenticationCookiesPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreAuthenticationCookiesPackageVersion>
<MicrosoftAspNetCoreAuthenticationCorePackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreAuthenticationCorePackageVersion>
<MicrosoftAspNetCoreAuthenticationJwtBearerPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreAuthenticationJwtBearerPackageVersion>
<MicrosoftAspNetCoreAuthorizationPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreAuthorizationPackageVersion>
<MicrosoftAspNetCoreAuthorizationPolicyPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreAuthorizationPolicyPackageVersion>
<MicrosoftAspNetCoreBenchmarkRunnerSourcesPackageVersion>3.0.0-preview-181113-11</MicrosoftAspNetCoreBenchmarkRunnerSourcesPackageVersion>
<MicrosoftAspNetCoreConnectionsAbstractionsPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreConnectionsAbstractionsPackageVersion>
<MicrosoftAspNetCoreCorsPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreCorsPackageVersion>
<MicrosoftAspNetCoreDiagnosticsEntityFrameworkCorePackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreDiagnosticsEntityFrameworkCorePackageVersion>
<MicrosoftAspNetCoreDiagnosticsPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreDiagnosticsPackageVersion>
<MicrosoftAspNetCoreHostingAbstractionsPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreHostingAbstractionsPackageVersion>
<MicrosoftAspNetCoreHostingPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreHostingPackageVersion>
<MicrosoftAspNetCoreHttpAbstractionsPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreHttpAbstractionsPackageVersion>
<MicrosoftAspNetCoreHttpFeaturesPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreHttpFeaturesPackageVersion>
<MicrosoftAspNetCoreHttpPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreHttpPackageVersion>
<MicrosoftAspNetCoreIdentityEntityFrameworkCorePackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreIdentityEntityFrameworkCorePackageVersion>
<MicrosoftAspNetCoreMvcPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreMvcPackageVersion>
<MicrosoftAspNetCoreRoutingPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreRoutingPackageVersion>
<MicrosoftAspNetCoreServerIISIntegrationPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreServerIISIntegrationPackageVersion>
<MicrosoftAspNetCoreServerKestrelPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreServerKestrelPackageVersion>
<MicrosoftAspNetCoreStaticFilesPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreStaticFilesPackageVersion>
<MicrosoftAspNetCoreTestHostPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreTestHostPackageVersion>
<MicrosoftAspNetCoreTestingPackageVersion>3.0.0-preview-181113-11</MicrosoftAspNetCoreTestingPackageVersion>
<MicrosoftAspNetCoreWebSocketsPackageVersion>3.0.0-alpha1-10742</MicrosoftAspNetCoreWebSocketsPackageVersion>
<MicrosoftCSharpPackageVersion>4.6.0-preview1-26907-04</MicrosoftCSharpPackageVersion>
<MicrosoftEntityFrameworkCoreDesignPackageVersion>3.0.0-preview-181109-02</MicrosoftEntityFrameworkCoreDesignPackageVersion>
<MicrosoftEntityFrameworkCoreSqlServerPackageVersion>3.0.0-preview-181109-02</MicrosoftEntityFrameworkCoreSqlServerPackageVersion>
<MicrosoftEntityFrameworkCoreToolsPackageVersion>3.0.0-preview-181109-02</MicrosoftEntityFrameworkCoreToolsPackageVersion>
<MicrosoftExtensionsBuffersTestingSourcesPackageVersion>3.0.0-alpha1-10727</MicrosoftExtensionsBuffersTestingSourcesPackageVersion>
<MicrosoftExtensionsClosedGenericMatcherSourcesPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsClosedGenericMatcherSourcesPackageVersion>
<MicrosoftExtensionsCommandLineUtilsSourcesPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsCommandLineUtilsSourcesPackageVersion>
<MicrosoftExtensionsConfigurationCommandLinePackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsConfigurationCommandLinePackageVersion>
<your_sha256_hashon>3.0.0-preview-181113-11</your_sha256_hashon>
<MicrosoftExtensionsConfigurationUserSecretsPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsConfigurationUserSecretsPackageVersion>
<your_sha256_hash>3.0.0-preview-181113-11</your_sha256_hash>
<MicrosoftExtensionsDependencyInjectionPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsDependencyInjectionPackageVersion>
<MicrosoftExtensionsLoggingAbstractionsPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsLoggingAbstractionsPackageVersion>
<MicrosoftExtensionsLoggingConfigurationPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsLoggingConfigurationPackageVersion>
<MicrosoftExtensionsLoggingConsolePackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsLoggingConsolePackageVersion>
<MicrosoftExtensionsLoggingDebugPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsLoggingDebugPackageVersion>
<MicrosoftExtensionsLoggingPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsLoggingPackageVersion>
<MicrosoftExtensionsLoggingTestingPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsLoggingTestingPackageVersion>
<MicrosoftExtensionsObjectMethodExecutorSourcesPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsObjectMethodExecutorSourcesPackageVersion>
<MicrosoftExtensionsOptionsPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsOptionsPackageVersion>
<MicrosoftExtensionsSecurityHelperSourcesPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsSecurityHelperSourcesPackageVersion>
<MicrosoftExtensionsValueStopwatchSourcesPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsValueStopwatchSourcesPackageVersion>
<MicrosoftExtensionsWebEncodersSourcesPackageVersion>3.0.0-preview-181113-11</MicrosoftExtensionsWebEncodersSourcesPackageVersion>
<MicrosoftNETCoreAppPackageVersion>3.0.0-preview1-26907-05</MicrosoftNETCoreAppPackageVersion>
<MicrosoftNETTestSdkPackageVersion>15.6.1</MicrosoftNETTestSdkPackageVersion>
<MoqPackageVersion>4.10.0</MoqPackageVersion>
<NETStandardLibrary20PackageVersion>2.0.3</NETStandardLibrary20PackageVersion>
<NewtonsoftJsonPackageVersion>11.0.2</NewtonsoftJsonPackageVersion>
<StackExchangeRedisPackageVersion>2.0.513</StackExchangeRedisPackageVersion>
<SystemBuffersPackageVersion>4.6.0-preview1-26907-04</SystemBuffersPackageVersion>
<SystemIOPipelinesPackageVersion>4.6.0-preview1-26907-04</SystemIOPipelinesPackageVersion>
<SystemMemoryPackageVersion>4.6.0-preview1-26717-04</SystemMemoryPackageVersion>
<SystemNumericsVectorsPackageVersion>4.6.0-preview1-26907-04</SystemNumericsVectorsPackageVersion>
<SystemReactiveLinqPackageVersion>3.1.1</SystemReactiveLinqPackageVersion>
<SystemReflectionEmitPackageVersion>4.3.0</SystemReflectionEmitPackageVersion>
<SystemRuntimeCompilerServicesUnsafePackageVersion>4.6.0-preview1-26907-04</SystemRuntimeCompilerServicesUnsafePackageVersion>
<SystemSecurityPrincipalWindowsPackageVersion>4.6.0-preview1-26907-04</SystemSecurityPrincipalWindowsPackageVersion>
<SystemThreadingChannelsPackageVersion>4.6.0-preview1-26907-04</SystemThreadingChannelsPackageVersion>
<SystemThreadingTasksExtensionsPackageVersion>4.6.0-preview1-26907-04</SystemThreadingTasksExtensionsPackageVersion>
<XunitAssertPackageVersion>2.3.1</XunitAssertPackageVersion>
<XunitExtensibilityCorePackageVersion>2.3.1</XunitExtensibilityCorePackageVersion>
<XunitPackageVersion>2.3.1</XunitPackageVersion>
<XunitRunnerVisualStudioPackageVersion>2.4.0</XunitRunnerVisualStudioPackageVersion>
</PropertyGroup>
<Import Project="$(DotNetPackageVersionPropsPath)" Condition=" '$(DotNetPackageVersionPropsPath)' != '' " />
<PropertyGroup Label="Package Versions: Pinned" />
</Project>
``` | /content/code_sandbox/build/dependencies.props | xml | 2016-10-17T16:39:15 | 2024-08-15T16:33:14 | SignalR | aspnet/SignalR | 2,383 | 2,114 |
```xml
import { pod } from './pod';
import { name } from './name';
import { image } from './image';
import { imagePullPolicy } from './imagePullPolicy';
import { status } from './status';
import { node } from './node';
import { podIp } from './podIp';
import { creationDate } from './creationDate';
import { getActions } from './actions';
export function getColumns(isServerMetricsEnabled: boolean) {
return [
pod,
name,
image,
imagePullPolicy,
status,
node,
podIp,
creationDate,
getActions(isServerMetricsEnabled),
];
}
``` | /content/code_sandbox/app/react/kubernetes/applications/DetailsView/ApplicationContainersDatatable/columns/index.ts | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 136 |
```xml
import * as React from 'react';
import { Steps } from 'storywright';
import { TestWrapperDecorator, StoryWrightDecorator } from '../../utilities';
import { Fabric, SpinButton, ISpinButtonProps, TextField, ITextFieldStyles } from '@fluentui/react';
import { Position } from '@fluentui/react/lib/Positioning';
const props: ISpinButtonProps = {
defaultValue: '0',
label: 'Basic SpinButton:',
min: 0,
max: 0,
step: 1,
};
const textFieldStyles: Partial<ITextFieldStyles> = {
root: { width: 250, display: 'inline-block' },
};
const iconProps = { iconName: 'IncreaseIndentLegacy' };
export default {
title: 'SpinButton',
decorators: [
TestWrapperDecorator,
StoryWrightDecorator(new Steps().snapshot('default', { cropTo: '.testWrapper' }).end()),
],
};
export const LabelOnTop = () => (
<Fabric>
<SpinButton
{...props}
styles={{ root: { width: 120, display: 'inline-block' } }}
labelPosition={Position.top}
/>
{/* DO NOT delete this TextField! It's here to verify that the SpinButton's field and label
vertically align with other form components (this positioning can get messed up since
SpinButton's optional icon is 1px larger than the label line height). */}
<TextField
label="Should vertically align with SpinButton"
placeholder="(verify field and label alignment)"
styles={textFieldStyles}
/>
</Fabric>
);
LabelOnTop.storyName = 'Label on top';
export const LabelOnTopWithIcon = () => (
<Fabric>
<SpinButton
{...props}
styles={{ root: { width: 150, display: 'inline-block' } }}
labelPosition={Position.top}
iconProps={iconProps}
/>
{/* DO NOT delete this TextField! It's here to verify that the SpinButton's field and label
vertically align with other form components (this positioning can get messed up since
SpinButton's optional icon is 1px larger than the label line height). */}
<TextField
label="Should vertically align with SpinButton"
placeholder="(verify field and label alignment)"
styles={textFieldStyles}
/>
</Fabric>
);
LabelOnTopWithIcon.storyName = 'Label on top with icon';
``` | /content/code_sandbox/apps/vr-tests/src/stories/Button/SpinButtonLabelOnTop.stories.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 521 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>$(CurrentTargetFramework)</TargetFramework>
<OutputType>Exe</OutputType>
<RunArguments>"Argument Specified in Props"</RunArguments>
</PropertyGroup>
</Project>
``` | /content/code_sandbox/test/TestAssets/TestProjects/WatchHotReloadAppCustomHost/WatchHotReloadApp.csproj | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 63 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\..\buildtools\common.props" />
<PropertyGroup>
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<Description>Common code for the AWS .NET Core Lambda Mock Test Tool.</Description>
<NoWarn>1701;1702;1591;1587;3021;NU5100;CS1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.Core" Version="2.2.0" />
<PackageReference Include="AWSSDK.SSO" Version="3.7.300.80" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="3.7.301.75" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="YamlDotNet.Signed" Version="5.2.1" />
<PackageReference Include="AWSSDK.Core" Version="3.7.303.20" />
<PackageReference Include="AWSSDK.SQS" Version="3.7.300.80" />
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'PackNET60' ">
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'PackNET70' ">
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'PackNET80' ">
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net6.0' ">
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="6.0.0" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net7.0' ">
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="7.0.0" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' ">
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="8.0.0-rc.2.23479.6" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\**" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/Tools/LambdaTestTool/src/Amazon.Lambda.TestTool/Amazon.Lambda.TestTool.csproj | xml | 2016-11-11T20:43:34 | 2024-08-15T16:57:53 | aws-lambda-dotnet | aws/aws-lambda-dotnet | 1,558 | 549 |
```xml
import { ComponentType, FC } from 'react';
import { WALLET_STEPS } from '@components';
import { useNetworks } from '@services/Store';
import { ISignComponentProps, ISignedTx, IStepComponentProps, ITxReceipt, WalletId } from '@types';
type Props = Pick<IStepComponentProps, 'txConfig' | 'onComplete'> & {
protectTxButton?(): JSX.Element;
};
const SignTransaction: FC<Props> = ({ txConfig, onComplete, protectTxButton }: Props) => {
const {
networkId,
senderAccount: { wallet: walletName }
} = txConfig;
const { getNetworkById } = useNetworks();
const network = getNetworkById(networkId);
const getWalletComponent = (walletType: WalletId) => {
return WALLET_STEPS[walletType];
};
const WalletComponent: ComponentType<ISignComponentProps> = getWalletComponent(walletName)!;
return (
<>
<WalletComponent
network={network}
senderAccount={txConfig.senderAccount}
rawTransaction={txConfig.rawTransaction}
onSuccess={(payload: ITxReceipt | ISignedTx) => onComplete(payload)}
/>
{protectTxButton && protectTxButton()}
</>
);
};
export default SignTransaction;
``` | /content/code_sandbox/src/features/SendAssets/components/SignTransaction.tsx | xml | 2016-12-04T01:35:27 | 2024-08-14T21:41:58 | MyCrypto | MyCryptoHQ/MyCrypto | 1,347 | 279 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:paddingVertical="5dp"
android:paddingStart="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:clickable="true"
android:focusable="true"
android:background="?android:attr/selectableItemBackground">
<TextView
android:id="@+id/icon_category"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp" />
<ImageView
android:id="@+id/icon_category_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_outline_expand_more_24"
app:tint="?attr/colorOnSurfaceVariant"
android:layout_gravity="center_vertical" />
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/card_icon_category.xml | xml | 2016-08-15T19:10:31 | 2024-08-16T19:34:19 | Aegis | beemdevelopment/Aegis | 8,651 | 223 |
```xml
// See LICENSE.txt for license information.
import {t} from '@i18n';
export const labels = {
standard: {
label: {
id: t('post_priority.picker.label.standard'),
defaultMessage: 'Standard',
},
},
urgent: {
label: {
id: t('post_priority.picker.label.urgent'),
defaultMessage: 'Urgent',
},
},
important: {
label: {
id: t('post_priority.picker.label.important'),
defaultMessage: 'Important',
},
},
requestAck: {
label: {
id: t('post_priority.picker.label.request_ack'),
defaultMessage: 'Request acknowledgement',
},
description: {
id: t('post_priority.picker.label.request_ack.description'),
defaultMessage: 'An acknowledgement button will appear with your message',
},
},
persistentNotifications: {
label: {
id: t('post_priority.picker.label.persistent_notifications'),
defaultMessage: 'Send persistent notifications',
},
description: {
id: t('post_priority.picker.label.persistent_notifications.description'),
defaultMessage: 'Recipients are notified every {interval, plural, one {minute} other {{interval} minutes}} until they acknowledge or reply.',
},
},
};
``` | /content/code_sandbox/app/screens/post_priority_picker/utils.ts | xml | 2016-10-07T16:52:32 | 2024-08-16T12:08:38 | mattermost-mobile | mattermost/mattermost-mobile | 2,155 | 269 |
```xml
import { BufferLike } from '../interfaces.js';
import { IterableX } from '../iterable/iterablex.js';
import { Readable, ReadableOptions } from 'stream';
const done = (_: any) => null as any;
type SourceIterator<TSource> = Iterator<TSource, any, number | ArrayBufferView | undefined | null>;
/** @ignore */
/** @ignore */
export class IterableReadable<T> extends Readable {
private _pulling = false;
private _objectMode = true;
private _iterator: SourceIterator<T> | undefined;
constructor(source: Iterable<T>, options?: ReadableOptions) {
super(options);
this._iterator = source[Symbol.iterator]();
this._objectMode = !options || !!options.objectMode;
}
public _read(size: number) {
const it = this._iterator;
if (it && !this._pulling && (this._pulling = true)) {
this._pulling = this._pull(it, size);
}
}
public _destroy(err: Error | null, cb: (err: Error | null) => void) {
const it = this._iterator;
this._iterator = undefined;
const fn = (it && (err ? it.throw : it.return)) || done;
fn.call(it, err);
if (cb) {
cb(null);
}
}
// eslint-disable-next-line complexity
_pull(it: SourceIterator<T>, size: number) {
let innerSize = size;
const objectMode = this._objectMode;
let r: IteratorResult<BufferLike | T> | undefined;
while (this.readable && !(r = it.next(innerSize)).done) {
if (innerSize != null) {
if (objectMode) {
innerSize -= 1;
} else {
innerSize -= Buffer.byteLength(<BufferLike>r.value || '');
}
}
if (!this.push(r.value) || innerSize <= 0) {
break;
}
}
if ((r && r.done) || !this.readable) {
this.push(null);
if (it.return) {
it.return();
}
}
return !this.readable;
}
}
export function toNodeStream<TSource>(source: Iterable<TSource>): IterableReadable<TSource>;
export function toNodeStream<TSource>(
source: Iterable<TSource>,
options: ReadableOptions & { objectMode: true }
): IterableReadable<TSource>;
export function toNodeStream<TSource extends BufferLike>(
source: Iterable<TSource>,
options: ReadableOptions & { objectMode: false }
): IterableReadable<TSource>;
export function toNodeStream<TSource>(
source: Iterable<any>,
options?: ReadableOptions
): IterableReadable<TSource> {
return !options || options.objectMode === true
? new IterableReadable<TSource>(source, options)
: new IterableReadable<TSource extends BufferLike ? TSource : any>(source, options);
}
/**
* @ignore
*/
export function toNodeStreamProto<TSource>(this: Iterable<TSource>): IterableReadable<TSource>;
export function toNodeStreamProto<TSource>(
this: Iterable<TSource>,
options: ReadableOptions | { objectMode: true }
): IterableReadable<TSource>;
export function toNodeStreamProto<TSource extends BufferLike>(
this: Iterable<TSource>,
options: ReadableOptions | { objectMode: false }
): IterableReadable<TSource>;
export function toNodeStreamProto<TSource>(
this: Iterable<any>,
options?: ReadableOptions
): IterableReadable<TSource> {
return !options || options.objectMode === true
? new IterableReadable<TSource>(this, options)
: new IterableReadable<TSource extends BufferLike ? TSource : any>(this, options);
}
IterableX.prototype.toNodeStream = toNodeStreamProto;
declare module '../iterable/iterablex' {
interface IterableX<T> {
toNodeStream: typeof toNodeStreamProto;
}
}
``` | /content/code_sandbox/src/iterable/tonodestream.ts | xml | 2016-02-22T20:04:19 | 2024-08-09T18:46:41 | IxJS | ReactiveX/IxJS | 1,319 | 831 |
```xml
import { CryptoProxy } from '@proton/crypto';
import { base64StringToUint8Array } from '@proton/shared/lib/helpers/encoding';
import type { Address as tsAddress, User as tsUser } from '../../lib/interfaces';
import { getDecryptedUserKeysHelper, getReplacedAddressKeyTokens, splitKeys } from '../../lib/keys';
import { getAddressKey, getUserKey } from './keyDataHelper';
const getSetup = async (forceSameUserKey = false) => {
const keyPassword = '1';
const userKeysFull = await Promise.all([
getUserKey('1', keyPassword),
getUserKey('2', keyPassword),
getUserKey('3', keyPassword),
]);
const UserKeys = userKeysFull.map(({ Key }) => Key);
const User = {
Keys: UserKeys,
} as unknown as tsUser;
const address1 = 'test@test.com';
const address2 = 'test2@test.com';
const address3 = 'test3@test.com';
const userKeys = await getDecryptedUserKeysHelper(User, keyPassword);
const getUserPrivateKey = (index: number) => {
return userKeysFull[forceSameUserKey ? 0 : index].key.privateKey;
};
const addressKeysFull = await Promise.all([
getAddressKey('a', getUserPrivateKey(0), address1),
getAddressKey('b', getUserPrivateKey(0), address1),
getAddressKey('c', getUserPrivateKey(1), address1),
getAddressKey('d', getUserPrivateKey(1), address1),
getAddressKey('e', getUserPrivateKey(1), address1),
getAddressKey('f', getUserPrivateKey(2), address1),
]);
const address2KeysFull = await Promise.all([
getAddressKey('g', getUserPrivateKey(0), address2),
getAddressKey('h', getUserPrivateKey(1), address2),
]);
const address3KeysFull = await Promise.all([
getAddressKey('i', getUserPrivateKey(2), address3),
getAddressKey('j', getUserPrivateKey(2), address3),
]);
const Addresses = [
{
ID: 'my-address',
Email: address1,
Keys: addressKeysFull.map(({ Key }) => Key),
},
{
ID: 'my-address-2',
Email: address2,
Keys: address2KeysFull.map(({ Key }) => Key),
},
{
ID: 'my-address-3',
Email: address3,
Keys: address3KeysFull.map(({ Key }) => Key),
},
] as unknown as tsAddress[];
return {
keyPassword,
User,
Addresses,
userKeys,
privateKeys: splitKeys(userKeys).privateKeys,
};
};
describe('re-encrypt address keys', () => {
it('should get address key tokens and re-encrypt to another user key', async () => {
const setup = await getSetup();
const tokens = await getReplacedAddressKeyTokens({
addresses: setup.Addresses,
privateKey: setup.userKeys[0].privateKey,
privateKeys: setup.privateKeys,
});
const decryptedTokens = await Promise.all(
tokens.AddressKeyTokens.map(async (addressKeyToken) => {
await CryptoProxy.decryptSessionKey({
binaryMessage: base64StringToUint8Array(addressKeyToken.KeyPacket),
decryptionKeys: [setup.userKeys[0].privateKey],
});
return true;
})
);
expect(decryptedTokens.length).toBe(7);
});
it('should not re-encrypt tokens to the same user key', async () => {
const setup = await getSetup(true);
const tokens = await getReplacedAddressKeyTokens({
addresses: setup.Addresses,
privateKey: setup.userKeys[0].privateKey,
privateKeys: setup.privateKeys,
});
const decryptedTokens = await Promise.all(
tokens.AddressKeyTokens.map(async (addressKeyToken) => {
await CryptoProxy.decryptSessionKey({
binaryMessage: base64StringToUint8Array(addressKeyToken.KeyPacket),
decryptionKeys: [setup.userKeys[0].privateKey],
});
return true;
})
);
expect(decryptedTokens.length).toBe(0);
});
});
``` | /content/code_sandbox/packages/shared/test/keys/replaceAddressKeyTokens.spec.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 908 |
```xml
// luma.gl
import {RenderPass, RenderPassProps, RenderPassParameters} from '@luma.gl/core';
import {NullDevice} from '../null-device';
export class NullRenderPass extends RenderPass {
readonly device: NullDevice;
constructor(device: NullDevice, props: RenderPassProps) {
super(device, props);
this.device = device;
}
end(): void {}
pushDebugGroup(groupLabel: string): void {}
popDebugGroup(): void {}
insertDebugMarker(markerLabel: string): void {}
setParameters(parameters: RenderPassParameters = {}): void {}
beginOcclusionQuery(queryIndex: number): void {}
endOcclusionQuery(): void {}
}
``` | /content/code_sandbox/modules/test-utils/src/null-device/resources/null-render-pass.ts | xml | 2016-01-25T09:41:59 | 2024-08-16T10:03:05 | luma.gl | visgl/luma.gl | 2,280 | 150 |
```xml
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<dataset>
<metadata>
<column name="channel_name" />
<column name="thread_id" />
<column name="service_state" />
<column name="last_error_number" />
<column name="last_error_message" />
<column name="last_error_timestamp" />
<column name="last_processed_transaction" />
<column name="last_processed_transaction_original_commit_timestamp" />
<column name="last_processed_transaction_immediate_commit_timestamp" />
<column name="last_processed_transaction_start_buffer_timestamp" />
<column name="last_processed_transaction_end_buffer_timestamp" />
<column name="processing_transaction" />
<column name="processing_transaction_original_commit_timestamp" />
<column name="processing_transaction_immediate_commit_timestamp" />
<column name="processing_transaction_start_buffer_timestamp" />
</metadata>
</dataset>
``` | /content/code_sandbox/test/e2e/sql/src/test/resources/cases/dql/dataset/empty_storage_units/mysql/select_mysql_performance_schema_replication_applier_status_by_coordinator.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 252 |
```xml
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<UseWindowsForms>true</UseWindowsForms>
<TargetFrameworks>netcoreapp3.1</TargetFrameworks>
<RuntimeIdentifiers>win-x64;win-x86</RuntimeIdentifiers>
</PropertyGroup>
<PropertyGroup>
<AssetTargetFallback>uap10.0.19041</AssetTargetFallback>
<ApplicationManifest>app.manifest</ApplicationManifest>
<StartupObject>UnitTests.XamlIslands.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\UnitTests.XamlIslands.UWPApp\UnitTests.XamlIslands.UWPApp.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Toolkit.Forms.UI.XamlHost" Version="6.1.2" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/UnitTests/UnitTests.XamlIslands/UnitTests.XamlIslands.csproj | xml | 2016-06-17T21:29:46 | 2024-08-16T09:32:00 | WindowsCommunityToolkit | CommunityToolkit/WindowsCommunityToolkit | 5,842 | 205 |
```xml
import { Copy } from '@proton/components';
import { getTitle } from '../../helpers/title';
import mdx from './Copy.mdx';
export default {
component: Copy,
title: getTitle(__filename, false),
parameters: {
docs: {
page: mdx,
},
},
};
export const Basic = () => <Copy value="Pikachu" onCopy={() => alert(`"Pikachu" copied to clipboard`)} />;
``` | /content/code_sandbox/applications/storybook/src/stories/components/Copy.stories.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 96 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/general_padding">
<ListView
android:id="@+id/remoteList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/dialog_remove_remote.xml | xml | 2016-10-14T02:54:01 | 2024-08-16T16:01:33 | MGit | maks/MGit | 1,193 | 95 |
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.lamport.tla.toolbox.tool.tlc.modelCheck">
<stringAttribute key="configurationName" value="SmallModel"/>
<intAttribute key="distributedFPSetCount" value="0"/>
<stringAttribute key="distributedNetworkInterface" value="100.64.12.255"/>
<intAttribute key="distributedNodesCount" value="1"/>
<stringAttribute key="distributedTLC" value="off"/>
<intAttribute key="fpIndex" value="0"/>
<intAttribute key="maxHeapSize" value="25"/>
<stringAttribute key="modelBehaviorInit" value=""/>
<stringAttribute key="modelBehaviorNext" value=""/>
<stringAttribute key="modelBehaviorSpec" value="Spec"/>
<intAttribute key="modelBehaviorSpecType" value="1"/>
<stringAttribute key="modelBehaviorVars" value="maxVal, maxVBal, msgs, maxBal"/>
<stringAttribute key="modelComments" value="Has three acceptors, two values, and three ballots."/>
<booleanAttribute key="modelCorrectnessCheckDeadlock" value="true"/>
<listAttribute key="modelCorrectnessInvariants">
<listEntry value="1Inv"/>
</listAttribute>
<listAttribute key="modelCorrectnessProperties">
<listEntry value="1V!Spec"/>
</listAttribute>
<intAttribute key="modelEditorOpenTabs" value="6"/>
<stringAttribute key="modelExpressionEval" value=""/>
<stringAttribute key="modelParameterActionConstraint" value=""/>
<listAttribute key="modelParameterConstants">
<listEntry value="Acceptor;;{a1, a2, a3};1;0"/>
<listEntry value="Quorum;;{{a1, a2}, {a1, a3}, {a2, a3}};0;0"/>
<listEntry value="Value;;{v1, v2};1;0"/>
</listAttribute>
<stringAttribute key="modelParameterContraint" value=""/>
<listAttribute key="modelParameterDefinitions">
<listEntry value="None;;None;1;0"/>
<listEntry value="Ballot;;0..2;0;0"/>
<listEntry value="V!Ballot;;0..2;0;0"/>
</listAttribute>
<stringAttribute key="modelParameterModelValues" value="{}"/>
<stringAttribute key="modelParameterNewDefinitions" value=""/>
<intAttribute key="numberOfWorkers" value="2"/>
<stringAttribute key="result.mail.address" value=""/>
<stringAttribute key="specName" value="Paxos"/>
<stringAttribute key="tlcResourcesProfile" value="local custom"/>
</launchConfiguration>
``` | /content/code_sandbox/specifications/PaxosHowToWinATuringAward/Paxos.toolbox/Paxos___SmallModel.launch | xml | 2016-03-01T10:50:58 | 2024-08-15T09:26:38 | Examples | tlaplus/Examples | 1,258 | 611 |
```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 { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
import {
CacheGroupService,
CDNService,
ChangeLogsService,
DeliveryServiceService,
InvalidationJobService,
MiscAPIsService,
OriginService,
PhysicalLocationService,
ProfileService,
ServerService,
TopologyService,
TypeService,
UserService
} from "..";
import { CacheGroupService as TestingCacheGroupService } from "./cache-group.service";
import { CDNService as TestingCDNService } from "./cdn.service";
import { ChangeLogsService as TestingChangeLogsService} from "./change-logs.service";
import { DeliveryServiceService as TestingDeliveryServiceService } from "./delivery-service.service";
import { InvalidationJobService as TestingInvalidationJobService } from "./invalidation-job.service";
import { MiscAPIsService as TestingMiscAPIsService } from "./misc-apis.service";
import { OriginService as TestingOriginService } from "./origin.service";
import { PhysicalLocationService as TestingPhysicalLocationService } from "./physical-location.service";
import { ProfileService as TestingProfileService } from "./profile.service";
import { ServerService as TestingServerService } from "./server.service";
import { TopologyService as TestingTopologyService } from "./topology.service";
import { TypeService as TestingTypeService } from "./type.service";
import { UserService as TestingUserService } from "./user.service";
/**
* The API Testing Module provides mock services that allow components to use
* the Traffic Ops API without actually requiring a running Traffic Ops.
*/
@NgModule({
declarations: [],
imports: [
CommonModule
],
providers: [
{provide: CacheGroupService, useClass: TestingCacheGroupService},
{provide: ChangeLogsService, useClass: TestingChangeLogsService},
{provide: CDNService, useClass: TestingCDNService},
{provide: DeliveryServiceService, useClass: TestingDeliveryServiceService},
{provide: InvalidationJobService, useClass: TestingInvalidationJobService},
{provide: MiscAPIsService, useClass: TestingMiscAPIsService},
{provide: OriginService, useClass: TestingOriginService},
{provide: PhysicalLocationService, useClass: TestingPhysicalLocationService},
{provide: ProfileService, useClass: TestingProfileService},
{provide: ServerService, useClass: TestingServerService},
{provide: TopologyService, useClass: TestingTopologyService},
{provide: TypeService, useClass: TestingTypeService},
{provide: UserService, useClass: TestingUserService},
TestingServerService,
TestingMiscAPIsService
]
})
export class APITestingModule { }
``` | /content/code_sandbox/experimental/traffic-portal/src/app/api/testing/index.ts | xml | 2016-09-02T07:00:06 | 2024-08-16T03:50:21 | trafficcontrol | apache/trafficcontrol | 1,043 | 610 |
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<definitions id="definitions"
targetNamespace="path_to_url"
xmlns:activiti="path_to_url"
xmlns:bpmndi="path_to_url"
xmlns:omgdc="path_to_url"
xmlns:omgdi="path_to_url"
xmlns="path_to_url">
<process id="financialReport" name="Monthly financial report process">
<startEvent id="theStart" />
<sequenceFlow id="flow1" sourceRef="theStart" targetRef="writeReportTask" />
<userTask id="writeReportTask" name="Write monthly financial report" >
<documentation>
Write monthly financial report for publication to shareholders.
</documentation>
<potentialOwner>
<resourceAssignmentExpression>
<formalExpression>accountancy</formalExpression>
</resourceAssignmentExpression>
</potentialOwner>
</userTask>
<sequenceFlow id="flow2" sourceRef="writeReportTask" targetRef="verifyReportTask" />
<userTask id="verifyReportTask" name="Verify monthly financial report" >
<documentation>
Verify monthly financial report composed by the accountancy department.
This financial report is going to be sent to all the company shareholders.
</documentation>
<potentialOwner>
<resourceAssignmentExpression>
<formalExpression>management</formalExpression>
</resourceAssignmentExpression>
</potentialOwner>
</userTask>
<sequenceFlow id="flow3" sourceRef="verifyReportTask" targetRef="theEnd" />
<endEvent id="theEnd" />
</process>
<bpmndi:BPMNDiagram>
<bpmndi:BPMNPlane bpmnElement="financialReport">
<bpmndi:BPMNShape bpmnElement="theStart">
<omgdc:Bounds height="30.0" width="30.0" x="75.0" y="225.0" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="writeReportTask">
<omgdc:Bounds height="80.0" width="100.0" x="165.0" y="200.0" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="verifyReportTask">
<omgdc:Bounds height="80.0" width="100.0" x="330.0" y="200.0" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="theEnd">
<omgdc:Bounds height="28.0" width="28.0" x="480.0" y="226.0" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="flow1">
<omgdi:waypoint x="105.0" y="240.0" />
<omgdi:waypoint x="165.0" y="240.0" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="flow2">
<omgdi:waypoint x="265.0" y="240.0" />
<omgdi:waypoint x="330.0" y="240.0" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="flow3">
<omgdi:waypoint x="430.0" y="240.0" />
<omgdi:waypoint x="480.0" y="240.0" />
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>
``` | /content/code_sandbox/docs/docusaurus/docs/assets/static/userguide-5/images/FinancialReportProcess.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 878 |
```xml
import { expect, type Page, type TestInfo } from '@playwright/test';
import WpAdminPage from '../../../../../pages/wp-admin-page';
import Breakpoints from '../../../../../assets/breakpoints';
import EditorPage from '../../../../../pages/editor-page';
export default class ReverseColumns {
readonly page: Page;
readonly testInfo: TestInfo;
readonly wpAdmin: WpAdminPage;
readonly editor: EditorPage;
constructor( page: Page, testInfo: TestInfo, apiRequests ) {
this.page = page;
this.testInfo = testInfo;
this.wpAdmin = new WpAdminPage( this.page, this.testInfo, apiRequests );
this.editor = new EditorPage( this.page, this.testInfo );
}
getFirstColumn() {
return this.editor.getPreviewFrame().locator( '[data-element_type="column"][data-col="50"]:nth-child(1)' ).first();
}
async reverseColumnsForBreakpoint( breakpoint: string ) {
await this.editor.openPanelTab( 'advanced' );
await this.editor.openSection( '_section_responsive' );
await this.editor.setSwitcherControlValue( `reverse_order_${ breakpoint }`, true );
}
async init() {
await this.wpAdmin.openNewPage();
await this.editor.closeNavigatorIfOpen();
await this.editor.getPreviewFrame().locator( '.elementor-add-section-inner' ).click( { button: 'right' } );
await this.editor.getPreviewFrame().click( '.elementor-add-section-button', { delay: 500, clickCount: 2 } );
await this.editor.getPreviewFrame().click( '.elementor-select-preset-list li:nth-child(2)' );
}
async initAdditionalBreakpoints() {
const editor = await this.wpAdmin.openNewPage();
await this.editor.getPreviewFrame().locator( '.elementor-add-section-inner' ).click( { button: 'right' } );
const pageUrl = new URL( this.page.url() );
const searchParams = pageUrl.searchParams;
const breakpoints = new Breakpoints( this.page );
await breakpoints.addAllBreakpoints( editor, searchParams.get( 'post' ) );
}
async resetAdditionalBreakpoints() {
const editor = await this.wpAdmin.openNewPage();
const breakpoints = new Breakpoints( this.page );
await breakpoints.resetBreakpoints( editor );
}
async testReverseColumnsOneActivated( testDevice, isExperimentBreakpoints = false ) {
await this.init();
await this.editor.changeResponsiveView( testDevice );
const firstColumn = this.getFirstColumn();
await expect( firstColumn ).toHaveCSS( 'order', '0' );
await this.reverseColumnsForBreakpoint( testDevice );
await expect( firstColumn ).toHaveCSS( 'order', '10' );
const breakpoints = isExperimentBreakpoints ? Breakpoints.getAll() : Breakpoints.getBasic(),
filteredBreakpoints = breakpoints.filter( ( value ) => testDevice !== value );
for ( const breakpoint of filteredBreakpoints ) {
await this.editor.changeResponsiveView( breakpoint );
await expect( firstColumn ).toHaveCSS( 'order', '0' );
}
}
async testReverseColumnsAllActivated( isExperimentBreakpoints = false ) {
await this.init();
const breakpoints = isExperimentBreakpoints ? Breakpoints.getAll() : Breakpoints.getBasic();
for ( const breakpoint of breakpoints ) {
if ( 'widescreen' === breakpoint ) {
continue;
}
await this.editor.changeResponsiveView( breakpoint );
const firstColumn = this.getFirstColumn();
if ( 'desktop' === breakpoint ) {
await expect( firstColumn ).toHaveCSS( 'order', '0' );
continue;
}
await this.reverseColumnsForBreakpoint( breakpoint );
await expect( firstColumn ).toHaveCSS( 'order', '10' );
}
}
}
``` | /content/code_sandbox/tests/playwright/sanity/includes/elements/section/reverse-columns/reverse-columns.ts | xml | 2016-05-30T13:05:46 | 2024-08-16T13:13:10 | elementor | elementor/elementor | 6,507 | 818 |
```xml
<List x:TypeArguments="msx:XmlSerializable" Capacity="4" xmlns="clr-namespace:System.Collections.Generic;assembly=System.Private.CoreLib" xmlns:msx="clr-namespace:MonoTests.System.Xaml;assembly=System.Xaml.TestCases" xmlns:x="path_to_url">
<msx:XmlSerializable />
</List>
``` | /content/code_sandbox/src/Test/System.Xaml.TestCases/XmlFiles/List_XmlSerializable.xml | xml | 2016-08-25T20:07:20 | 2024-08-13T22:23:35 | CoreWF | UiPath/CoreWF | 1,126 | 72 |
```xml
import { Subscriber } from '../Subscriber';
/**
* Subscribes to an ArrayLike with a subscriber
* @param array The array or array-like to subscribe to
*/
export declare const subscribeToArray: <T>(array: ArrayLike<T>) => (subscriber: Subscriber<T>) => void;
``` | /content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/internal/util/subscribeToArray.d.ts | xml | 2016-09-05T10:18:44 | 2024-08-11T13:21:40 | LiquidCore | LiquidPlayer/LiquidCore | 1,010 | 61 |
```xml
import { c } from 'ttag';
import { APPS_CONFIGURATION } from '@proton/shared/lib/constants';
import { textToClipboard } from '@proton/shared/lib/helpers/browser';
import { getAppVersion } from '../../helpers';
import { useConfig, useEarlyAccess, useNotifications } from '../../hooks';
import { Tooltip } from '../tooltip';
interface Props {
appVersion?: string;
appName?: string;
fullVersion?: string;
}
const envMap = {
alpha: '',
beta: '',
relaunch: '',
};
const AppVersion = ({ appVersion: maybeAppVersion, appName: maybeAppName, fullVersion }: Props) => {
const { APP_NAME, APP_VERSION } = useConfig();
const { currentEnvironment } = useEarlyAccess();
const { createNotification } = useNotifications();
const appName = maybeAppName || APPS_CONFIGURATION[APP_NAME]?.name;
const appVersion = maybeAppVersion || getAppVersion(APP_VERSION);
const className = 'app-infos-version text-xs m-0';
const currentEnvDisplay = currentEnvironment && envMap[currentEnvironment] ? envMap[currentEnvironment] : '';
const children = (
<>
<span className="app-infos-name mr-1">{appName}</span>
<span className="app-infos-number" data-testid="app-infos:release-notes">
{appVersion} {currentEnvDisplay}
</span>
</>
);
if (fullVersion) {
return (
<Tooltip title={`Copy ${fullVersion} ${currentEnvDisplay} to clipboard`} className={className}>
<button
type="button"
onClick={() => {
textToClipboard(fullVersion);
createNotification({ text: c('Info').t`Version number successfully copied to clipboard` });
}}
>
{children}
</button>
</Tooltip>
);
}
return (
<Tooltip title={c('Action').t`Copy version number to clipboard`} className={className}>
<button
type="button"
onClick={() => {
textToClipboard(appVersion);
createNotification({ text: c('Info').t`Version number successfully copied to clipboard` });
}}
className={className}
>
{children}
</button>
</Tooltip>
);
};
export default AppVersion;
``` | /content/code_sandbox/packages/components/components/version/AppVersion.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 486 |
```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 floor = require( './index' );
// TESTS //
// The function returns an array-like object containing numbers...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor( x.length, 'float64', x, 1, 'float64', y, 1 ); // $ExpectType ArrayLike<number>
}
// The compiler throws an error if the function is provided a first argument which is not a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor( '10', 'float64', x, 1, 'float64', y, 1 ); // $ExpectError
floor( true, 'float64', x, 1, 'float64', y, 1 ); // $ExpectError
floor( false, 'float64', x, 1, 'float64', y, 1 ); // $ExpectError
floor( null, 'float64', x, 1, 'float64', y, 1 ); // $ExpectError
floor( undefined, 'float64', x, 1, 'float64', y, 1 ); // $ExpectError
floor( [], 'float64', x, 1, 'float64', y, 1 ); // $ExpectError
floor( {}, 'float64', x, 1, 'float64', y, 1 ); // $ExpectError
floor( ( x: number ): number => x, 'float64', x, 1, 'float64', y, 1 ); // $ExpectError
}
// The compiler throws an error if the function is provided a third argument which is not an array-like object containing numbers...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor( x.length, 'float64', 10, 1, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', '10', 1, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', true, 1, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', false, 1, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', null, 1, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', undefined, 1, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', [ '1' ], 1, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', {}, 1, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', ( x: number ): number => x, 1, 'float64', y, 1 ); // $ExpectError
}
// The compiler throws an error if the function is provided a fourth argument which is not a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor( x.length, 'float64', x, '10', 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', x, true, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', x, false, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', x, null, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', x, undefined, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', x, [], 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', x, {}, 'float64', y, 1 ); // $ExpectError
floor( x.length, 'float64', x, ( x: number ): number => x, 'float64', y, 1 ); // $ExpectError
}
// The compiler throws an error if the function is provided a sixth argument which is not an array-like object containing numbers...
{
const x = new Float64Array( 10 );
floor( x.length, 'float64', x, 1, 'float64', 10, 1 ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', '10', 1 ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', true, 1 ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', false, 1 ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', null, 1 ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', undefined, 1 ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', [ '1' ], 1 ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', {}, 1 ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', ( x: number ): number => x, 1 ); // $ExpectError
}
// The compiler throws an error if the function is provided a seventh argument which is not a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor( x.length, 'float64', x, 1, 'float64', y, '10' ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', y, true ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', y, false ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', y, null ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', y, undefined ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', y, [] ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', y, {} ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', y, ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the function is provided an unsupported number of arguments...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor(); // $ExpectError
floor( x.length ); // $ExpectError
floor( x.length, 'float64' ); // $ExpectError
floor( x.length, 'float64', x ); // $ExpectError
floor( x.length, 'float64', x, 1 ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64' ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', y ); // $ExpectError
floor( x.length, 'float64', x, 1, 'float64', y, 1, 10 ); // $ExpectError
}
// Attached to main export is an `ndarray` method which returns an array-like object containing numbers...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0 ); // $ExpectType ArrayLike<number>
}
// The compiler throws an error if the `ndarray` method is provided a first argument which is not a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor.ndarray( '10', 'float64', x, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( true, 'float64', x, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( false, 'float64', x, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( null, 'float64', x, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( undefined, 'float64', x, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( [], 'float64', x, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( {}, 'float64', x, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( ( x: number ): number => x, 'float64', x, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a third argument which is not an array-like object containing numbers...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor.ndarray( x.length, 'float64', 10, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', '10', 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', true, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', false, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', null, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', undefined, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', [ '1' ], 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', {}, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', ( x: number ): number => x, 1, 0, 'float64', y, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a fourth argument which is not a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor.ndarray( x.length, 'float64', x, '10', 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, true, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, false, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, null, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, undefined, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, [], 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, {}, 0, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, ( x: number ): number => x, 0, 'float64', y, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a fifth argument which is not a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor.ndarray( x.length, 'float64', x, 1, '10', 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, true, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, false, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, null, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, undefined, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, [], 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, {}, 'float64', y, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, ( x: number ): number => x, 'float64', y, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a seventh argument which is not an array-like object containing numbers...
{
const x = new Float64Array( 10 );
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', 10, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', '10', 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', true, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', false, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', null, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', undefined, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', [ '1' ], 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', {}, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', ( x: number ): number => x, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided an eighth argument which is not a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, '10', 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, true, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, false, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, null, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, undefined, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, [], 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, {}, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, ( x: number ): number => x, 0 ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a ninth argument which is not a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, '10' ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, true ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, false ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, null ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, undefined ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, [] ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, {} ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided an unsupported number of arguments...
{
const x = new Float64Array( 10 );
const y = new Float64Array( 10 );
floor.ndarray(); // $ExpectError
floor.ndarray( x.length ); // $ExpectError
floor.ndarray( x.length, 'float64' ); // $ExpectError
floor.ndarray( x.length, 'float64', x ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64' ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1 ); // $ExpectError
floor.ndarray( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 10 ); // $ExpectError
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/math/strided/special/floor/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 4,577 |
```xml
/** @jsx jsx */
import { Node } from 'slate'
import { jsx } from 'slate-hyperscript'
export const input = (
<editor>
<element>
<text key="a" />
<text key="b" />
<text key="c" />
<text key="d" />
</element>
</editor>
)
export const test = value => {
return Array.from(
Node.elements(value, {
range: {
anchor: {
path: [0, 1],
offset: 0,
},
focus: {
path: [0, 2],
offset: 0,
},
},
})
)
}
export const output = [
[
<element>
<text key="a" />
<text key="b" />
<text key="c" />
<text key="d" />
</element>,
[0],
],
]
``` | /content/code_sandbox/packages/slate/test/interfaces/Node/elements/range.tsx | xml | 2016-06-18T01:52:42 | 2024-08-16T18:43:42 | slate | ianstormtaylor/slate | 29,492 | 208 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE language SYSTEM "language.dtd">
<language name="ChangeLog" version="4" kateversion="2.4" section="Other" extensions="ChangeLog" mimetype="" author="Dominik Haumann (dhaumann@kde.org)" license="MIT">
<highlighting>
<contexts>
<context attribute="Normal Text" lineEndContext="#stay" name="Normal">
<DetectChar attribute="Entry" context="entry" char="*" firstNonSpace="true" />
<RegExpr attribute="Date" context="line" String="^\d\d\d\d\s*-\s*\d\d\s*-\s*\d\d\s*" column="0"/>
</context>
<context attribute="Normal Text" lineEndContext="#pop" name="line">
<RegExpr attribute="Name" context="#stay" String="(\w\s*)+"/>
<RegExpr attribute="E-Mail" context="#pop" String="<.*>\s*$"/>
</context>
<context attribute="Normal Text" lineEndContext="#pop" name="entry">
<RegExpr attribute="Entry" context="#pop" String=".*:" minimal="true"/>
</context>
</contexts>
<itemDatas>
<itemData name="Normal Text" defStyleNum="dsNormal"/>
<itemData name="Name" defStyleNum="dsKeyword"/>
<itemData name="E-Mail" defStyleNum="dsOthers"/>
<itemData name="Date" defStyleNum="dsDataType"/>
<itemData name="Entry" defStyleNum="dsDecVal"/>
</itemDatas>
</highlighting>
<general>
<keywords casesensitive="1" />
</general>
</language>
``` | /content/code_sandbox/syntax/changelog.xml | xml | 2016-08-19T16:25:54 | 2024-08-11T08:59:44 | matterhorn | matterhorn-chat/matterhorn | 1,027 | 385 |
```xml
import { c } from 'ttag';
import type { ExtractKeysOfType, IdentityValues } from '@proton/pass/types';
import type { IdentityFormField, IdentityFormSection } from './useIdentityForm';
type FieldType = ExtractKeysOfType<IdentityValues, string>;
export type IdentityFormFields = Record<FieldType, IdentityFormField>;
export const getIdentityFields = (): IdentityFormFields => ({
fullName: {
name: 'fullName',
label: c('Label').t`Full Name`,
placeholder: c('Label').t`Full Name`,
},
email: {
name: 'email',
label: c('Label').t`Email`,
placeholder: c('Label').t`Email`,
},
phoneNumber: {
name: 'phoneNumber',
label: c('Label').t`Phone number`,
placeholder: c('Label').t`Phone number`,
},
firstName: {
name: 'firstName',
label: c('Label').t`First name`,
placeholder: c('Label').t`First name`,
},
middleName: {
name: 'middleName',
label: c('Label').t`Middle name`,
placeholder: c('Label').t`Middle name`,
},
lastName: {
name: 'lastName',
label: c('Label').t`Last name`,
placeholder: c('Label').t`Last name`,
},
birthdate: {
name: 'birthdate',
label: c('Label').t`Birthdate`,
placeholder: c('Label').t`Birthdate`,
},
gender: {
name: 'gender',
label: c('Label').t`Gender`,
placeholder: c('Label').t`Gender`,
},
organization: {
name: 'organization',
label: c('Label').t`Organization`,
placeholder: c('Label').t`Name`,
},
streetAddress: {
name: 'streetAddress',
label: c('Label').t`Street address, P.O. box`,
placeholder: c('Label').t`Street address`,
},
floor: {
name: 'floor',
label: c('Label').t`Floor, apartment, building`,
placeholder: c('Label').t`Additional details`,
},
zipOrPostalCode: {
name: 'zipOrPostalCode',
label: c('Label').t`ZIP or Postal code`,
placeholder: c('Label').t`ZIP or Postal code`,
},
city: {
name: 'city',
label: c('Label').t`City`,
placeholder: c('Label').t`City`,
},
stateOrProvince: {
name: 'stateOrProvince',
label: c('Label').t`State or province`,
placeholder: c('Label').t`State or province`,
},
countryOrRegion: {
name: 'countryOrRegion',
label: c('Label').t`Country or Region`,
placeholder: c('Label').t`Country or Region`,
},
county: {
name: 'county',
label: c('Label').t`County`,
placeholder: c('Label').t`County`,
},
socialSecurityNumber: {
name: 'socialSecurityNumber',
label: c('Label').t`Social security number`,
placeholder: c('Label').t`Social security number`,
},
passportNumber: {
name: 'passportNumber',
label: c('Label').t`Passport number`,
placeholder: c('Label').t`Passport number`,
},
licenseNumber: {
name: 'licenseNumber',
},
website: {
name: 'website',
label: c('Label').t`Website`,
placeholder: c('Label').t`path_to_url`,
},
xHandle: {
name: 'xHandle',
label: c('Label').t`X handle`,
placeholder: `@username`,
},
linkedin: {
name: 'linkedin',
label: c('Label').t`LinkedIn account`,
placeholder: '',
},
facebook: {
name: 'facebook',
label: c('Label').t`Facebook account`,
placeholder: '',
},
reddit: {
name: 'reddit',
label: c('Label').t`Reddit handle`,
placeholder: '@username',
},
yahoo: {
name: 'yahoo',
label: c('Label').t`Yahoo account`,
placeholder: '',
},
instagram: {
name: 'instagram',
label: c('Label').t`Instagram handle`,
placeholder: '@username',
},
secondPhoneNumber: {
name: 'secondPhoneNumber',
label: c('Label').t`Phone number`,
placeholder: c('Label').t`Phone number`,
},
company: {
name: 'company',
label: c('Label').t`Company`,
placeholder: c('Label').t`Company`,
},
jobTitle: {
name: 'jobTitle',
label: c('Label').t`Job title`,
placeholder: c('Label').t`Job title`,
},
personalWebsite: {
name: 'personalWebsite',
label: c('Label').t`Personal website`,
placeholder: c('Label').t`Personal website`,
},
workPhoneNumber: {
name: 'workPhoneNumber',
label: c('Label').t`Work phone number`,
placeholder: c('Label').t`Work phone number`,
},
workEmail: {
name: 'workEmail',
label: c('Label').t`Work email`,
placeholder: c('Label').t`Work email`,
},
});
export const getInitialSections = (fields: IdentityFormFields): IdentityFormSection[] => [
{
name: c('Label').t`Personal details`,
expanded: true,
fields: [fields.fullName, fields.email, fields.phoneNumber],
customFieldsKey: 'extraPersonalDetails',
optionalFields: [fields.firstName, fields.middleName, fields.lastName, fields.birthdate, fields.gender],
},
{
name: c('Label').t`Address details`,
expanded: true,
customFieldsKey: 'extraAddressDetails',
fields: [
fields.organization,
fields.streetAddress,
fields.zipOrPostalCode,
fields.city,
fields.stateOrProvince,
fields.countryOrRegion,
],
optionalFields: [fields.floor, fields.county],
},
{
name: c('Label').t`Contact details`,
expanded: false,
customFieldsKey: 'extraContactDetails',
fields: [
fields.socialSecurityNumber,
fields.passportNumber,
fields.licenseNumber,
fields.xHandle,
fields.secondPhoneNumber,
],
optionalFields: [
fields.website,
fields.facebook,
fields.instagram,
fields.linkedin,
fields.reddit,
fields.yahoo,
],
},
{
name: c('Label').t`Work details`,
expanded: false,
fields: [fields.company, fields.jobTitle],
customFieldsKey: 'extraWorkDetails',
optionalFields: [fields.personalWebsite, fields.workPhoneNumber, fields.workEmail],
},
];
``` | /content/code_sandbox/packages/pass/hooks/identity/utils.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,541 |
```xml
import { FastifyInstance } from 'fastify';
import fp from 'fastify-plugin';
import { logger } from '@verdaccio/logger';
import { Storage } from '@verdaccio/store';
import { Config as IConfig } from '@verdaccio/types';
export default fp(
async function (fastify: FastifyInstance, opts: { config: IConfig; filters?: unknown }) {
const { config } = opts;
const storage: Storage = new Storage(config, logger);
// @ts-ignore
await storage.init(config, []);
fastify.decorate('storage', storage);
},
{
fastify: '>=4.x',
}
);
declare module 'fastify' {
interface FastifyInstance {
storage: Storage;
}
}
``` | /content/code_sandbox/packages/server/fastify/src/plugins/storage.ts | xml | 2016-04-15T16:21:12 | 2024-08-16T09:38:01 | verdaccio | verdaccio/verdaccio | 16,189 | 166 |
```xml
/**
* @license
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import {MDCTabScrollerAdapter} from './adapter';
import {MDCTabScrollerAnimation} from './types';
/** MDC Tab Scroller RTL */
export abstract class MDCTabScrollerRTL {
constructor(protected readonly adapter: MDCTabScrollerAdapter) {}
abstract getScrollPositionRTL(translateX: number): number;
abstract scrollToRTL(scrollX: number): MDCTabScrollerAnimation;
abstract incrementScrollRTL(scrollX: number): MDCTabScrollerAnimation;
/**
* @param scrollX The current scrollX position
* @param translateX The current translateX position
*/
abstract getAnimatingScrollPosition(scrollX: number, translateX: number):
number;
}
// tslint:disable-next-line:no-default-export Needed for backward compatibility with MDC Web v0.44.0 and earlier.
export default MDCTabScrollerRTL;
``` | /content/code_sandbox/packages/mdc-tab-scroller/rtl-scroller.ts | xml | 2016-12-05T16:04:09 | 2024-08-16T15:42:22 | material-components-web | material-components/material-components-web | 17,119 | 415 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="path_to_url">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="debug|Win32">
<Configuration>debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="checked|Win32">
<Configuration>checked</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="profile|Win32">
<Configuration>profile</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="release|Win32">
<Configuration>release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{F7CE93CE-0BAE-6EF7-73B9-F960570DDA77}</ProjectGuid>
<RootNamespace>SnippetImmediateMode</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='checked|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='profile|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<PlatformToolset>v140</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='checked|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='profile|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='debug|Win32'">
<OutDir>./../../../bin/vc14win32\</OutDir>
<IntDir>./Win32/SnippetImmediateMode/debug\</IntDir>
<TargetExt>.exe</TargetExt>
<TargetName>$(ProjectName)DEBUG</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='debug|Win32'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<StringPooling>true</StringPooling>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<BasicRuntimeChecks>UninitializedLocalUsageCheck</BasicRuntimeChecks>
<AdditionalOptions>/MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4350 /wd4668 /wd4365 /wd4548 /d2Zi+</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>./../../../Include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../Graphics/include/win32/GL;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_EXCEPTIONS=0;WIN32;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PHYSX_PROFILE_SDK;RENDER_SNIPPET;_DEBUG;PX_DEBUG=1;PX_CHECKED=1;PX_NVTX=1;PX_SUPPORT_PVD=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalOptions>/LIBPATH:../../../Lib/vc14win32 PhysX3CommonDEBUG_x86.lib PhysX3DEBUG_x86.lib PhysX3CookingDEBUG_x86.lib PhysX3CharacterKinematicDEBUG_x86.lib PhysX3ExtensionsDEBUG.lib PhysX3VehicleDEBUG.lib PxPvdSDKDEBUG_x86.lib PxTaskDEBUG_x86.lib PxFoundationDEBUG_x86.lib PsFastXmlDEBUG_x86.lib /LIBPATH:../../lib/vc14win32 SnippetUtilsDEBUG.lib /DEBUG</AdditionalOptions>
<AdditionalDependencies>Winmm.lib;OpenGL32.lib;glut32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)DEBUG.exe</OutputFile>
<AdditionalLibraryDirectories>./../../../Common/lib/vc14win32;./../../lib/vc14win32;./../../../../PxShared/lib/vc14win32;./../../Graphics/lib/win32/glut;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<ImportLibrary>$(OutDir)$(TargetName).lib</ImportLibrary>
<GenerateDebugInformation>true</GenerateDebugInformation>
<TargetMachine>MachineX86</TargetMachine>
</Link>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
</ProjectReference>
<PostBuildEvent>
<Command>XCOPY "../../../../PxShared/bin\vc14win32\PxFoundationDEBUG_x86.dll" "$(OutDir)" /D /Y
 XCOPY "../../../../PxShared/bin\vc14win32\PxPvdSDKDEBUG_x86.dll" "$(OutDir)" /D /Y</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='checked|Win32'">
<OutDir>./../../../bin/vc14win32\</OutDir>
<IntDir>./Win32/SnippetImmediateMode/checked\</IntDir>
<TargetExt>.exe</TargetExt>
<TargetName>$(ProjectName)CHECKED</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='checked|Win32'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<StringPooling>true</StringPooling>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<AdditionalOptions>/MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4350 /wd4668 /wd4365 /wd4548 /d2Zi+</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>./../../../Include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../Graphics/include/win32/GL;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_EXCEPTIONS=0;WIN32;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PHYSX_PROFILE_SDK;RENDER_SNIPPET;NDEBUG;PX_CHECKED=1;PX_NVTX=1;PX_SUPPORT_PVD=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalOptions>/LIBPATH:../../../Lib/vc14win32 PhysX3CommonCHECKED_x86.lib PhysX3CHECKED_x86.lib PhysX3CookingCHECKED_x86.lib PhysX3CharacterKinematicCHECKED_x86.lib PhysX3ExtensionsCHECKED.lib PhysX3VehicleCHECKED.lib PxPvdSDKCHECKED_x86.lib PxTaskCHECKED_x86.lib PxFoundationCHECKED_x86.lib PsFastXmlCHECKED_x86.lib /LIBPATH:../../lib/vc14win32 SnippetUtilsCHECKED.lib</AdditionalOptions>
<AdditionalDependencies>Winmm.lib;OpenGL32.lib;glut32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)CHECKED.exe</OutputFile>
<AdditionalLibraryDirectories>./../../../Common/lib/vc14win32;./../../lib/vc14win32;./../../../../PxShared/lib/vc14win32;./../../Graphics/lib/win32/glut;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<ImportLibrary>$(OutDir)$(TargetName).lib</ImportLibrary>
<GenerateDebugInformation>true</GenerateDebugInformation>
<TargetMachine>MachineX86</TargetMachine>
</Link>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
</ProjectReference>
<PostBuildEvent>
<Command>XCOPY "../../../../PxShared/bin\vc14win32\PxFoundationCHECKED_x86.dll" "$(OutDir)" /D /Y
 XCOPY "../../../../PxShared/bin\vc14win32\PxPvdSDKCHECKED_x86.dll" "$(OutDir)" /D /Y</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='profile|Win32'">
<OutDir>./../../../bin/vc14win32\</OutDir>
<IntDir>./Win32/SnippetImmediateMode/profile\</IntDir>
<TargetExt>.exe</TargetExt>
<TargetName>$(ProjectName)PROFILE</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='profile|Win32'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<StringPooling>true</StringPooling>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<AdditionalOptions>/MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4350 /wd4668 /wd4365 /wd4548 /d2Zi+</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>./../../../Include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../Graphics/include/win32/GL;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_EXCEPTIONS=0;WIN32;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PHYSX_PROFILE_SDK;RENDER_SNIPPET;NDEBUG;PX_PROFILE=1;PX_NVTX=1;PX_SUPPORT_PVD=1;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalOptions>/INCREMENTAL:NO /LIBPATH:../../../Lib/vc14win32 PhysX3CommonPROFILE_x86.lib PhysX3PROFILE_x86.lib PhysX3CookingPROFILE_x86.lib PhysX3CharacterKinematicPROFILE_x86.lib PhysX3ExtensionsPROFILE.lib PhysX3VehiclePROFILE.lib PxPvdSDKPROFILE_x86.lib PxTaskPROFILE_x86.lib PxFoundationPROFILE_x86.lib PsFastXmlPROFILE_x86.lib /LIBPATH:../../lib/vc14win32 SnippetUtilsPROFILE.lib /DEBUG</AdditionalOptions>
<AdditionalDependencies>Winmm.lib;OpenGL32.lib;glut32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName)PROFILE.exe</OutputFile>
<AdditionalLibraryDirectories>./../../../Common/lib/vc14win32;./../../lib/vc14win32;./../../../../PxShared/lib/vc14win32;./../../Graphics/lib/win32/glut;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<ImportLibrary>$(OutDir)$(TargetName).lib</ImportLibrary>
<GenerateDebugInformation>true</GenerateDebugInformation>
<TargetMachine>MachineX86</TargetMachine>
</Link>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
</ProjectReference>
<PostBuildEvent>
<Command>XCOPY "../../../../PxShared/bin\vc14win32\PxFoundationPROFILE_x86.dll" "$(OutDir)" /D /Y
 XCOPY "../../../../PxShared/bin\vc14win32\PxPvdSDKPROFILE_x86.dll" "$(OutDir)" /D /Y</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release|Win32'">
<OutDir>./../../../bin/vc14win32\</OutDir>
<IntDir>./Win32/SnippetImmediateMode/release\</IntDir>
<TargetExt>.exe</TargetExt>
<TargetName>$(ProjectName)</TargetName>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules />
<CodeAnalysisRuleAssemblies />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='release|Win32'">
<ClCompile>
<TreatWarningAsError>true</TreatWarningAsError>
<StringPooling>true</StringPooling>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
<RuntimeTypeInfo>false</RuntimeTypeInfo>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FloatingPointModel>Fast</FloatingPointModel>
<AdditionalOptions>/MP /Wall /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4435 /wd4577 /wd4464 /wd4350 /wd4668 /wd4365 /wd4548 /d2Zi+</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>./../../../Include;./../../../../PxShared/include;./../../../../PxShared/src/foundation/include;./../../../../PxShared/src/fastxml/include;./../../Graphics/include/win32/GL;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_EXCEPTIONS=0;WIN32;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;PHYSX_PROFILE_SDK;RENDER_SNIPPET;NDEBUG;PX_SUPPORT_PVD=0;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling>false</ExceptionHandling>
<WarningLevel>Level4</WarningLevel>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<PrecompiledHeaderFile></PrecompiledHeaderFile>
<ProgramDataBaseFileName>$(TargetDir)\$(TargetName).pdb</ProgramDataBaseFileName>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<AdditionalOptions>/INCREMENTAL:NO /LIBPATH:../../../Lib/vc14win32 PhysX3Common_x86.lib PhysX3_x86.lib PhysX3Cooking_x86.lib PhysX3CharacterKinematic_x86.lib PhysX3Extensions.lib PhysX3Vehicle.lib PxPvdSDK_x86.lib PxTask_x86.lib PxFoundation_x86.lib PsFastXml_x86.lib /LIBPATH:../../lib/vc14win32 SnippetUtils.lib</AdditionalOptions>
<AdditionalDependencies>Winmm.lib;OpenGL32.lib;glut32.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName).exe</OutputFile>
<AdditionalLibraryDirectories>./../../../Common/lib/vc14win32;./../../lib/vc14win32;./../../../../PxShared/lib/vc14win32;./../../Graphics/lib/win32/glut;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<ProgramDatabaseFile>$(TargetDir)\$(TargetName).pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<ImportLibrary>$(OutDir)$(TargetName).lib</ImportLibrary>
<GenerateDebugInformation>true</GenerateDebugInformation>
<TargetMachine>MachineX86</TargetMachine>
</Link>
<ResourceCompile>
</ResourceCompile>
<ProjectReference>
</ProjectReference>
<PostBuildEvent>
<Command>XCOPY "../../../../PxShared/bin\vc14win32\PxFoundation_x86.dll" "$(OutDir)" /D /Y
 XCOPY "../../../../PxShared/bin\vc14win32\PxPvdSDK_x86.dll" "$(OutDir)" /D /Y</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\SnippetCommon\ClassicMain.cpp">
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\SnippetImmediateMode\SnippetImmediateMode.cpp">
</ClCompile>
<ClCompile Include="..\..\SnippetImmediateMode\SnippetImmediateModeRender.cpp">
</ClCompile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="./SnippetUtils.vcxproj">
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="./SnippetRender.vcxproj">
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets"></ImportGroup>
</Project>
``` | /content/code_sandbox/PhysX_3.4/Snippets/compiler/vc14win32/SnippetImmediateMode.vcxproj | xml | 2016-10-12T16:34:31 | 2024-08-16T09:40:38 | PhysX-3.4 | NVIDIAGameWorks/PhysX-3.4 | 2,343 | 4,847 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="ActionBar" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android-gradle" name="Android-Gradle">
<configuration>
<option name="GRADLE_PROJECT_PATH" value=":app" />
</configuration>
</facet>
<facet type="android" name="Android">
<configuration>
<option name="SELECTED_BUILD_VARIANT" value="debug" />
<option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
<option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
<option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
<option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
<afterSyncTasks>
<task>generateDebugAndroidTestSources</task>
<task>generateDebugSources</task>
</afterSyncTasks>
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/23.0.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
</content>
<orderEntry type="jdk" jdkName="Android API 23 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" exported="" name="support-v4-23.0.1" level="project" />
<orderEntry type="library" exported="" name="appcompat-v7-23.0.1" level="project" />
<orderEntry type="library" exported="" name="support-annotations-23.0.1" level="project" />
</component>
</module>
``` | /content/code_sandbox/Android/ActionBar/app/app.iml | xml | 2016-05-02T05:43:21 | 2024-08-16T06:51:39 | journaldev | WebJournal/journaldev | 1,314 | 1,984 |
```xml
/**
* Oracle specific connection credential options.
*/
export interface OracleConnectionCredentialsOptions {
/**
* Connection url where perform connection to.
*/
readonly url?: string
/**
* Database host.
*/
readonly host?: string
/**
* Database host port.
*/
readonly port?: number
/**
* Database username.
*/
readonly username?: string
/**
* Database password.
*/
readonly password?: string
/**
* Database name to connect to.
*/
readonly database?: string
/**
* Connection SID.
*/
readonly sid?: string
/**
* Connection Service Name.
*/
readonly serviceName?: string
/**
* Embedded TNS Connection String
*/
readonly connectString?: string
}
``` | /content/code_sandbox/src/driver/oracle/OracleConnectionCredentialsOptions.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 166 |
```xml
/*
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
import { ed } from '@liskhq/lisk-cryptography';
import { math } from '@liskhq/lisk-utils';
import {
ModuleConfig,
ModuleConfigJSON,
UnlockingObject,
StakeSharingCoefficient,
PunishmentLockingPeriods,
} from './types';
const { q96 } = math;
export const sortUnlocking = (unlocks: UnlockingObject[]): void => {
unlocks.sort((a, b) => {
if (!a.validatorAddress.equals(b.validatorAddress)) {
return a.validatorAddress.compare(b.validatorAddress);
}
if (a.unstakeHeight !== b.unstakeHeight) {
return b.unstakeHeight - a.unstakeHeight;
}
const diff = b.amount - a.amount;
if (diff > BigInt(0)) {
return 1;
}
if (diff < BigInt(0)) {
return -1;
}
return 0;
});
};
export const equalUnlocking = (a: UnlockingObject, b: UnlockingObject): boolean =>
a.validatorAddress.equals(b.validatorAddress) &&
a.amount === b.amount &&
a.unstakeHeight === b.unstakeHeight;
export const isNullCharacterIncluded = (input: string): boolean =>
new RegExp(/\\0|\\u0000|\\x00/).test(input);
export const isUsername = (username: string): boolean => {
if (isNullCharacterIncluded(username)) {
return false;
}
if (username !== username.trim().toLowerCase()) {
return false;
}
return /^[a-z0-9!@$&_.]+$/g.test(username);
};
export const validateSignature = (
tag: string,
chainID: Buffer,
publicKey: Buffer,
signature: Buffer,
bytes: Buffer,
): boolean => ed.verifyData(tag, chainID, bytes, signature, publicKey);
export interface ValidatorWeight {
readonly address: Buffer;
weight: bigint;
}
export const pickStandByValidator = (
validatorWeights: ReadonlyArray<ValidatorWeight>,
randomSeed: Buffer,
): number => {
const seedNumber = randomSeed.readBigUInt64BE();
const totalStakeWeight = validatorWeights.reduce(
(prev, current) => prev + BigInt(current.weight),
BigInt(0),
);
let threshold = seedNumber % totalStakeWeight;
for (let i = 0; i < validatorWeights.length; i += 1) {
const validatorWeight = BigInt(validatorWeights[i].weight);
if (validatorWeight > threshold) {
return i;
}
threshold -= validatorWeight;
}
return -1;
};
export const selectStandbyValidators = (
validatorWeights: ValidatorWeight[],
randomSeed1: Buffer,
randomSeed2?: Buffer,
): ValidatorWeight[] => {
const numberOfCandidates = 1 + (randomSeed2 !== undefined ? 1 : 0);
// if validator weights is smaller than number selecting, select all
if (validatorWeights.length <= numberOfCandidates) {
return validatorWeights.map(v => ({
address: v.address,
weight: BigInt(0),
}));
}
const result: ValidatorWeight[] = [];
const index = pickStandByValidator(validatorWeights, randomSeed1);
const [selected] = validatorWeights.splice(index, 1);
result.push({
address: selected.address,
weight: BigInt(0),
});
// if seed2 is missing, return only 1
if (!randomSeed2) {
return result;
}
const secondIndex = pickStandByValidator(validatorWeights, randomSeed2);
const [secondStandby] = validatorWeights.splice(secondIndex, 1);
result.push({
address: secondStandby.address,
weight: BigInt(0),
});
return result;
};
export const isCurrentlyPunished = (
height: number,
pomHeights: ReadonlyArray<number>,
punishmentWindowSelfStaking: number,
): boolean => {
if (pomHeights.length === 0) {
return false;
}
const lastPomHeight = Math.max(...pomHeights);
if (height - lastPomHeight < punishmentWindowSelfStaking) {
return true;
}
return false;
};
export const getWaitTime = (
senderAddress: Buffer,
validatorAddress: Buffer,
punishmentLockingPeriods: PunishmentLockingPeriods,
): number =>
validatorAddress.equals(senderAddress)
? punishmentLockingPeriods.lockingPeriodSelfStaking
: punishmentLockingPeriods.lockingPeriodStaking;
export const getPunishTime = (
senderAddress: Buffer,
validatorAddress: Buffer,
punishmentLockingPeriods: PunishmentLockingPeriods,
): number =>
validatorAddress.equals(senderAddress)
? punishmentLockingPeriods.punishmentWindowSelfStaking
: punishmentLockingPeriods.punishmentWindowStaking;
export const hasWaited = (
unlockingObject: UnlockingObject,
senderAddress: Buffer,
height: number,
punishmentLockingPeriods: PunishmentLockingPeriods,
) => {
const delayedAvailability = getWaitTime(
senderAddress,
unlockingObject.validatorAddress,
punishmentLockingPeriods,
);
return !(height - unlockingObject.unstakeHeight < delayedAvailability);
};
export const isPunished = (
unlockingObject: UnlockingObject,
pomHeights: ReadonlyArray<number>,
senderAddress: Buffer,
height: number,
punishmentLockingPeriods: PunishmentLockingPeriods,
) => {
if (!pomHeights.length) {
return false;
}
const lastPomHeight = pomHeights[pomHeights.length - 1];
const waitTime = getWaitTime(
senderAddress,
unlockingObject.validatorAddress,
punishmentLockingPeriods,
);
const punishTime = getPunishTime(
senderAddress,
unlockingObject.validatorAddress,
punishmentLockingPeriods,
);
return (
height - lastPomHeight < punishTime && lastPomHeight < unlockingObject.unstakeHeight + waitTime
);
};
const lastHeightOfRound = (height: number, genesisHeight: number, roundLength: number) => {
const roundNumber = Math.ceil((height - genesisHeight) / roundLength);
return roundNumber * roundLength + genesisHeight;
};
export const isCertificateGenerated = (options: {
unlockObject: UnlockingObject;
genesisHeight: number;
maxHeightCertified: number;
roundLength: number;
}): boolean =>
lastHeightOfRound(
options.unlockObject.unstakeHeight + 2 * options.roundLength,
options.genesisHeight,
options.roundLength,
) <= options.maxHeightCertified;
export const getMinPunishedHeight = (pomHeights: number[], punishmentWindow: number): number => {
if (pomHeights.length === 0) {
return 0;
}
const lastPomHeight = Math.max(...pomHeights);
// path_to_url#update-to-validity-of-unlock-transaction
return lastPomHeight + punishmentWindow;
};
export const getPunishmentPeriod = (
senderAddress: Buffer,
validatorAddress: Buffer,
pomHeights: number[],
currentHeight: number,
punishmentLockingPeriods: PunishmentLockingPeriods,
): number => {
const punishmentWindow = senderAddress.equals(validatorAddress)
? punishmentLockingPeriods.punishmentWindowSelfStaking
: punishmentLockingPeriods.punishmentWindowStaking;
const minPunishedHeight = getMinPunishedHeight(pomHeights, punishmentWindow);
const remainingBlocks = minPunishedHeight - currentHeight;
return remainingBlocks < 0 ? 0 : remainingBlocks;
};
export const getModuleConfig = (config: ModuleConfigJSON): ModuleConfig => {
const roundLength = config.numberActiveValidators + config.numberStandbyValidators;
return {
...config,
roundLength,
minWeightStandby: BigInt(config.minWeightStandby),
posTokenID: Buffer.from(config.posTokenID, 'hex'),
validatorRegistrationFee: BigInt(config.validatorRegistrationFee),
baseStakeAmount: BigInt(config.baseStakeAmount),
reportMisbehaviorReward: BigInt(config.reportMisbehaviorReward),
weightScaleFactor: BigInt(config.weightScaleFactor),
};
};
export const getValidatorWeight = (
factorSelfStakes: number,
selfStake: bigint,
totalStakeReceived: bigint,
) => {
const cap = selfStake * BigInt(factorSelfStakes);
if (cap < totalStakeReceived) {
return cap;
}
return totalStakeReceived;
};
export const isSharingCoefficientSorted = (
sharingCoefficients: StakeSharingCoefficient[],
): boolean => {
const sharingCoefficientsCopy = [...sharingCoefficients];
sharingCoefficientsCopy.sort((a, b) => a.tokenID.compare(b.tokenID));
for (let i = 0; i < sharingCoefficients.length; i += 1) {
if (!sharingCoefficientsCopy[i].tokenID.equals(sharingCoefficients[i].tokenID)) {
return false;
}
}
return true;
};
export const calculateStakeRewards = (
stakeSharingCoefficient: StakeSharingCoefficient,
amount: bigint,
validatorSharingCoefficient: StakeSharingCoefficient,
): bigint => {
const qAmount = q96(amount);
const qStakeSharingCoefficient = q96(stakeSharingCoefficient.coefficient);
const qValidatorSharingCoefficient = q96(validatorSharingCoefficient.coefficient);
const reward = qValidatorSharingCoefficient.sub(qStakeSharingCoefficient).mul(qAmount);
return reward.floor();
};
``` | /content/code_sandbox/framework/src/modules/pos/utils.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 2,148 |
```xml
import {
isOrgModerator,
isSiteMember,
isSiteModerator,
PermissionsActionPredicate,
} from "./types";
const usersCantUpdateSelves: PermissionsActionPredicate = ({
viewer,
user,
}) => ({
pass: viewer.id !== user.id,
reason: "Users cannot update their own roles or scopes",
});
const onlyAdminsCanAllocateStaff: PermissionsActionPredicate = ({
viewer,
user,
newUserRole,
}) => ({
pass: !(viewer.role !== "ADMIN" && newUserRole === "STAFF"),
reason: "Only admins may allocate staff",
});
const onlyAdminsCanDemoteStaffDirectly: PermissionsActionPredicate = ({
viewer,
user,
}) => ({
pass: !(viewer.role !== "ADMIN" && user.role === "STAFF"),
reason: "Only admins may change staffs roles",
});
/**
* This (terribly named) predicate ensures that a scoped viewer cannot
* change a scoped user's role in a way that inadvertantly
* remove scopes the viewer does not posses.
*/
const scopedUsersCantIndirectlyRemoveScopesTheyDontPosses: PermissionsActionPredicate =
({ viewer, user, newUserRole, scoped }) => {
const reason =
"This role change would remove scopes outside of the viewers authorization";
const changingAwayFromCurrentScopedRole =
(isSiteModerator(user) || isSiteMember(user)) && !scoped;
if (
viewer.role === "ADMIN" ||
isOrgModerator(viewer) ||
!changingAwayFromCurrentScopedRole
) {
return {
pass: true,
reason,
};
}
const relevantScopes =
user.role === "MODERATOR" ? user.moderationScopes : user.membershipScopes;
const userHasScopesViewerDoesnt = !!relevantScopes?.siteIDs?.find(
(userSiteID) => !viewer.moderationScopes?.siteIDs?.includes(userSiteID)
);
return {
pass: !userHasScopesViewerDoesnt,
reason,
};
};
export const predicates: PermissionsActionPredicate[] = [
usersCantUpdateSelves,
onlyAdminsCanAllocateStaff,
onlyAdminsCanDemoteStaffDirectly,
scopedUsersCantIndirectlyRemoveScopesTheyDontPosses,
];
``` | /content/code_sandbox/common/lib/permissions/predicates.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 504 |
```xml
export type Transition<T = any> = (state?: T) => void;
export type EventStateTransition<E, S> = [E, S, Transition];
export type StateMachine<S extends string, E> = {
[key in S]: EventStateTransition<E, S>[];
};
export const find_transition = <S extends string, E>(
state_machine: StateMachine<S, E>,
state: S,
event: E
): { next_state?: S, transition?: Transition } => {
const current_state = state_machine[state];
if (!current_state) throw new Error(`No state: ${current_state} found in state machine`);
const event_tuple = current_state.find(s => s[0] === event);
return event_tuple ? {
next_state: event_tuple[1],
transition: event_tuple[2]
} : {}
};
``` | /content/code_sandbox/docs/_src/state-machine.ts | xml | 2016-10-07T02:07:44 | 2024-08-16T16:03:13 | apprun | yysun/apprun | 1,177 | 182 |
```xml
import * as React from 'react';
/**
* {@docCategory Popup}
*/
export interface IPopupProps extends React.HTMLAttributes<HTMLDivElement>, React.RefAttributes<HTMLDivElement> {
/**
* Aria role for popup
*/
role?: string;
/**
* Accessible label text for the popup.
*/
ariaLabel?: string;
/**
* Defines the element id referencing the element containing label text for popup.
*/
ariaLabelledBy?: string;
/**
* Defines the element id referencing the element containing the description for the popup.
*/
ariaDescribedBy?: string;
/**
* A callback function for when the popup is dismissed from the close button or light dismiss. If provided, will
* handle escape key press and call this. The event will be stopped/canceled.
*/
onDismiss?: (ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement> | KeyboardEvent) => any;
/**
* Optional class name for the root popup div.
*/
className?: string;
/**
* If true, when this component is unmounted, focus will be restored to the element that had focus when the component
* first mounted.
* @defaultvalue true
* @deprecated use restoreFocus callback instead
*/
shouldRestoreFocus?: boolean;
/**
* Called when the component is unmounting, and focus needs to be restored. If this is provided,
* focus will not be restored automatically, and you'll need to call `params.originalElement.focus()`.
*/
onRestoreFocus?: (params: IPopupRestoreFocusParams) => void;
/**
* Puts aria-hidden=true on all non-ancestors of the current popup, for screen readers.
* @defaultvalue true
* @deprecated Setting this to `false` is deprecated since it breaks modal behavior for some screen readers.
* It will not be supported in future versions of the library.
*/
enableAriaHiddenSiblings?: boolean;
}
/**
* Parameters passed to `onRestoreFocus` callback of `Popup` and related components.
* {@docCategory Popup}
*/
export interface IPopupRestoreFocusParams {
/** Element the underlying Popup believes focus should go to */
originalElement?: HTMLElement | Window | null;
/** Whether the popup currently contains focus */
containsFocus: boolean;
/** Whether the document the popup belongs to contains focus (or false if unknown) */
documentContainsFocus: boolean;
}
``` | /content/code_sandbox/packages/react/src/components/Popup/Popup.types.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 525 |
```xml
import { getSnapshot, types, unprotect } from "../../src"
import { describe, expect, test } from "bun:test"
describe("null as default", () => {
describe("basic tests", () => {
const M = types.model({
x: types.optional(types.number, 1, [null]),
y: types.optional(types.number, () => 2, [null])
})
test("with optional values, then assigned values", () => {
const m = M.create({
x: null,
y: null
})
unprotect(m)
expect(m.x).toBe(1)
expect(m.y).toBe(2)
expect(getSnapshot(m)).toEqual({
x: 1,
y: 2
})
m.x = 10
m.y = 20
expect(m.x).toBe(10)
expect(m.y).toBe(20)
expect(getSnapshot(m)).toEqual({
x: 10,
y: 20
})
})
test("with given values, then assigned optional values", () => {
const m = M.create({
x: 10,
y: 20
})
unprotect(m)
expect(m.x).toBe(10)
expect(m.y).toBe(20)
expect(getSnapshot(m)).toEqual({
x: 10,
y: 20
})
m.x = null as any
m.y = null as any
expect(m.x).toBe(1)
expect(m.y).toBe(2)
expect(getSnapshot(m)).toEqual({
x: 1,
y: 2
})
})
})
test("when the underlying type accepts undefined it should be ok", () => {
const M = types.model({
a: types.optional(types.union(types.undefined, types.number), undefined, [null]),
b: types.optional(types.union(types.undefined, types.number), 5, [null])
})
{
const m = M.create({
a: null,
b: null
})
expect(m.a).toBeUndefined()
expect(m.b).toBe(5)
expect(getSnapshot(m)).toEqual({
a: undefined,
b: 5
})
}
{
const m = M.create({
a: 10,
b: 20
})
expect(m.a).toBe(10)
expect(m.b).toBe(20)
expect(getSnapshot(m)).toEqual({
a: 10,
b: 20
})
}
{
const m = M.create({
a: undefined,
b: undefined
})
expect(m.a).toBeUndefined()
expect(m.b).toBeUndefined()
expect(getSnapshot(m)).toEqual({
a: undefined,
b: undefined
})
}
})
test("when the underlying type does not accept undefined, then undefined should throw", () => {
const M = types.model({
a: types.optional(types.number, 5, [null]),
b: types.optional(types.number, 6, [null])
})
{
const m = M.create({
a: null,
b: null
})
expect(m.a).toBe(5)
expect(m.b).toBe(6)
}
if (process.env.NODE_ENV !== "production") {
expect(() => {
M.create({
a: null,
b: undefined as any // undefined is not valid
})
}).toThrow("value `undefined` is not assignable to type: `number`")
expect(() => {
M.create({
a: null
// b: null missing, but should be there
} as any)
}).toThrow("value `undefined` is not assignable to type: `number`")
}
})
})
describe("'empty' or false as default", () => {
describe("basic tests", () => {
const M = types.model({
x: types.optional(types.number, 1, ["empty", false]),
y: types.optional(types.number, () => 2, ["empty", false])
})
test("with optional values, then assigned values", () => {
const m = M.create({
x: "empty",
y: false
})
unprotect(m)
expect(m.x).toBe(1)
expect(m.y).toBe(2)
expect(getSnapshot(m)).toEqual({
x: 1,
y: 2
})
m.x = 10
m.y = 20
expect(m.x).toBe(10)
expect(m.y).toBe(20)
expect(getSnapshot(m)).toEqual({
x: 10,
y: 20
})
})
test("with given values, then assigned 'empty'", () => {
const m = M.create({
x: 10,
y: 20
})
unprotect(m)
expect(m.x).toBe(10)
expect(m.y).toBe(20)
expect(getSnapshot(m)).toEqual({
x: 10,
y: 20
})
m.x = "empty" as any
m.y = false as any
expect(m.x).toBe(1)
expect(m.y).toBe(2)
expect(getSnapshot(m)).toEqual({
x: 1,
y: 2
})
})
})
test("when the underlying type accepts undefined it should be ok", () => {
const M = types.model({
a: types.optional(types.union(types.undefined, types.number), undefined, ["empty", false]),
b: types.optional(types.union(types.undefined, types.number), 5, ["empty", false])
})
{
const m = M.create({
a: "empty",
b: false
})
expect(m.a).toBeUndefined()
expect(m.b).toBe(5)
expect(getSnapshot(m)).toEqual({
a: undefined,
b: 5
})
}
{
const m = M.create({
a: 10,
b: 20
})
expect(m.a).toBe(10)
expect(m.b).toBe(20)
expect(getSnapshot(m)).toEqual({
a: 10,
b: 20
})
}
{
const m = M.create({
a: undefined,
b: undefined
})
expect(m.a).toBeUndefined()
expect(m.b).toBeUndefined()
expect(getSnapshot(m)).toEqual({
a: undefined,
b: undefined
})
}
})
test("when the underlying type does not accept undefined, then undefined should throw", () => {
const M = types.model({
a: types.optional(types.number, 5, ["empty", false]),
b: types.optional(types.number, 6, ["empty", false])
})
{
const m = M.create({
a: "empty",
b: false
})
expect(m.a).toBe(5)
expect(m.b).toBe(6)
}
if (process.env.NODE_ENV !== "production") {
expect(() => {
M.create({
a: undefined as any,
b: undefined as any
})
}).toThrow("value `undefined` is not assignable to type: `number`")
}
})
})
test("cached snapshots should be ok when using default values", () => {
const M = types.model({ x: 5, y: 6 })
const Store = types.model({
deep: types.model({
a: types.optional(types.undefined, undefined),
b: types.optional(types.undefined, undefined, ["empty"]),
c: types.optional(types.number, 5),
d: types.optional(types.number, 5, ["empty"]),
a2: types.optional(types.undefined, () => undefined),
b2: types.optional(types.undefined, () => undefined, ["empty"]),
c2: types.optional(types.number, () => 5),
d2: types.optional(types.number, () => 5, ["empty"]),
a3: types.optional(M, { y: 20 }),
b3: types.optional(M, { y: 20 }, ["empty"]),
c3: types.optional(M, () => M.create({ y: 20 })),
d3: types.optional(M, () => M.create({ y: 20 }), ["empty"]),
e3: types.optional(M, () => ({ y: 20 })),
f3: types.optional(M, () => ({ y: 20 }), ["empty"])
})
})
const s = Store.create({
deep: {
b: "empty",
d: "empty",
b2: "empty",
d2: "empty",
b3: "empty",
d3: "empty",
f3: "empty"
}
})
expect(getSnapshot(s)).toEqual({
deep: {
a: undefined,
b: undefined,
c: 5,
d: 5,
a2: undefined,
b2: undefined,
c2: 5,
d2: 5,
a3: { x: 5, y: 20 },
b3: { x: 5, y: 20 },
c3: { x: 5, y: 20 },
d3: { x: 5, y: 20 },
e3: { x: 5, y: 20 },
f3: { x: 5, y: 20 }
}
})
})
``` | /content/code_sandbox/__tests__/core/optional-extension.test.ts | xml | 2016-09-04T18:28:25 | 2024-08-16T08:48:55 | mobx-state-tree | mobxjs/mobx-state-tree | 6,917 | 2,062 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="path_to_url"
xmlns:app="path_to_url">
<item
android:icon="@drawable/ic_home_black_24dp"
android:enabled="true"
app:showAsAction="ifRoom"
android:title="home"/>
<item
android:icon="@drawable/ic_search_black_24dp"
android:enabled="true"
app:showAsAction="ifRoom"
android:title="search"/>
<item
android:icon="@drawable/ic_account_circle_black_24dp"
android:enabled="true"
app:showAsAction="ifRoom"
android:title="me"
/>
<item
android:icon="@drawable/ic_settings_black_24dp"
android:enabled="true"
app:showAsAction="ifRoom"
android:title="setting"
/>
</menu>
``` | /content/code_sandbox/app/src/main/res/menu/bottom.xml | xml | 2016-11-04T06:01:23 | 2024-08-02T07:46:20 | ByeBurger | githubwing/ByeBurger | 1,214 | 202 |
```xml
import { ulid } from 'ulidx'
export function generateId() {
return ulid()
}
``` | /content/code_sandbox/examples/lambda-function-url/packages/api/utils/id.ts | xml | 2016-09-13T23:29:07 | 2024-08-15T09:52:47 | serverless-express | CodeGenieApp/serverless-express | 5,117 | 23 |
```xml
import { PlanID } from '../utils'
import { Column, ColumnSubscription, PlanSource, PlanType } from './devhub'
import { GitHubTokenDetails, GraphQLGitHubUser, Installation } from './graphql'
import { StripeSubscription } from './stripe'
export interface DatabaseUserPlan {
id: PlanID
source: PlanSource
type: PlanType
stripeIds?: [string, string] | []
paddleProductId?: number
amount: number
currency: string
label: string | undefined
trialPeriodDays: number
interval: 'day' | 'week' | 'month' | 'year' | undefined
intervalCount: number
transformUsage?:
| {
divideBy: number
round: 'up' | 'down'
}
| undefined
quantity: number | undefined
coupon?: string
dealCode?: string
referralId?: string
status:
| 'incomplete'
| 'incomplete_expired'
| 'trialing'
| 'active'
| 'past_due'
| 'canceled'
| 'unpaid'
startAt: string | undefined
cancelAt: string | undefined
cancelAtPeriodEnd: boolean
trialStartAt: string | undefined
trialEndAt: string | undefined
currentPeriodStartAt: string | undefined
currentPeriodEndAt: string | undefined
last4: string | undefined
reason?: string | undefined
userPlansToKeepUsing?: boolean | null | undefined
users?: string[] | undefined
createdAt: string
updatedAt: string
}
export interface DatabaseUserFeedback {
appVersion: string
feedback?: string
isElectron: boolean
platformOS: string
platformRealOS: string
location?: string
}
export interface DatabaseUser {
_id: any
emails: {
provider: 'github' | 'npm'
email: string
primary?: boolean
verified?: boolean
visibility?: 'public' | 'private' | null
}[]
columns?: {
allIds: string[]
byId: Record<string, Column | undefined>
updatedAt: string
}
subscriptions?: {
allIds: string[]
byId: Record<string, ColumnSubscription | undefined>
updatedAt: string
}
github: {
app?: GitHubTokenDetails
oauth?: GitHubTokenDetails
personal?: GitHubTokenDetails
user: GraphQLGitHubUser
installations?: Installation[]
}
createdAt: string
updatedAt: string
lastLoginAt: string
loginCount: number
freeTrialStartAt?: string
freeTrialEndAt?: string
paddle: { [key: string]: any } | undefined | null
plan: DatabaseUserPlan
planHistory: DatabaseUserPlan[]
stripe?:
| {
customerId: string
subscription: StripeSubscription
last4: string | undefined
clientIp: string | undefined
createdAt: string
updatedAt: string
}
| undefined
feedbacks?: DatabaseUserFeedback[]
}
export interface DatabaseDeal {
code: string
planIds: string[]
// rules?: {
// emailSuffix?: string
// orgs?: string[]
// platforms?: string[]
// users?: string[]
// usersLimit?: number
// }
// statistics?: {
// claimedBy?: string[]
// usedBy?: string[]
// }
// expiresAt?: string
createdAt: string
}
``` | /content/code_sandbox/packages/core/src/types/database.ts | xml | 2016-11-30T23:24:21 | 2024-08-16T00:24:59 | devhub | devhubapp/devhub | 9,652 | 776 |
```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, type OnInit } from "@angular/core";
import { UntypedFormControl } from "@angular/forms";
import { ActivatedRoute } from "@angular/router";
import { Subject } from "rxjs";
import { AlertLevel, ResponseDeliveryService } from "trafficops-types";
import { DeliveryServiceService } from "src/app/api";
import type { DataPoint, DataSet } from "src/app/models";
import { AlertService } from "src/app/shared/alert/alert.service";
import { LoggingService } from "src/app/shared/logging.service";
import { NavigationService } from "src/app/shared/navigation/navigation.service";
/**
* DeliveryserviceComponent is the controller for a single Delivery Service's
* details page.
*/
@Component({
selector: "tp-deliveryservice",
styleUrls: ["./deliveryservice.component.scss"],
templateUrl: "./deliveryservice.component.html"
})
export class DeliveryserviceComponent implements OnInit {
/** The Delivery Service described by this component. */
public deliveryservice = {} as ResponseDeliveryService;
/** Data for the bandwidth chart. */
public bandwidthData = new Subject<[DataSet]>();
/** Data for the transactions per second chart. */
public tpsChartData: Subject<Array<DataSet>>;
/** End date for charts. */
private to: Date = new Date();
/** Start date for charts. */
private from: Date = new Date();
/**
* Form controller for the user's date selector for the end of the time
* range.
*/
public fromDate: UntypedFormControl = new UntypedFormControl();
/**
* Form controller for the user's time selector for the end of the time
* range.
*/
public fromTime: UntypedFormControl = new UntypedFormControl();
/**
* Form controller for the user's date selector for the beginning of the
* time range.
*/
public toDate: UntypedFormControl = new UntypedFormControl();
/**
* Form controller for the user's date selector for the beginning of the
* time range.
*/
public toTime: UntypedFormControl = new UntypedFormControl();
/* Contains the DS xmlIds that this DS is this steering target for. */
public steeringTargetsFor = new Set<string>();
/** The size of each single interval for data grouping, in seconds. */
private bucketSize = 300;
constructor(
private readonly route: ActivatedRoute,
private readonly api: DeliveryServiceService,
private readonly alerts: AlertService,
private readonly navSvc: NavigationService,
private readonly log: LoggingService,
) {
this.bandwidthData.next([{
backgroundColor: "#BA3C57",
borderColor: "#BA3C57",
data: new Array<DataPoint>(),
fill: false,
label: "Edge-Tier"
}]);
this.tpsChartData = new Subject<Array<DataSet>>();
}
/**
* Runs initialization, including setting up date/time range controls and
* fetching data.
*/
public ngOnInit(): void {
this.to.setUTCMilliseconds(0);
this.from = new Date(this.to.getFullYear(), this.to.getMonth(), this.to.getDate());
const dateStr = String(this.from.getFullYear()).padStart(4, "0").concat(
"-", String(this.from.getMonth() + 1).padStart(2, "0").concat(
"-", String(this.from.getDate()).padStart(2, "0")));
this.fromDate = new UntypedFormControl(dateStr);
this.fromTime = new UntypedFormControl("00:00");
this.toDate = new UntypedFormControl(dateStr);
const timeStr = String(this.to.getHours()).padStart(2, "0").concat(":", String(this.to.getMinutes()).padStart(2, "0"));
this.toTime = new UntypedFormControl(timeStr);
const DSID = this.route.snapshot.paramMap.get("id");
if (!DSID) {
this.log.error("Missing route 'id' parameter");
return;
}
this.api.getDeliveryServices(parseInt(DSID, 10)).then(
d => {
this.deliveryservice = d;
this.loadBandwidth();
this.loadTPS();
this.navSvc.headerTitle.next(d.displayName);
this.api.getSteering().then(configs => {
configs.forEach(config => {
config.targets.forEach(target => {
if (target.deliveryService === this.deliveryservice.xmlId) {
this.steeringTargetsFor.add(config.deliveryService);
}
});
});
});
}
);
}
/**
* Returns the tooltip text for the steering target displays.
*
* @returns Tooltip text.
*/
public steeringTargetDisplay(): string {
return `Steering target for: ${Array.from(this.steeringTargetsFor).join(", ")}`;
}
/**
* Runs when a new date/time range is selected by the user, updating the
* chart data accordingly.
*/
public newDateRange(): void {
this.to = new Date(this.toDate.value.concat("T", this.toTime.value));
this.from = new Date(this.fromDate.value.concat("T", this.fromTime.value));
// I need to set these explicitly, just in case - the API can't handle millisecond precision
this.to.setUTCMilliseconds(0);
this.from.setUTCMilliseconds(0);
// This should set it to the number of seconds needed to bucket 500 datapoints
this.bucketSize = (this.to.getTime() - this.from.getTime()) / 30000000;
this.loadBandwidth();
this.loadTPS();
}
/**
* Loads new data for the bandwidth chart.
*/
private async loadBandwidth(): Promise<void> {
let interval: string;
if (this.bucketSize < 1) {
interval = "1m";
} else {
interval = `${Math.round(this.bucketSize)}m`;
}
const xmlID = this.deliveryservice.xmlId;
let data;
try {
data = await this.api.getDSKBPS(xmlID, this.from, this.to, interval, false, true);
} catch (e) {
this.alerts.newAlert(AlertLevel.WARNING, "Edge-Tier bandwidth data not found!");
this.log.error(`Failed to get edge KBPS data for '${xmlID}':`, e);
return;
}
const chartData = {
backgroundColor: "#BA3C57",
borderColor: "#BA3C57",
data,
fill: false,
label: "Edge-Tier"
};
this.bandwidthData.next([chartData]);
}
/**
* Loads new data for the TPS chart.
*/
private loadTPS(): void {
let interval: string;
if (this.bucketSize < 1) {
interval = "1m";
} else {
interval = `${Math.round(this.bucketSize)}m`;
}
this.api.getAllDSTPSData(this.deliveryservice.xmlId, this.from, this.to, interval, false).then(
data => {
data.total.dataSet.label = "Total";
data.total.dataSet.borderColor = "#3C96BA";
data.success.dataSet.label = "Successful Responses";
data.success.dataSet.borderColor = "#3CBA5F";
data.redirection.dataSet.label = "Redirection Responses";
data.redirection.dataSet.borderColor = "#9f3CBA";
data.clientError.dataSet.label = "Client Error Responses";
data.clientError.dataSet.borderColor = "#BA9E3B";
data.serverError.dataSet.label = "Server Error Responses";
data.serverError.dataSet.borderColor = "#BA3C57";
this.tpsChartData.next([
data.total.dataSet,
data.success.dataSet,
data.redirection.dataSet,
data.clientError.dataSet,
data.serverError.dataSet
]);
},
e => {
this.log.error(`Failed to get edge TPS data for '${this.deliveryservice.xmlId}':`, e);
this.alerts.newAlert(AlertLevel.WARNING, "Edge-Tier transaction data not found!");
}
);
}
}
``` | /content/code_sandbox/experimental/traffic-portal/src/app/core/deliveryservice/deliveryservice.component.ts | xml | 2016-09-02T07:00:06 | 2024-08-16T03:50:21 | trafficcontrol | apache/trafficcontrol | 1,043 | 1,767 |
```xml
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<response>
<result code="1000">
<msg>Command completed successfully</msg>
</result>
<resData>
<domain:creData
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>xn--abc-873b2e7eb1k8a4lpjvv.xn--q9jyb4c</domain:name>
<domain:crDate>1999-04-03T22:00:00.0Z</domain:crDate>
<domain:exDate>2001-04-03T22:00:00.0Z</domain:exDate>
</domain:creData>
</resData>
<trID>
<clTRID>ABC-12345</clTRID>
<svTRID>server-trid</svTRID>
</trID>
</response>
</epp>
``` | /content/code_sandbox/core/src/test/resources/google/registry/flows/domain/domain_create_response_idn_minna.xml | xml | 2016-02-29T20:16:48 | 2024-08-15T19:49:29 | nomulus | google/nomulus | 1,685 | 230 |
```xml
import * as React from 'react';
import ThumbDown from '@mui/icons-material/ThumbDown';
import {
Button,
useUpdateMany,
useNotify,
useUnselectAll,
Identifier,
useListContext,
} from 'react-admin';
const noSelection: Identifier[] = [];
const BulkRejectButton = () => {
const { selectedIds = noSelection } = useListContext();
const notify = useNotify();
const unselectAll = useUnselectAll('reviews');
const [updateMany, { isPending }] = useUpdateMany(
'reviews',
{ ids: selectedIds, data: { status: 'rejected' } },
{
mutationMode: 'undoable',
onSuccess: () => {
notify('resources.reviews.notification.approved_success', {
type: 'info',
undoable: true,
});
unselectAll();
},
onError: () => {
notify('resources.reviews.notification.approved_error', {
type: 'error',
});
},
}
);
return (
<Button
label="resources.reviews.action.reject"
onClick={() => updateMany()}
disabled={isPending}
>
<ThumbDown />
</Button>
);
};
export default BulkRejectButton;
``` | /content/code_sandbox/examples/demo/src/reviews/BulkRejectButton.tsx | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 269 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.9.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="NUnit" Version="4.1.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SMAPI.ModBuildConfig.Analyzer\SMAPI.ModBuildConfig.Analyzer.csproj" />
</ItemGroup>
<Import Project="..\..\build\common.targets" />
</Project>
``` | /content/code_sandbox/src/SMAPI.ModBuildConfig.Analyzer.Tests/SMAPI.ModBuildConfig.Analyzer.Tests.csproj | xml | 2016-03-02T14:12:15 | 2024-08-16T05:34:53 | SMAPI | Pathoschild/SMAPI | 1,755 | 209 |
```xml
import * as React from 'react';
import styles from './CustomPluginDemo.module.scss';
import { ICustomPluginDemoProps } from './ICustomPluginDemo,types';
import * as strings from 'CustomPluginDemoWebPartStrings';
// used to add a chart control
import { ChartControl, ChartType, IChartPlugin } from "@pnp/spfx-controls-react/lib/ChartControl";
// Import the chart.js helpers
import * as Chart from 'chart.js';
/**
* Declare the plugins before adding them.
* Custom plugins should implement portions of the IChartPlugin interface
*/
const donutPlugins: IChartPlugin[] = [
// This plugin renders the "rounded line" donut chart
{
afterUpdate: (chart: any) => {
var a = chart.config.data.datasets.length - 1;
for (let i in chart.config.data.datasets) {
for (var j = chart.config.data.datasets[i].data.length - 1; j >= 0; --j) {
if (Number(j) == (chart.config.data.datasets[i].data.length - 1))
continue;
var arc = chart.getDatasetMeta(i).data[j];
arc.round = {
x: (chart.chartArea.left + chart.chartArea.right) / 2,
y: (chart.chartArea.top + chart.chartArea.bottom) / 2,
radius: chart.innerRadius + chart.radiusLength / 2 + (a * chart.radiusLength),
thickness: chart.radiusLength / 2 - 1,
backgroundColor: arc._model.backgroundColor
};
}
a--;
}
},
afterDraw: (chart: any) => {
var ctx = chart.chart.ctx;
for (let i in chart.config.data.datasets) {
for (var j = chart.config.data.datasets[i].data.length - 1; j >= 0; --j) {
if (Number(j) == (chart.config.data.datasets[i].data.length - 1))
continue;
var arc = chart.getDatasetMeta(i).data[j];
var startAngle = Math.PI / 2 - arc._view.startAngle;
var endAngle = Math.PI / 2 - arc._view.endAngle;
ctx.save();
ctx.translate(arc.round.x, arc.round.y);
ctx.fillStyle = arc.round.backgroundColor;
ctx.beginPath();
ctx.arc(arc.round.radius * Math.sin(endAngle), arc.round.radius * Math.cos(endAngle), arc.round.thickness, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
ctx.restore();
}
}
}
},
// This plugin renders text in the middle of the chart.
{
afterUpdate: (chart: any) => {
if (chart.config.options.elements.center) {
var helpers = Chart.helpers;
var centerConfig = chart.config.options.elements.center;
var globalConfig = Chart.defaults.global;
var ctx = chart.chart.ctx;
var fontStyle = helpers.getValueOrDefault(centerConfig.fontStyle, globalConfig.defaultFontStyle);
var fontFamily = helpers.getValueOrDefault(centerConfig.fontFamily, globalConfig.defaultFontFamily);
var fontSize = undefined;
if (centerConfig.fontSize)
fontSize = centerConfig.fontSize;
// figure out the best font size, if one is not specified
else {
ctx.save();
fontSize = helpers.getValueOrDefault(centerConfig.minFontSize, 1);
var maxFontSize = helpers.getValueOrDefault(centerConfig.maxFontSize, 256);
var maxText = helpers.getValueOrDefault(centerConfig.maxText, centerConfig.text);
do {
ctx.font = helpers.fontString(fontSize, fontStyle, fontFamily);
var textWidth = ctx.measureText(maxText).width;
// check if it fits, is within configured limits and that we are not simply toggling back and forth
if (textWidth < chart.innerRadius * 2 && fontSize < maxFontSize)
fontSize += 1;
else {
// reverse last step
fontSize -= 1;
break;
}
} while (true);
ctx.restore();
}
// save properties
chart.center = {
font: helpers.fontString(fontSize, fontStyle, fontFamily),
fillStyle: helpers.getValueOrDefault(centerConfig.fontColor, globalConfig.defaultFontColor)
};
}
},
afterDraw: (chart: any) => {
if (chart.center) {
var centerConfig = chart.config.options.elements.center;
var ctx = chart.chart.ctx;
ctx.save();
ctx.font = chart.center.font;
ctx.fillStyle = chart.center.fillStyle;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = (chart.chartArea.left + chart.chartArea.right) / 2;
var centerY = (chart.chartArea.top + chart.chartArea.bottom) / 2;
ctx.fillText(centerConfig.text, centerX, centerY);
ctx.restore();
}
}
}];
/**
* Chart.js accepts options for the plugins as well.
* To prevent the compiler from complaining,
* we defined the options as "any" and pass them on.
*/
const chartOptions: any = {
elements: {
center: {
// the longest text that could appear in the center
maxText: '100%',
text: '67%',
fontColor: styles.fontColor,
fontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
fontStyle: 'normal',
// fontSize: 12,
// if a fontSize is NOT specified, we will scale (within the below limits) maxText to take up the maximum space in the center
// if these are not specified either, we default to 1 and 256
minFontSize: 1,
maxFontSize: 256,
}
},
legend: {
display: false
}
};
export class CustomPluginDemo extends React.Component<ICustomPluginDemoProps, {}> {
/**
* Renders the (static) donut chart with the plugins passed in
*/
public render(): React.ReactElement<ICustomPluginDemoProps> {
return (
<div className={styles.customPluginDemo}>
<ChartControl
type={ChartType.Doughnut}
plugins={donutPlugins}
data={{
datasets:
[
{
label: strings.Bugs,
data: [60, 6.6666666666667, 33.333333333333],
backgroundColor: [styles.bugBackground1, styles.bugBackground2, styles.bugBackground3],
}, {
label: strings.Fixes,
data: [60, 0.44444444444444, 39.555555555556],
backgroundColor: [styles.fixesBackground1, styles.fixesBackground2, styles.fixesBackground3],
}, {
label: strings.Redesigns,
data: [
33.333333333333, 10.37037037037, 56.296296296296],
backgroundColor: [styles.redesignsBackground1, styles.redesignsBackground2, styles.redesignsBackground3],
}
]
}}
options={chartOptions}
/>
</div>
);
}
}
``` | /content/code_sandbox/samples/react-chartcontrol/src/webparts/customPluginDemo/components/CustomPluginDemo.tsx | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 1,516 |
```xml
import * as React from "react"
import { Diff } from "./../../../Services/VersionControl"
import styled from "./../../../UI/components/common"
import Octicon, { Icons } from "./../../../UI/components/Octicon"
type ChangeTypes = "change" | "addition" | "deletion"
interface ICreateIconArgs {
type: ChangeTypes
num: number
}
const BranchContainer = styled.div`
height: 100%;
width: 100%;
display: flex;
align-items: center;
`
const BranchText = styled.span`
min-width: 10px;
text-align: center;
padding: 2px 4px 0 0;
display: flex;
align-items: center;
`
export const BranchNameContainer = styled.span`
width: 100%;
margin-left: 4px;
`
const ChangeSpanContainer = styled.span`
font-size: 0.7rem;
padding: 0 0.15rem;
`
const ChangeSpan = styled.span`
padding-left: 0.25rem;
`
interface BranchProps {
branch: string
children?: React.ReactNode
diff: Diff
}
export const Branch: React.SFC<BranchProps> = ({ diff, branch, children }) =>
branch && (
<BranchContainer>
<BranchText>
<Octicon name="git-branch" />
<BranchNameContainer>
{`${branch} `}
{diff && (
<DeletionsAndInsertions
deletions={diff.deletions}
insertions={diff.insertions}
/>
)}
{children}
</BranchNameContainer>
</BranchText>
</BranchContainer>
)
const getClassNameForType = (type: ChangeTypes): Icons => {
switch (type) {
case "addition":
return "diff-added"
case "deletion":
return "diff-removed"
case "change":
return "diff-modified"
default:
return "diff-ignored"
}
}
interface ChangesProps {
deletions: number
insertions: number
}
export const DeletionsAndInsertions: React.SFC<ChangesProps> = ({ deletions, insertions }) => (
<span>
<VCSIcon type="addition" num={insertions} />
{!!(deletions && insertions) && <span key={2}>, </span>}
<VCSIcon type="deletion" num={deletions} />
</span>
)
export const VCSIcon: React.SFC<ICreateIconArgs> = ({ type, num }) =>
!!num && (
<span>
<ChangeSpanContainer>
<Octicon name={getClassNameForType(type)} />
</ChangeSpanContainer>
<ChangeSpan data-test={`${type}-${num}`}>{num}</ChangeSpan>
</span>
)
``` | /content/code_sandbox/browser/src/UI/components/VersionControl/Branch.tsx | xml | 2016-11-16T14:42:55 | 2024-08-14T11:48:05 | oni | onivim/oni | 11,355 | 622 |
```xml
/**
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "RNSVGForeignObject.h"
#import "RNSVGClipPath.h"
#import "RNSVGMask.h"
#import "RNSVGNode.h"
#ifdef RCT_NEW_ARCH_ENABLED
#import <React/RCTConversions.h>
#import <React/RCTFabricComponentsPlugins.h>
#import <react/renderer/components/rnsvg/ComponentDescriptors.h>
#import <react/renderer/components/view/conversions.h>
#import "RNSVGFabricConversions.h"
#endif // RCT_NEW_ARCH_ENABLED
@implementation RNSVGForeignObject
#ifdef RCT_NEW_ARCH_ENABLED
using namespace facebook::react;
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
static const auto defaultProps = std::make_shared<const RNSVGForeignObjectProps>();
_props = defaultProps;
}
return self;
}
#pragma mark - RCTComponentViewProtocol
+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<RNSVGForeignObjectComponentDescriptor>();
}
- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
{
const auto &newProps = static_cast<const RNSVGForeignObjectProps &>(*props);
id x = RNSVGConvertFollyDynamicToId(newProps.x);
if (x != nil) {
self.x = [RCTConvert RNSVGLength:x];
}
id y = RNSVGConvertFollyDynamicToId(newProps.y);
if (y != nil) {
self.y = [RCTConvert RNSVGLength:y];
}
id height = RNSVGConvertFollyDynamicToId(newProps.height);
if (height != nil) {
self.foreignObjectheight = [RCTConvert RNSVGLength:height];
}
id width = RNSVGConvertFollyDynamicToId(newProps.width);
if (width != nil) {
self.foreignObjectwidth = [RCTConvert RNSVGLength:width];
}
setCommonGroupProps(newProps, self);
_props = std::static_pointer_cast<RNSVGForeignObjectProps const>(props);
}
- (void)prepareForRecycle
{
[super prepareForRecycle];
_x = nil;
_y = nil;
_foreignObjectheight = nil;
_foreignObjectwidth = nil;
}
#endif // RCT_NEW_ARCH_ENABLED
- (RNSVGPlatformView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
return nil;
}
- (void)parseReference
{
self.dirty = false;
}
- (void)renderLayerTo:(CGContextRef)context rect:(CGRect)rect
{
[self clip:context];
CGContextTranslateCTM(context, [self relativeOnWidth:self.x], [self relativeOnHeight:self.y]);
CGRect clip = CGRectMake(
0, 0, [self relativeOnWidth:self.foreignObjectwidth], [self relativeOnHeight:self.foreignObjectheight]);
CGContextClipToRect(context, clip);
[super renderLayerTo:context rect:rect];
}
- (void)renderGroupTo:(CGContextRef)context rect:(CGRect)rect
{
[self pushGlyphContext];
__block CGRect bounds = CGRectNull;
[self traverseSubviews:^(RNSVGView *node) {
if ([node isKindOfClass:[RNSVGMask class]] || [node isKindOfClass:[RNSVGClipPath class]]) {
// no-op
} else if ([node isKindOfClass:[RNSVGNode class]]) {
RNSVGNode *svgNode = (RNSVGNode *)node;
if (svgNode.display && [@"none" isEqualToString:svgNode.display]) {
return YES;
}
if (svgNode.responsible && !self.svgView.responsible) {
self.svgView.responsible = YES;
}
if ([node isKindOfClass:[RNSVGRenderable class]]) {
[(RNSVGRenderable *)node mergeProperties:self];
}
[svgNode renderTo:context rect:rect];
CGRect nodeRect = svgNode.clientRect;
if (!CGRectIsEmpty(nodeRect)) {
bounds = CGRectUnion(bounds, nodeRect);
}
if ([node isKindOfClass:[RNSVGRenderable class]]) {
[(RNSVGRenderable *)node resetProperties];
}
} else if ([node isKindOfClass:[RNSVGSvgView class]]) {
RNSVGSvgView *svgView = (RNSVGSvgView *)node;
CGFloat width = [self relativeOnWidth:svgView.bbWidth];
CGFloat height = [self relativeOnHeight:svgView.bbHeight];
CGRect rect = CGRectMake(0, 0, width, height);
CGContextClipToRect(context, rect);
[svgView drawToContext:context withRect:rect];
} else {
node.hidden = false;
[node.layer renderInContext:context];
node.hidden = true;
}
return YES;
}];
CGPathRef path = [self getPath:context];
[self setHitArea:path];
if (!CGRectEqualToRect(bounds, CGRectNull)) {
self.clientRect = bounds;
self.fillBounds = CGPathGetBoundingBox(path);
self.strokeBounds = CGPathGetBoundingBox(self.strokePath);
self.pathBounds = CGRectUnion(self.fillBounds, self.strokeBounds);
CGAffineTransform current = CGContextGetCTM(context);
CGAffineTransform svgToClientTransform = CGAffineTransformConcat(current, self.svgView.invInitialCTM);
self.ctm = svgToClientTransform;
self.screenCTM = current;
CGAffineTransform transform = CGAffineTransformConcat(self.matrix, self.transforms);
CGPoint mid = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
CGPoint center = CGPointApplyAffineTransform(mid, transform);
self.bounds = bounds;
if (!isnan(center.x) && !isnan(center.y)) {
self.center = center;
}
self.frame = bounds;
}
[self popGlyphContext];
}
- (void)drawRect:(CGRect)rect
{
[self invalidate];
}
- (void)setX:(RNSVGLength *)x
{
if ([x isEqualTo:_x]) {
return;
}
_x = x;
[self invalidate];
}
- (void)setY:(RNSVGLength *)y
{
if ([y isEqualTo:_y]) {
return;
}
_y = y;
[self invalidate];
}
- (void)setForeignObjectwidth:(RNSVGLength *)foreignObjectwidth
{
if ([foreignObjectwidth isEqualTo:_foreignObjectwidth]) {
return;
}
_foreignObjectwidth = foreignObjectwidth;
[self invalidate];
}
- (void)setForeignObjectheight:(RNSVGLength *)foreignObjectheight
{
if ([foreignObjectheight isEqualTo:_foreignObjectheight]) {
return;
}
_foreignObjectheight = foreignObjectheight;
[self invalidate];
}
@end
#ifdef RCT_NEW_ARCH_ENABLED
Class<RCTComponentViewProtocol> RNSVGForeignObjectCls(void)
{
return RNSVGForeignObject.class;
}
#endif // RCT_NEW_ARCH_ENABLED
``` | /content/code_sandbox/apple/Elements/RNSVGForeignObject.mm | xml | 2016-01-17T14:29:21 | 2024-08-16T13:35:44 | react-native-svg | software-mansion/react-native-svg | 7,397 | 1,560 |
```xml
import { GeometryRenderer, FlipbookRenderer, GeometryData, MovementController, AnimationMode, SpawnedObjects, BKLayer } from './render.js';
import { vec3, mat4, vec2 } from 'gl-matrix';
import { nArray, assertExists } from '../util.js';
import { MathConstants, lerp, angleDist, scaleMatrix, randomRange } from '../MathHelpers.js';
import { getPointHermite } from '../Spline.js';
import { brentildaWandConfig, ConfigurableEmitter, Emitter, farJumpPadConfig, JumpPadEmitter, lavaRockLaunchFlameConfig, nearJumpPadConfig, ParticleType, SparkleColor, Sparkler, lavaRockBigTrailConfig, lavaRockSmallTrailConfig, MultiEmitter, lavaRockExplosionConfig, fireballIndex, lavaSmokeIndex, emitAt, lavaRockShardsConfig, lavaRockSmokeConfig, LavaRockEmitter, StreamEmitter, fromBB, SceneEmitterHolder, SnowballChunkEmitter } from './particles.js';
import { ViewerRenderInput } from '../viewer.js';
import { makeSortKey, GfxRendererLayer, GfxRenderInstManager } from '../gfx/render/GfxRenderInstManager.js';
import { GfxDevice } from '../gfx/platform/GfxPlatform.js';
export class ClankerTooth extends GeometryRenderer {
constructor(device: GfxDevice, geometryData: GeometryData, public index: number) {
super(device, geometryData);
}
}
const enum BoltState {
InClanker,
Rising,
AtPeak,
Falling,
}
const scratchVec = vec3.create();
export class ClankerBolt extends GeometryRenderer {
private static peak = vec3.fromValues(2640, 5695, -10);
public clankerVector: vec3;
private boltState = BoltState.InClanker;
protected override movement(): void {
let timer = this.animationController.getTimeInSeconds();
vec3.copy(scratchVec, this.clankerVector);
let newState = this.boltState;
switch (this.boltState) {
case BoltState.InClanker:
if (timer >= 2 && Math.hypot(scratchVec[0] - ClankerBolt.peak[0], scratchVec[2] - ClankerBolt.peak[2]) <= 60)
newState = BoltState.Rising;
break;
case BoltState.Rising:
if (timer >= 1) newState = BoltState.AtPeak;
break;
case BoltState.AtPeak:
if (timer >= 1) newState = BoltState.Falling;
break;
case BoltState.Falling:
if (timer >= 1) newState = BoltState.InClanker;
break;
}
if (this.boltState !== newState) {
this.boltState = newState;
timer = 0;
this.animationController.resetPhase();
}
switch (this.boltState) {
case BoltState.InClanker: break; // already set
case BoltState.Rising:
vec3.lerp(scratchVec, scratchVec, ClankerBolt.peak, Math.sin(timer * Math.PI / 2));
break;
case BoltState.AtPeak:
vec3.copy(scratchVec, ClankerBolt.peak);
break;
case BoltState.Falling:
vec3.lerp(scratchVec, scratchVec, ClankerBolt.peak, Math.cos(timer * Math.PI / 2));
break;
}
mat4.fromTranslation(this.modelMatrix, scratchVec);
}
}
class ShinyObject extends GeometryRenderer {
constructor(device: GfxDevice, geometryData: GeometryData, emitters: SceneEmitterHolder, sparkleRate: number, private turnRate: number = 0, sparkleColor = SparkleColor.Yellow) {
super(device, geometryData);
for (let i = 0; i < 4; i++) {
const sparkler = new Sparkler(sparkleRate, sparkleColor);
sparkler.movementController = new ModelPin(this.modelPointArray, i + 5);
emitters.flipbookManager.emitters.push(sparkler);
}
}
protected override movement(viewerInput: ViewerRenderInput) {
mat4.rotateY(this.modelMatrix, this.modelMatrix, viewerInput.deltaTime / 1000 * this.turnRate * MathConstants.DEG_TO_RAD);
}
}
class Brentilda extends GeometryRenderer {
constructor(device: GfxDevice, geometryData: GeometryData, emitters: SceneEmitterHolder) {
super(device, geometryData);
const wandEmitter = new ConfigurableEmitter(brentildaWandConfig);
wandEmitter.movementController = new ModelPin(this.modelPointArray, 31);
emitters.flipbookManager.emitters.push(wandEmitter);
}
}
class MovingJumpPad extends GeometryRenderer {
private center = vec3.create();
private emitters: ConfigurableEmitter[] = [];
constructor(device: GfxDevice, geometryData: GeometryData, emitters: SceneEmitterHolder) {
super(device, geometryData);
this.emitters.push(
new JumpPadEmitter(nearJumpPadConfig),
new JumpPadEmitter(farJumpPadConfig),
);
emitters.flipbookManager.emitters.push(...this.emitters);
}
protected override movement(viewerInput: ViewerRenderInput) {
if (this.center[0] === 0 && this.center[2] === 0) {
// store the center, can't do in constructor because we don't know the position until later...
mat4.getTranslation(this.center, this.modelMatrix);
}
const angle = 75 * MathConstants.DEG_TO_RAD * this.animationController.getTimeInSeconds();
this.modelMatrix[12] = this.center[0] + 590 * Math.cos(angle);
this.modelMatrix[14] = this.center[2] - 590 * Math.sin(angle);
const trailingAngle = angle - 10 * MathConstants.DEG_TO_RAD;
this.emitters[0].modelMatrix[12] = this.center[0] + 590 * Math.cos(trailingAngle);
this.emitters[0].modelMatrix[14] = this.center[2] - 590 * Math.sin(trailingAngle);
mat4.copy(this.emitters[1].modelMatrix, this.emitters[0].modelMatrix);
}
}
const chunkVelMin = vec3.fromValues(-220, 210, -220);
// horizontal max is 280 in game, not sure why
const chunkVelMax = vec3.fromValues(220, 460, 220);
const chunkScratch = nArray(2, () => vec3.create());
export class SnowballChunk extends GeometryRenderer {
public override movementController: Projectile = new Projectile(800);
public timer = -1;
public override sortKeyBase = makeSortKey(GfxRendererLayer.TRANSLUCENT + BKLayer.Particles);
public init(start: mat4) {
this.timer = .8;
// put in translucent object layer since these fade out
mat4.getTranslation(chunkScratch[0], start);
for (let i = 0; i < 3; i++)
chunkScratch[0][i] += randomRange(20);
fromBB(chunkScratch[1], chunkVelMin, chunkVelMax);
this.movementController.setFromVel(chunkScratch[0], chunkScratch[1]);
vec2.set(this.movementController.angularVel,
randomRange(300 * MathConstants.DEG_TO_RAD),
randomRange(300 * MathConstants.DEG_TO_RAD),
);
this.movementController.scale = randomRange(.65, 1.1);
this.setEnvironmentAlpha(1);
}
protected override movement(viewerInput: ViewerRenderInput) {
super.movement(viewerInput);
if (this.timer < .4)
this.setEnvironmentAlpha(this.timer / .4);
this.timer -= viewerInput.deltaTime / 1000;
}
}
const enum SnowballState {
Dead,
Aiming,
Flying,
}
const snowballScratch = vec3.create();
export class Snowball extends GeometryRenderer {
private target = vec3.create();
public state = SnowballState.Dead;
public override movementController: Projectile = new Projectile(1800);
private sparkleEmitter = new StreamEmitter(30, ParticleType.SnowSparkle);
private chunkEmitter = new SnowballChunkEmitter();
constructor(device: GfxDevice, geometryData: GeometryData, emitters: SceneEmitterHolder) {
super(device, geometryData);
this.die();
emitters.flipbookManager.emitters.push(this.sparkleEmitter);
this.sparkleEmitter.movementController = new ModelPin(this.modelPointArray, 5);
emitters.snowballChunkManager.emitters.push(this.chunkEmitter);
}
private static computeTarget(dst: vec3, cameraToWorld: mat4): void {
// aim slightly in front of and below camera
vec3.set(dst, 0, -30, -60);
vec3.transformMat4(dst, dst, cameraToWorld);
}
public init(start: vec3, camera: mat4): void {
this.sparkleEmitter.active = true;
this.state = SnowballState.Aiming;
mat4.fromTranslation(this.modelMatrix, start);
Snowball.computeTarget(this.target, camera);
this.animationController.resetPhase();
}
protected override movement(viewerInput: ViewerRenderInput) {
const flightTime = this.animationController.getTimeInSeconds();
if (flightTime < 1 / 30)
return;
if (this.state === SnowballState.Aiming) {
this.state = SnowballState.Flying;
// project position using constant velocity
Snowball.computeTarget(snowballScratch, viewerInput.camera.worldMatrix);
vec3.sub(this.target, snowballScratch, this.target);
vec3.scaleAndAdd(this.target, snowballScratch, this.target, Math.random() > .5 ? 21 : 43);
mat4.getTranslation(snowballScratch, this.modelMatrix);
this.movementController.setFromTarget(snowballScratch, this.target, 32 / 30);
vec2.set(this.movementController.angularVel, 300 * MathConstants.DEG_TO_RAD, 300 * MathConstants.DEG_TO_RAD);
}
super.movement(viewerInput);
if (flightTime < 1 / 5)
return;
if (flightTime > 6 || this.modelMatrix[13] < -1000) {
this.die();
return;
}
mat4.getTranslation(snowballScratch, this.modelMatrix);
vec3.transformMat4(snowballScratch, snowballScratch, viewerInput.camera.viewMatrix);
if (vec3.len(snowballScratch) < 100) {
Snowball.computeTarget(snowballScratch, viewerInput.camera.worldMatrix);
mat4.fromTranslation(this.chunkEmitter.modelMatrix, snowballScratch);
this.chunkEmitter.emitCount = 8;
this.die();
}
}
private die(): void {
this.state = SnowballState.Dead;
this.sparkleEmitter.active = false;
}
}
function turnTowards(mat: mat4, delta: number, cap: number): void {
if (delta > cap)
delta = cap;
else if (delta < -cap)
delta = -cap;
mat4.rotateY(mat, mat, delta);
}
const enum SirSlushState {
Idle,
Throwing,
// there is also a third, unanimated state for when the player is far away
// we just use the idle animation for that case
}
const sirSlushScratch = nArray(2, () => vec3.create());
export class SirSlush extends GeometryRenderer {
public snowball: Snowball;
private throwTimer = 0;
constructor(device: GfxDevice, geometryData: GeometryData) {
super(device, geometryData);
this.currAnimation = SirSlushState.Idle;
this.animationMode = AnimationMode.Loop;
}
public override additionalSetup(spawner: (id: number) => SpawnedObjects, id: number, selector = 0): void {
this.snowball = spawner(0x125)[0] as Snowball;
}
protected override movement(viewerInput: ViewerRenderInput) {
mat4.getTranslation(sirSlushScratch[0], this.modelMatrix);
mat4.getTranslation(sirSlushScratch[1], viewerInput.camera.worldMatrix);
vec3.sub(sirSlushScratch[0], sirSlushScratch[1], sirSlushScratch[0]);
const toCamera = sirSlushScratch[0];
const cameraDist = vec3.len(toCamera);
const yawToCamera = Math.atan2(toCamera[0], toCamera[2]);
const facingYaw = Math.atan2(this.modelMatrix[8], this.modelMatrix[10]);
let angleDelta = angleDist(facingYaw, yawToCamera);
const turnCap = Math.PI * viewerInput.deltaTime / 1000;
// in game height range is 500, roughly the hat height
const inThrowRange = cameraDist > 500 && cameraDist < 2750 && toCamera[1] < 1500;
switch (this.currAnimation) {
case SirSlushState.Idle:
this.selectorState.values[1] = 0; // turn off snowball
if (this.throwTimer > 0)
this.throwTimer -= viewerInput.deltaTime / 1000;
else if (inThrowRange && Math.abs(angleDelta) < 9 * MathConstants.DEG_TO_RAD && this.snowball.state === SnowballState.Dead)
this.changeAnimation(SirSlushState.Throwing, AnimationMode.Once);
if (cameraDist < 3150)
turnTowards(this.modelMatrix, angleDelta, turnCap);
break;
case SirSlushState.Throwing:
if (this.getAnimationPhase() > .98 || !inThrowRange) {
this.changeAnimation(SirSlushState.Idle, AnimationMode.Loop);
this.throwTimer = .4;
return;
}
if (this.getAnimationPhase() < .45)
turnTowards(this.modelMatrix, angleDelta, turnCap);
if (this.animationPhaseTrigger(.45))
this.selectorState.values[1] = 1;
if (this.animationPhaseTrigger(.58)) {
this.selectorState.values[1] = 0;
vec3.copy(sirSlushScratch[0], assertExists(this.modelPointArray[5]));
this.snowball.init(sirSlushScratch[0], viewerInput.camera.worldMatrix);
}
break;
}
}
public override prepareToRender(device: GfxDevice, renderInstManager: GfxRenderInstManager, viewerInput: ViewerRenderInput): void {
super.prepareToRender(device, renderInstManager, viewerInput);
if (this.snowball.state !== SnowballState.Dead)
this.snowball.prepareToRender(device, renderInstManager, viewerInput);
}
}
interface LerpEndpoint {
pairIndex: number;
time: number;
useAngle: boolean;
keyYaw: number;
keyPitch: number;
useSpeed: boolean;
keySpeed: number;
}
interface RailLerp {
range: [number, number];
yaw?: [number, number];
pitch?: [number, number];
speed?: [number, number];
}
const enum AngleUpdate {
None,
Rail,
Lerp,
}
class RailKeyframe {
public facePlayer = false;
public yawUpdate = AngleUpdate.None;
public pitchUpdate = AngleUpdate.None;
public animMode = AnimationMode.None;
public speedSign = 0;
public timeToEnd = 0;
public waitTime = 0;
public waitIndex = 0;
public distToEnd = 0;
constructor(public time: number) { }
}
interface KeyframeData {
kind: "keyframe";
keyframe: RailKeyframe;
lerpEndpoint: LerpEndpoint;
}
interface CameraData {
kind: "camera";
time: number;
}
type RailData = vec3 | KeyframeData | CameraData;
export interface RailNode {
next: number;
data: RailData;
}
export interface Rail {
points: vec3[];
loopStart: number;
keyframes: RailKeyframe[];
lerps: RailLerp[];
}
export function buildKeyframeData(view: DataView, offs: number): KeyframeData | CameraData {
const time = view.getFloat32(offs + 0x00);
const isSpecial = !!(view.getUint32(offs + 0x0C) & 1);
if (isSpecial)
return { kind: "camera", time };
const pairIndex = view.getUint16(offs + 0x04) >>> 4;
const lerpFlags = view.getUint16(offs + 0x04) & 0x0f;
const keyPitch = view.getUint16(offs + 0x06) >>> 7;
const angleUpdateType = (view.getUint16(offs + 0x06) >> 4) & 0x07;
const animUpdateType = (view.getUint16(offs + 0x06) >> 1) & 0x07;
const animFile = view.getUint32(offs + 0x08) >>> 22;
const animDuration = ((view.getUint32(offs + 0x08) >>> 11) & 0x7ff) / 4;
const updateFlags = view.getUint8(offs + 0x0A) & 0x07;
// next byte set to track index
const keyYaw = view.getUint16(offs + 0x0C) >>> 7;
const keySpeed = (view.getUint32(offs + 0x0C) >>> 12) & 0x7ff;
const waitParam = (view.getUint32(offs + 0x0C) >>> 1) & 0x7ff;
// current and next indices
const moreFlags = view.getUint8(offs + 0x13) >>> 4;
const useAngle = !!(lerpFlags & 1);
const useSpeed = !!(lerpFlags & 2);
const lerpEndpoint: LerpEndpoint = { time, pairIndex, keyPitch, keySpeed, keyYaw, useAngle, useSpeed };
const keyframe = new RailKeyframe(time);
if (updateFlags & 1) {
if (moreFlags & 2)
keyframe.waitIndex = (waitParam - 0x69) % 15;
else
keyframe.waitTime = waitParam / 4;
}
if (updateFlags & 2)
keyframe.timeToEnd = keySpeed / 4; // presumably not a lerp endpoint
if (updateFlags & 4) { }// support for changing animations, only for cutscenes?
switch (angleUpdateType) {
case 1:
keyframe.facePlayer = true;
keyframe.yawUpdate = AngleUpdate.Lerp;
keyframe.pitchUpdate = AngleUpdate.Lerp;
break;
case 2:
keyframe.yawUpdate = AngleUpdate.Rail;
break;
case 3:
keyframe.yawUpdate = AngleUpdate.Lerp;
break;
case 4:
keyframe.pitchUpdate = AngleUpdate.Rail;
break;
case 5:
keyframe.pitchUpdate = AngleUpdate.Lerp;
break;
case 6:
keyframe.yawUpdate = AngleUpdate.Rail;
keyframe.pitchUpdate = AngleUpdate.Rail;
break;
case 7:
keyframe.yawUpdate = AngleUpdate.Lerp;
keyframe.pitchUpdate = AngleUpdate.Lerp;
}
switch (animUpdateType) {
case 2:
keyframe.speedSign = 1;
keyframe.animMode = AnimationMode.Once;
break;
case 3:
keyframe.speedSign = -1;
keyframe.animMode = AnimationMode.Once;
break;
case 4:
keyframe.speedSign = 1;
keyframe.animMode = AnimationMode.Loop;
break;
case 5:
keyframe.speedSign = -1;
keyframe.animMode = AnimationMode.Loop;
}
// TODO: understand impact of other lerpFlags and moreFlags logic
return { kind: "keyframe", keyframe, lerpEndpoint };
}
function isKeyframe(data: RailData): data is KeyframeData {
return "kind" in data && data.kind === "keyframe";
}
function isPoint(data: RailData): data is vec3 {
return !("kind" in data);
}
export function buildRails(nodes: (RailNode | undefined)[]): Rail[] {
const allRails: Rail[] = [];
const childNodes = new Set<number>();
const usedNodes = new Set<number>();
// preprocess
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node === undefined)
continue;
if (node.next > nodes.length)
node.next = 0;
else
childNodes.add(node.next);
}
for (let i = 1; i <= nodes.length; i++) {
if (childNodes.has(i))
continue;
const startNode = nodes[i];
if (startNode === undefined)
continue;
if (startNode.next === 0 || !isPoint(startNode.data))
continue;
const points = [startNode.data];
const keyframes: RailKeyframe[] = [];
const lerpEnds: LerpEndpoint[] = [];
const lerps: RailLerp[] = [];
let nextIndex = startNode.next;
usedNodes.clear();
while (nextIndex !== 0) {
const curr = nodes[nextIndex];
if (curr === undefined) {
console.warn('bad next node index', nextIndex);
break;
}
if (isKeyframe(curr.data)) {
keyframes.push(curr.data.keyframe);
lerpEnds.push(curr.data.lerpEndpoint);
} else if (isPoint(curr.data))
points.push(curr.data);
// an already used node indicates a loop, break after adding it
if (usedNodes.has(nextIndex))
break;
usedNodes.add(nextIndex);
nextIndex = curr.next;
}
keyframes.sort((a, b) => a.time - b.time);
for (let i = 0; i < lerpEnds.length; i++) {
const end = lerpEnds[i];
if (end.pairIndex === 0)
continue;
const startNode = nodes[end.pairIndex];
if (startNode === undefined) {
console.warn("missing lerp start index", end.pairIndex);
continue;
}
if (!isKeyframe(startNode.data)) {
console.warn(`lerp from non keyframe`);
continue;
}
const start = startNode.data.lerpEndpoint;
const newLerp: RailLerp = { range: [start.time, end.time] };
// end node controls the behavior
if (end.useAngle) {
newLerp.yaw = [start.keyYaw, end.keyYaw];
newLerp.pitch = [start.keyPitch, end.keyPitch];
}
if (end.useSpeed)
newLerp.speed = [start.keySpeed, end.keySpeed];
lerps.push(newLerp);
}
let lengthAcc = 0;
let endParam = 1;
for (let j = keyframes.length - 1; j >= 0; j--) {
lengthAcc += calcRailDist(points, keyframes[j].time, endParam);
keyframes[j].distToEnd = lengthAcc;
endParam = keyframes[j].time;
}
// a point exactly equal to the last point indicates a loop in the rail
let loopStart = 1;
const lastPoint = points[points.length - 1];
for (let i = 0; i < points.length - 1; i++) {
if (vec3.exactEquals(points[i], lastPoint)) {
loopStart = i / (points.length - 1);
break;
}
}
allRails.push({ points, keyframes, loopStart, lerps });
}
return allRails;
}
function getKeyframeIndex(rail: Rail, param: number): number {
for (let i = 0; i < rail.keyframes.length; i++) {
if (param <= rail.keyframes[i].time)
return i;
}
return rail.keyframes.length;
}
const railScratch = nArray(2, () => vec3.create());
function calcRailDist(points: vec3[], start: number, end: number): number {
let dist = 0;
let ind = 1;
calcRailPos(railScratch[0], points, start);
while (start < end) {
calcRailPos(railScratch[ind], points, start);
dist += vec3.dist(railScratch[1 - ind], railScratch[ind]);
ind = 1 - ind;
start += 1e-4;
}
return dist;
}
function rideRail(dst: vec3, rail: Rail, param: number, target: number): number {
calcRailPos(dst, rail.points, param);
if (target === 0)
return param; // no movement required
let step = target > 0 ? .01 : -.01;
target = Math.abs(target);
while (Math.abs(step) > 1e-7) {
let trialDist = 0;
let trialParam = param + step;
if (rail.loopStart < 1 && (step > 0 && trialParam >= 1) || (step < 0 && trialParam < rail.loopStart)) {
// shift by the loop length
trialParam += (rail.loopStart - 1) * (step > 0 ? 1 : -1);
// we've looped around, so break the path into two parts across the loop point
// note that in reverse, any rail before the loop starts would be skipped
calcRailPos(railScratch[0], rail.points, trialParam);
vec3.copy(railScratch[1], rail.points[rail.points.length - 1]); // loop point is also the last
// game does something different, which doesn't make physical sense but is faster?
// it takes absolute value of the deltas' components, adds the new vectors, and uses *that* length
trialDist = vec3.dist(dst, railScratch[1]) + vec3.dist(railScratch[1], railScratch[0]);
} else {
// clamp linear rails to endpoints
if (rail.loopStart === 1)
if (trialParam > 1)
trialParam = 1;
else if (trialParam < 0)
trialParam = 0;
calcRailPos(railScratch[0], rail.points, trialParam);
trialDist = vec3.dist(dst, railScratch[0]);
}
const closeEnough = Math.abs(target - trialDist) < 0.1;
if (trialDist < target || closeEnough) {
param = trialParam;
target -= trialDist;
vec3.copy(dst, railScratch[0]);
if (closeEnough)
return param;
// if we hit the end of a linear rail, we're done
if (rail.loopStart === 1) {
if (step > 0 && trialParam === 1)
return 1;
if (step < 0 && trialParam === 0)
return 0;
}
} else {
// we overshot, try again with a smaller step
step /= 2;
}
}
return param;
}
const s0Scratch = vec3.create();
const s1Scratch = vec3.create();
const railPointScratch: vec3[] = nArray(4, () => s0Scratch);
function calcRailPos(dst: vec3, pts: vec3[], t: number): void {
if (t >= 1) {
vec3.copy(dst, pts[pts.length - 1]);
return;
} else if (t <= 0) {
vec3.copy(dst, pts[0]);
return;
}
if (pts.length < 4) {
railPointScratch[0] = pts[0];
railPointScratch[1] = pts[0];
railPointScratch[2] = pts[1];
railPointScratch[3] = pts.length === 2 ? pts[1] : pts[2];
calcRailPos(dst, railPointScratch, t);
return;
}
const scaledParam = (pts.length - 1) * t;
const startIndex = scaledParam >>> 0;
const p0 = pts[startIndex];
const p1 = pts[startIndex + 1];
if (startIndex > 0)
vec3.sub(s0Scratch, p1, pts[startIndex - 1]);
else
vec3.sub(s0Scratch, p1, p0);
if (startIndex + 2 < pts.length)
vec3.sub(s1Scratch, pts[startIndex + 2], p0);
else
vec3.sub(s1Scratch, p1, p0);
vec3.scale(s0Scratch, s0Scratch, .5);
vec3.scale(s1Scratch, s1Scratch, .5);
for (let i = 0; i < 3; i++)
dst[i] = getPointHermite(p0[i], p1[i], s0Scratch[i], s1Scratch[i], scaledParam % 1);
}
const railEulerScratch = nArray(2, () => vec3.create());
function calcRailEuler(dst: vec3, rail: Rail, param: number): void {
calcRailPos(railEulerScratch[0], rail.points, param);
const testParam = (param + .0001 >= 1) ? param - .0001 : param;
rideRail(railEulerScratch[1], rail, testParam, 5);
const delta = railEulerScratch[0];
vec3.sub(delta, railEulerScratch[1], railEulerScratch[0]);
dst[0] = -Math.atan2(delta[1], Math.hypot(delta[0], delta[2]));
dst[1] = Math.atan2(delta[0], delta[2]);
dst[2] = 0;
}
const riderScratch = vec3.create();
export class RailRider extends GeometryRenderer {
public waitTimer = 0;
public moveTimer = 0;
public rail: Rail | null = null;
public speed = 100;
public facePlayer = false;
public railYaw = true;
public railPitch = true;
constructor(device: GfxDevice, geometryData: GeometryData) {
super(device, geometryData);
}
public setRail(rails: Rail[]): void {
mat4.getTranslation(riderScratch, this.modelMatrix);
for (let i = 0; i < rails.length; i++) {
for (let j = 0; j < rails[i].points.length; j++) {
if (vec3.exactEquals(riderScratch, rails[i].points[j])) {
this.rail = rails[i];
this.moveTimer = j / (rails[i].points.length - 1);
break;
}
}
if (this.rail !== null) {
break;
}
}
}
protected applyKeyframe(keyframe: RailKeyframe): void {
this.facePlayer = keyframe.facePlayer;
if (keyframe.pitchUpdate === AngleUpdate.Lerp)
this.railPitch = false;
else if (keyframe.pitchUpdate === AngleUpdate.Rail)
this.railPitch = true;
if (keyframe.yawUpdate === AngleUpdate.Lerp)
this.railYaw = false;
else if (keyframe.yawUpdate === AngleUpdate.Rail)
this.railYaw = true;
if (keyframe.animMode !== AnimationMode.None)
this.animationMode = keyframe.animMode;
this.waitTimer = keyframe.waitTime;
if (keyframe.waitIndex > 0)
this.waitTimer = 1 / 30; // pause might be incidental, stores the index somewhere
if (keyframe.speedSign !== 0)
this.speed = keyframe.speedSign * Math.abs(this.speed);
if (keyframe.timeToEnd > 0)
this.speed = keyframe.distToEnd / keyframe.timeToEnd;
}
protected override movement(viewerInput: ViewerRenderInput): void {
const deltaSeconds = viewerInput.deltaTime / 1000;
if (this.rail === null)
return;
if (this.waitTimer > 0) {
this.waitTimer = Math.max(this.waitTimer - deltaSeconds, 0);
return;
}
const oldIndex = getKeyframeIndex(this.rail, this.moveTimer);
this.moveTimer = rideRail(riderScratch, this.rail, this.moveTimer, this.speed * deltaSeconds);
mat4.fromTranslation(this.modelMatrix, riderScratch);
const newIndex = getKeyframeIndex(this.rail, this.moveTimer);
if (oldIndex !== newIndex) {
// process all keyframes we passed
const keyCount = this.rail.keyframes.length;
let step = 1;
let i = oldIndex;
let end = newIndex;
if (this.speed < 0) {
step = -1;
i--;
end--;
}
while (i !== end) {
// end might be oob, so wrap *after* comparing
if (i < 0)
i = keyCount - 1;
else if (i >= keyCount)
i = 0;
this.applyKeyframe(this.rail.keyframes[i]);
i += step;
}
}
if (this.facePlayer) {
console.warn("face player for object"); // only camera?
} else {
calcRailEuler(riderScratch, this.rail, this.moveTimer);
if (this.railYaw)
mat4.rotateY(this.modelMatrix, this.modelMatrix, riderScratch[1]);
if (this.railPitch)
mat4.rotateX(this.modelMatrix, this.modelMatrix, riderScratch[0]);
// no roll from a rail
}
}
}
const enum GloopState {
Swim,
Bubble,
}
class Gloop extends RailRider {
private bubbler = new Emitter(ParticleType.AirBubble);
constructor(device: GfxDevice, geometryData: GeometryData, emitters: SceneEmitterHolder) {
super(device, geometryData);
this.bubbler.movementController = new ModelPin(this.modelPointArray, 5);
emitters.flipbookManager.emitters.push(this.bubbler);
}
protected override movement(viewerInput: ViewerRenderInput): void {
super.movement(viewerInput);
let anim = GloopState.Swim;
let mode = AnimationMode.Loop;
if (this.waitTimer > 0) {
anim = GloopState.Bubble;
mode = AnimationMode.Once;
}
if (anim === GloopState.Bubble && this.animationPhaseTrigger(0.6))
this.bubbler.emitCount = 1;
if (anim !== this.currAnimation)
this.changeAnimation(anim, mode);
}
}
const enum CarpetState {
Normal,
Disappearing,
Hidden,
Reappearing,
}
function triangleWave(t: number, min: number, max: number, halfPeriod: number): number {
const relTime = t/halfPeriod;
return lerp(max, min, Math.abs((relTime % 2) - 1));
}
class MagicCarpet extends RailRider {
public override currAnimation = CarpetState.Normal;
public override animationMode = AnimationMode.Loop;
private blinkTimer = 0;
private emitter = new StreamEmitter(30, ParticleType.Carpet);
constructor(device: GfxDevice, geometryData:GeometryData, emitters: SceneEmitterHolder) {
super(device, geometryData);
this.emitter.movementController = new ModelPin(this.modelPointArray, 6);
emitters.flipbookManager.emitters.push(this.emitter);
}
protected override applyKeyframe(keyframe: RailKeyframe): void {
super.applyKeyframe(keyframe);
this.railPitch = false; // actually sets pitch to 0
}
protected override movement(viewerInput: ViewerRenderInput): void {
let opacity = 1;
switch (this.currAnimation) {
case CarpetState.Normal:
this.emitter.active = true;
super.movement(viewerInput);
if (this.waitTimer > 0)
this.changeAnimation(CarpetState.Disappearing, AnimationMode.None);
break;
case CarpetState.Disappearing:
this.emitter.active = false;
opacity = triangleWave(this.blinkTimer, 1, 0, 1 / 10);
if (this.blinkTimer >= 1.5) {
this.blinkTimer = 0;
this.changeAnimation(CarpetState.Hidden, AnimationMode.None);
}
this.blinkTimer += viewerInput.deltaTime / 1000;
break;
case CarpetState.Hidden:
super.movement(viewerInput);
opacity = 0;
if (this.waitTimer === 0)
this.changeAnimation(CarpetState.Reappearing, AnimationMode.None);
break;
case CarpetState.Reappearing:
// the game reactivates the emitter here, possibly a bug as the animation is stopped
// it tries to check for motion by saving the old moveTimer, but uses a member that's probably a union,
// and an unrelated function modifies the same value so that the emitter isn't skipped
opacity = triangleWave(this.blinkTimer, 0, 1, 1 / 10);
if (this.blinkTimer >= 1.5) {
this.blinkTimer = 0;
this.changeAnimation(CarpetState.Normal, AnimationMode.Loop);
}
this.blinkTimer += viewerInput.deltaTime / 1000;
}
this.setEnvironmentAlpha(opacity);
}
}
const lavaRockScratch = nArray(2, () => vec3.create());
export class LavaRock extends GeometryRenderer {
public static g = 1000;
public override movementController: Projectile = new Projectile(LavaRock.g);
public timer = -1;
private explode = false;
private flameEmitter = new ConfigurableEmitter(lavaRockLaunchFlameConfig);
private bigTrail = new ConfigurableEmitter(lavaRockBigTrailConfig);
private smallTrail = new ConfigurableEmitter(lavaRockSmallTrailConfig);
private smokeEmitter = new ConfigurableEmitter(lavaRockSmokeConfig);
private explosionEmitter = new MultiEmitter(lavaRockExplosionConfig, [fireballIndex, lavaSmokeIndex]);
private lavaSparkleEmitter = new MultiEmitter(lavaRockShardsConfig, [SparkleColor.Orange, SparkleColor.Red]);
private sparkleEmitter = new MultiEmitter(lavaRockShardsConfig, [SparkleColor.DarkBlue, SparkleColor.Green]);
public parent: LavaRockEmitter;
constructor(device: GfxDevice, geometryData: GeometryData, emitters: SceneEmitterHolder) {
super(device, geometryData);
emitters.flipbookManager.emitters.push(
this.flameEmitter,
this.bigTrail,
this.smallTrail,
this.smokeEmitter,
this.explosionEmitter,
this.lavaSparkleEmitter,
this.sparkleEmitter,
);
this.flameEmitter.active = false;
this.smokeEmitter.active = false;
this.explosionEmitter.active = false;
this.lavaSparkleEmitter.active = false;
this.sparkleEmitter.active = false;
this.bigTrail.active = false;
this.smallTrail.active = false;
}
public reset(emitter: LavaRockEmitter, end: mat4, big: boolean) {
this.parent = emitter;
this.animationController.resetPhase();
mat4.getTranslation(lavaRockScratch[0], emitter.modelMatrix);
mat4.getTranslation(lavaRockScratch[1], end);
const initialRise = lerp(1400, big ? 1200 : 1800, Math.random());
this.timer = Math.sqrt(2 * initialRise / LavaRock.g) + Math.sqrt(2 * (initialRise + lavaRockScratch[0][1] - lavaRockScratch[1][1]) / LavaRock.g);
this.movementController.setFromTarget(lavaRockScratch[0], lavaRockScratch[1], this.timer);
vec2.set(this.movementController.angularVel,
randomRange(1, 2) * 240 * MathConstants.DEG_TO_RAD,
-randomRange(1, 2) * 240 * MathConstants.DEG_TO_RAD,
);
this.movementController.scale = randomRange(big ? .8 : .2, big ? 1 : .6);
this.explode = !big && (Math.random() > .5);
// activate appropriate flame trail
if (big)
this.bigTrail.active = true;
else
this.smallTrail.active = true;
// TODO: sparkle trail? if I can understand the condition
this.flameEmitter.emitCount = 3;
this.flameEmitter.modelMatrix[12] = emitter.modelMatrix[12];
this.flameEmitter.modelMatrix[13] = emitter.modelMatrix[13] + 100;
this.flameEmitter.modelMatrix[14] = emitter.modelMatrix[14];
}
protected override movement(viewerInput: ViewerRenderInput) {
super.movement(viewerInput);
// move these along, but respect their existing emit logic
emitAt(this.bigTrail, this.modelMatrix, 0);
emitAt(this.smallTrail, this.modelMatrix, 0);
if (this.movementController.reachedPeak && this.explode) {
emitAt(this.explosionEmitter, this.modelMatrix, 2);
emitAt(this.sparkleEmitter, this.modelMatrix, 4);
emitAt(this.smokeEmitter, this.modelMatrix, 4);
this.die();
return;
}
this.timer -= viewerInput.deltaTime/1000;
if (this.timer < 0) {
// fell back into lava
emitAt(this.lavaSparkleEmitter, this.modelMatrix, 4);
emitAt(this.smokeEmitter, this.modelMatrix, 4);
this.flameEmitter.emitCount = 3;
this.flameEmitter.modelMatrix[12] = this.modelMatrix[12];
this.flameEmitter.modelMatrix[13] = this.modelMatrix[13] + 100;
this.flameEmitter.modelMatrix[14] = this.modelMatrix[14];
this.die();
}
}
private die() {
this.timer = -1;
this.parent.ready = true;
this.bigTrail.active = false;
this.smallTrail.active = false;
}
}
export const clankerID = 0x10001;
// TODO: avoid having to thread the emitter list all the way through
export function createRenderer(device: GfxDevice, emitters: SceneEmitterHolder, objectID: number, geometryData: GeometryData): GeometryRenderer | FlipbookRenderer {
switch (objectID) {
case 0x043: return new ClankerBolt(device, geometryData);
case 0x044: return new ClankerTooth(device, geometryData, 7); // left
case 0x045: return new ClankerTooth(device, geometryData, 9); // right
case 0x046: return new ShinyObject(device, geometryData, emitters, .015, 230); // jiggy
case 0x047: // empty honeycomb
case 0x050: // honeycomb
return new ShinyObject(device, geometryData, emitters, .03, Math.random() > .5 ? 200 : -200);
case 0x1d8: return new ShinyObject(device, geometryData, emitters, 1 / 60, 0, SparkleColor.DarkBlue);
case 0x1d9: return new ShinyObject(device, geometryData, emitters, 1 / 60, 0, SparkleColor.Red);
case 0x1da: return new ShinyObject(device, geometryData, emitters, 1 / 60);
case 0x0e6: return new Gloop(device, geometryData, emitters);
case 0x0f1: return new RailRider(device, geometryData); // swamp leaf
case 0x123: return new MagicCarpet(device, geometryData, emitters);
case 0x124: return new SirSlush(device, geometryData);
case 0x125: return new Snowball(device, geometryData, emitters);
case 0x249: return new MovingJumpPad(device, geometryData, emitters);
case 0x348: return new Brentilda(device, geometryData, emitters);
case 0x3bb: return new LavaRock(device, geometryData, emitters);
}
return new GeometryRenderer(device, geometryData);
}
const movementScratch = vec3.create();
class Bobber implements MovementController {
protected amplitudes = nArray(3, () => 0);
private speed = 80 + 20 * Math.random();
private basePos = vec3.create();
private baseYaw = 0;
private baseRoll = 0;
private baseScale = 1;
constructor(obj: GeometryRenderer) {
mat4.getTranslation(this.basePos, obj.modelMatrix);
mat4.getScaling(movementScratch, obj.modelMatrix);
this.baseScale = movementScratch[0]; // assume uniform
// BK uses a slightly different convention than the existing logic
this.baseRoll = Math.atan2(obj.modelMatrix[1], obj.modelMatrix[5]);
this.baseYaw = -Math.atan2(obj.modelMatrix[2], obj.modelMatrix[0]);
// nothing sets pitch, so ignore
}
public movement(dst: mat4, time: number) {
const phase = time * this.speed * MathConstants.DEG_TO_RAD;
mat4.fromYRotation(dst, this.baseYaw + Math.sin(phase) * this.amplitudes[0]);
mat4.rotateX(dst, dst, Math.cos(phase) * this.amplitudes[1]);
mat4.rotateZ(dst, dst, this.baseRoll);
scaleMatrix(dst, dst, this.baseScale);
dst[12] = this.basePos[0];
dst[13] = this.basePos[1] + Math.sin(phase) * this.amplitudes[2];
dst[14] = this.basePos[2];
}
}
// these objects sink and tilt when Banjo lands on them
// inside Clanker, there's extra logic to move with the water level,
// but the sinking behavior doesn't trigger (maybe a bug)
export class SinkingBobber extends Bobber {
constructor(obj: GeometryRenderer) {
super(obj);
this.amplitudes[0] = 2 * MathConstants.DEG_TO_RAD;
this.amplitudes[1] = 4.5 * MathConstants.DEG_TO_RAD;
this.amplitudes[2] = 10;
}
}
export class WaterBobber extends Bobber {
constructor(obj: GeometryRenderer) {
super(obj);
this.amplitudes[0] = 3 * MathConstants.DEG_TO_RAD;
this.amplitudes[1] = 7.5 * MathConstants.DEG_TO_RAD;
this.amplitudes[2] = 20;
}
}
export class ModelPin implements MovementController {
private modelVector: vec3;
constructor(points: vec3[], index: number) {
this.modelVector = assertExists(points[index]);
}
public movement(dst: mat4, _: number): void {
mat4.fromTranslation(dst, this.modelVector);
}
}
export class Projectile implements MovementController {
public start = vec3.create();
public startVel = vec3.create();
public angularVel = vec2.create();
public startTime = -1;
public scale = 1;
public reachedPeak = false;
constructor(private g = 1000) { }
public setFromVel(start: vec3, startVel: vec3): void {
this.startTime = -1;
vec3.copy(this.start, start);
vec3.copy(this.startVel, startVel);
}
public setFromTarget(start: vec3, target: vec3, flightTime: number): void {
this.startTime = -1;
vec3.copy(this.start, start);
vec3.sub(this.startVel, target, start);
vec3.scale(this.startVel, this.startVel, 1 / flightTime);
this.startVel[1] += this.g * flightTime / 2;
}
public movement(dst: mat4, time: number): void {
if (this.startTime < 0)
this.startTime = time;
const currTime = time - this.startTime;
vec3.copy(movementScratch, this.start);
vec3.scaleAndAdd(movementScratch, movementScratch, this.startVel, currTime);
movementScratch[1] -= this.g * currTime * currTime / 2;
mat4.fromTranslation(dst, movementScratch);
mat4.rotateY(dst, dst, this.angularVel[0] * currTime);
mat4.rotateX(dst, dst, this.angularVel[1] * currTime);
scaleMatrix(dst, dst, this.scale);
this.reachedPeak = currTime * this.g >= this.startVel[1];
}
}
``` | /content/code_sandbox/src/BanjoKazooie/actors.ts | xml | 2016-10-06T21:43:45 | 2024-08-16T17:03:52 | noclip.website | magcius/noclip.website | 3,206 | 10,912 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="path_to_url">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="DebugStatic|Win32">
<Configuration>DebugStatic</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseStatic|Win32">
<Configuration>ReleaseStatic</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="DebugDLL|Win32">
<Configuration>DebugDLL</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDLL|Win32">
<Configuration>ReleaseDLL</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{5BCC7EAB-4B17-3B4C-8FDF-E350C2D534BA}</ProjectGuid>
<RootNamespace>tutorial_2</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugStatic|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseStatic|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugDLL|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDLL|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='DebugStatic|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseStatic|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='DebugDLL|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDLL|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugStatic|Win32'">
<OutDir>..\..\bin\</OutDir>
<IntDir>..\..\intermediate\debugstatic\vs2013\tutorial_2\x32\</IntDir>
<TargetName>tutorial_2_debugstatic_win32_vs2013</TargetName>
<TargetExt>.exe</TargetExt>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseStatic|Win32'">
<OutDir>..\..\bin\</OutDir>
<IntDir>..\..\intermediate\releasestatic\vs2013\tutorial_2\x32\</IntDir>
<TargetName>tutorial_2_releasestatic_win32_vs2013</TargetName>
<TargetExt>.exe</TargetExt>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DebugDLL|Win32'">
<OutDir>..\..\bin\</OutDir>
<IntDir>..\..\intermediate\debugdll\vs2013\tutorial_2\x32\</IntDir>
<TargetName>tutorial_2_debugdll_win32_vs2013</TargetName>
<TargetExt>.exe</TargetExt>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDLL|Win32'">
<OutDir>..\..\bin\</OutDir>
<IntDir>..\..\intermediate\releasedll\vs2013\tutorial_2\x32\</IntDir>
<TargetName>tutorial_2_releasedll_win32_vs2013</TargetName>
<TargetExt>.exe</TargetExt>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='DebugStatic|Win32'">
<ClCompile>
<AdditionalOptions>/MP /bigobj %(AdditionalOptions)</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<SmallerTypeCheck>true</SmallerTypeCheck>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader></PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<ExceptionHandling>false</ExceptionHandling>
<FloatingPointModel>Fast</FloatingPointModel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<ProgramDataBaseFileName>$(OutDir)tutorial_2_debugstatic_win32_vs2013.pdb</ProgramDataBaseFileName>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<OutputFile>$(OutDir)tutorial_2_debugstatic_win32_vs2013.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseStatic|Win32'">
<ClCompile>
<AdditionalOptions>/MP /bigobj /Ox /Oi /Ob1 /Ot %(AdditionalOptions)</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_HAS_EXCEPTIONS=0;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader></PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<ExceptionHandling>false</ExceptionHandling>
<FloatingPointModel>Fast</FloatingPointModel>
<DebugInformationFormat></DebugInformationFormat>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_HAS_EXCEPTIONS=0;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<OutputFile>$(OutDir)tutorial_2_releasestatic_win32_vs2013.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='DebugDLL|Win32'">
<ClCompile>
<AdditionalOptions>/MP /bigobj %(AdditionalOptions)</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<SmallerTypeCheck>true</SmallerTypeCheck>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader></PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<ExceptionHandling>false</ExceptionHandling>
<FloatingPointModel>Fast</FloatingPointModel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<ProgramDataBaseFileName>$(OutDir)tutorial_2_debugdll_win32_vs2013.pdb</ProgramDataBaseFileName>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>WIN32;_DEBUG;DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<OutputFile>$(OutDir)tutorial_2_debugdll_win32_vs2013.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='ReleaseDLL|Win32'">
<ClCompile>
<AdditionalOptions>/MP /bigobj /Ox /Oi /Ob1 /Ot %(AdditionalOptions)</AdditionalOptions>
<Optimization>Full</Optimization>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_HAS_EXCEPTIONS=0;_CRT_SECURE_NO_WARNINGS;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader></PrecompiledHeader>
<WarningLevel>Level4</WarningLevel>
<ExceptionHandling>false</ExceptionHandling>
<FloatingPointModel>Fast</FloatingPointModel>
<DebugInformationFormat></DebugInformationFormat>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_HAS_EXCEPTIONS=0;_CRT_SECURE_NO_WARNINGS;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\inc;..\..\inc;..\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>false</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<OutputFile>$(OutDir)tutorial_2_releasedll_win32_vs2013.exe</OutputFile>
<AdditionalLibraryDirectories>..\..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\behaviors\behaviac_generated_behaviors.h" />
<ClInclude Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\types\behaviac_types.h" />
<ClInclude Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\types\internal\behaviac_agent_headers.h" />
<ClInclude Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\types\internal\behaviac_agent_member_visitor.h" />
<ClInclude Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\types\internal\behaviac_agent_meta.h" />
<ClInclude Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\types\internal\behaviac_headers.h" />
<ClInclude Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\types\internal\FirstAgent.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\tutorials\tutorial_2\cpp\tutorial_2.cpp">
</ClCompile>
<ClCompile Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\behaviors\behaviac_generated_behaviors.cpp">
</ClCompile>
<ClCompile Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\types\internal\behaviac_agent_meta.cpp">
</ClCompile>
<ClCompile Include="..\..\tutorials\tutorial_2\cpp\behaviac_generated\types\internal\FirstAgent.cpp">
</ClCompile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="behaviac.vcxproj">
<Project>{332CEEDC-7568-D84C-B9C6-B710915836ED}</Project>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
``` | /content/code_sandbox/projects/vs2013/tutorial_2.vcxproj | xml | 2016-11-21T05:08:08 | 2024-08-16T07:18:30 | behaviac | Tencent/behaviac | 2,831 | 3,501 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="path_to_url">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{EE32DAA4-6B5C-47E6-9409-F87CCA0E5797}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<WindowsTargetPlatformVersion>10.0.17763.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformVersion Condition="'$(VisualStudioVersion)'>='16.0'">10.0</WindowsTargetPlatformVersion>
<ProjectName>03-history_window</ProjectName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Label="Configuration">
<CharacterSet>Unicode</CharacterSet>
<PlatformToolset>v141</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)'=='16.0'">v142</PlatformToolset>
<PlatformToolset Condition="'$(VisualStudioVersion)'=='17.0'">v143</PlatformToolset>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)'=='Debug'">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Label="Configuration" Condition="'$(Configuration)'=='Release'">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup>
<OutDir>..\..\bin\$(Platform)\$(Configuration) Examples\</OutDir>
<IntDir>..\..\intermediate\$(ProjectName)\$(Platform)\$(Configuration)\</IntDir>
<TargetName>history_window</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Platform)'=='Win32'">
<TargetExt>.addon32</TargetExt>
</PropertyGroup>
<PropertyGroup Condition="'$(Platform)'=='x64'">
<TargetExt>.addon64</TargetExt>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level4</WarningLevel>
<SDLCheck>true</SDLCheck>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32_LEAN_AND_MEAN;NOMINMAX;ImTextureID=ImU64;_CRT_SECURE_NO_WARNINGS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\..\include;..\..\deps\imgui;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level4</WarningLevel>
<SDLCheck>true</SDLCheck>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32_LEAN_AND_MEAN;NOMINMAX;ImTextureID=ImU64;_CRT_SECURE_NO_WARNINGS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\..\include;..\..\deps\imgui;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PreprocessorDefinitions>WIN32_LEAN_AND_MEAN;NOMINMAX;ImTextureID=ImU64;_CRT_SECURE_NO_WARNINGS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\..\include;..\..\deps\imgui;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>false</GenerateDebugInformation>
<LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PreprocessorDefinitions>WIN32_LEAN_AND_MEAN;NOMINMAX;ImTextureID=ImU64;_CRT_SECURE_NO_WARNINGS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>..\..\include;..\..\deps\imgui;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>false</GenerateDebugInformation>
<LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="history_window_addon.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
``` | /content/code_sandbox/examples/03-history_window/history_window.vcxproj | xml | 2016-06-15T23:02:16 | 2024-08-16T16:36:42 | reshade | crosire/reshade | 4,006 | 1,662 |
```xml
<vector xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:width="108dp"
android:height="108dp"
android:viewportWidth="193.93939"
android:viewportHeight="193.93939">
<group android:translateX="32.969696"
android:translateY="32.969696">
<path
android:pathData="M58.111,61.689c-5.291,0 -9.597,3.203 -9.597,7.141s4.305,7.141 9.597,7.141s9.597,-3.203 9.597,-7.141S63.403,61.689 58.111,61.689z"
android:fillColor="#FFFFFF"/>
<!--<path-->
<!--android:pathData="M102.279,8.377H25.721c-9.594,0 -17.443,7.85 -17.443,17.443v76.568c0,9.594 7.85,17.443 17.443,17.443h76.558c9.594,0 17.443,-7.85 17.443,-17.443V25.821C119.722,16.227 111.873,8.377 102.279,8.377z"-->
<!--android:fillColor="#5290FF"/>-->
<path
android:pathData="M55.469,17.643c0.278,-0.038 0.558,-0.072 0.835,-0.101c1.427,-0.144 2.724,0.893 2.874,2.33c0.151,1.437 -0.892,2.724 -2.33,2.874c-0.221,0.023 -0.442,0.051 -0.665,0.081c-0.121,0.017 -0.241,0.024 -0.36,0.024c-1.286,0 -2.408,-0.949 -2.589,-2.26C53.037,19.161 54.037,17.841 55.469,17.643z"
android:fillColor="#FFFFFF"/>
<path
android:pathData="M64,111.084c-26.033,0 -47.211,-21.179 -47.211,-47.211c0,-18.632 11.002,-35.57 28.028,-43.15c0.557,-0.249 1.121,-0.486 1.689,-0.713c1.34,-0.536 2.864,0.118 3.4,1.46c0.536,1.342 -0.118,2.864 -1.46,3.4c-0.505,0.201 -1.006,0.413 -1.502,0.633c-15.139,6.74 -24.922,21.801 -24.922,38.369c0,23.147 18.831,41.978 41.978,41.978s41.978,-18.831 41.978,-41.978c0,-6.335 -1.375,-12.421 -4.086,-18.09c-0.611,-1.279 -1.301,-2.549 -2.05,-3.776c-6.038,-9.876 -15.735,-16.731 -26.901,-19.148v10.643c0.432,0.075 0.931,0.169 1.464,0.269c0.714,0.17 1.49,0.363 2.33,0.604c0.826,0.267 1.73,0.526 2.644,0.884c0.928,0.326 1.877,0.726 2.853,1.142c0.972,0.426 1.962,0.887 2.95,1.384c0.986,0.501 1.98,1.018 2.947,1.58c0.982,0.532 1.919,1.145 2.857,1.709c0.911,0.613 1.825,1.178 2.664,1.798c0.849,0.603 1.661,1.193 2.403,1.791c0.758,0.574 1.442,1.159 2.069,1.7c0.638,0.525 1.184,1.055 1.675,1.512c0.496,0.451 0.912,0.861 1.24,1.214c0.666,0.691 1.047,1.085 1.047,1.085s-0.435,-0.333 -1.196,-0.916c-0.373,-0.297 -0.843,-0.638 -1.396,-1.008c-0.549,-0.376 -1.156,-0.811 -1.858,-1.231c-0.691,-0.434 -1.437,-0.902 -2.258,-1.348c-0.803,-0.471 -1.676,-0.924 -2.581,-1.382c-0.895,-0.474 -1.862,-0.887 -2.818,-1.342c-0.984,-0.405 -1.96,-0.855 -2.971,-1.22c-0.999,-0.396 -2.013,-0.743 -3.012,-1.075c-1,-0.327 -1.99,-0.618 -2.95,-0.878c-0.963,-0.249 -1.89,-0.486 -2.775,-0.653c-0.881,-0.203 -1.717,-0.307 -2.482,-0.435c-0.761,-0.099 -1.47,-0.164 -2.067,-0.216c-0.278,-0.009 -0.538,-0.017 -0.781,-0.024v28.929c0,0.184 -0.02,0.363 -0.056,0.536c0.027,0.304 0.056,0.608 0.056,0.918c0,6.823 -6.653,12.374 -14.83,12.374s-14.83,-5.551 -14.83,-12.374s6.653,-12.374 14.83,-12.374c3.66,0 7.007,1.117 9.597,2.958V20.051c0,-0.426 0.112,-0.823 0.293,-1.179c0.409,-1.156 1.59,-1.901 2.841,-1.716c13.906,2.019 26.104,10.083 33.465,22.124c0.843,1.379 1.618,2.808 2.307,4.247c3.051,6.378 4.597,13.224 4.597,20.347C111.211,89.905 90.033,111.084 64,111.084z"
android:fillColor="#FFFFFF"
tools:ignore="VectorPath" />
</group>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_launcher_foreground.xml | xml | 2016-04-09T15:47:45 | 2024-08-14T04:30:04 | MusicLake | caiyonglong/MusicLake | 2,654 | 1,735 |
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="@PKG_ADDON_ID@"
name="@ADDON_NAME@"
version="@ADDON_VERSION@"
provider-name="@PROVIDER_NAME@">
<requires>
<import addon="xbmc.python" version="3.0.0"/>
@REQUIRES@
</requires>
<extension point="xbmc.service" library="default.py">
<provides>@PKG_ADDON_PROVIDES@</provides>
</extension>
<extension point="xbmc.python.script" library="download.py">
<provides>@PKG_ADDON_PROVIDES@</provides>
</extension>
<extension point="xbmc.addon.metadata">
<summary>@PKG_SHORTDESC@</summary>
<description>
@PKG_LONGDESC@
</description>
<disclaimer>
@PKG_DISCLAIMER@
</disclaimer>
<platform>all</platform>
<news>
@PKG_ADDON_NEWS@
</news>
<assets>
<icon>resources/icon.png</icon>
<fanart>resources/fanart.png</fanart>
@PKG_ADDON_SCREENSHOT@
</assets>
</extension>
</addon>
``` | /content/code_sandbox/packages/addons/service/tvheadend43/addon.xml | xml | 2016-03-13T01:46:18 | 2024-08-16T11:58:29 | LibreELEC.tv | LibreELEC/LibreELEC.tv | 2,216 | 268 |
```xml
import { LogicParams } from '../types';
const checkLogic = (logics: LogicParams[]) => {
const values: { [key: string]: boolean } = {};
for (const logic of logics) {
const {
fieldId,
operator,
logicValue,
fieldValue,
validation,
type
} = logic;
const key = `${fieldId}_${logicValue}`;
values[key] = false;
// if fieldValue is set
if (operator === 'hasAnyValue') {
if (fieldValue) {
values[key] = true;
} else {
values[key] = false;
}
}
// if fieldValue is not set
if (operator === 'isUnknown') {
if (!fieldValue) {
values[key] = true;
} else {
values[key] = false;
}
}
// if fieldValue equals logic value
if (operator === 'is') {
if ((logicValue || '').toString() === (fieldValue || '').toString()) {
values[key] = true;
} else {
values[key] = false;
}
}
// if fieldValue not equal to logic value
if (operator === 'isNot') {
if (logicValue !== fieldValue) {
values[key] = true;
} else {
values[key] = false;
}
}
if (validation === 'number') {
// if number value: is greater than
if (operator === 'greaterThan' && fieldValue) {
if (Number(fieldValue) > Number(logicValue)) {
values[key] = true;
} else {
values[key] = false;
}
}
// if number value: is less than
if (operator === 'lessThan' && fieldValue) {
if (Number(fieldValue) < Number(logicValue)) {
values[key] = true;
} else {
values[key] = false;
}
}
}
if (typeof logicValue === 'string') {
// if string value contains logicValue
if (operator === 'contains') {
if (String(fieldValue).includes(logicValue)) {
values[key] = true;
} else {
values[key] = false;
}
}
// if string value does not contain logicValue
if (operator === 'doesNotContain') {
if (!String(fieldValue).includes(logicValue)) {
values[key] = true;
} else {
values[key] = false;
}
}
// if string value startsWith logicValue
if (operator === 'startsWith') {
if (String(fieldValue).startsWith(logicValue)) {
values[key] = true;
} else {
values[key] = false;
}
}
// if string value endsWith logicValue
if (operator === 'endsWith') {
if (!String(fieldValue).endsWith(logicValue)) {
values[key] = true;
} else {
values[key] = false;
}
}
}
if (validation && validation.includes('date')) {
const dateValueToCheck = new Date(String(fieldValue));
const logicDateValue = new Date(String(logicValue));
// date is greather than
if (operator === 'dateGreaterThan') {
if (dateValueToCheck > logicDateValue) {
values[key] = true;
} else {
values[key] = false;
}
}
// date is less than
if (operator === 'dateLessThan') {
if (logicDateValue > dateValueToCheck) {
values[key] = true;
} else {
values[key] = false;
}
}
}
if (type === 'check') {
if (
fieldValue &&
typeof fieldValue === 'string' &&
typeof logicValue === 'string'
) {
if (operator === 'isNot') {
if (!fieldValue.includes(logicValue)) {
values[key] = true;
} else {
values[key] = false;
}
}
if (operator === 'is') {
if (fieldValue.includes(logicValue)) {
values[key] = true;
} else {
values[key] = false;
}
}
}
}
}
const result: any = [];
for (const key of Object.keys(values)) {
result.push(values[key]);
}
if (result.filter(val => !val).length === 0) {
return true;
}
return false;
};
export { checkLogic };
``` | /content/code_sandbox/client-portal/modules/utils/forms.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 983 |
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "path_to_url">
<mapper namespace="org.flowable.common.engine.impl.persistence.change.ChangeLog">
<!-- CHANGELOG SELECT -->
<select id="selectFlowableChangeLogVersions" parameterType="string" resultType="string">
select ID from ${prefix}${changeLogTablePrefix}_DATABASECHANGELOG order by ORDEREXECUTED
</select>
</mapper>
``` | /content/code_sandbox/modules/flowable-engine-common/src/main/resources/org/flowable/common/db/mapping/ChangeLog.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 115 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>Author</key>
<string>Vandroiy</string>
<key>CodecID</key>
<integer>2304</integer>
<key>CodecName</key>
<string>ALC1150</string>
<key>Files</key>
<dict>
<key>Layouts</key>
<array>
<dict>
<key>Comment</key>
<string>Toleda - ALC1150, 5/6 audio ports, native: 2 inputs, 3/4 outputs+front panel+SPDIF/Optical</string>
<key>Id</key>
<integer>1</integer>
<key>Path</key>
<string>layout1.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Toleda - ALC1150, 3 audio ports, repurposed to 5.1: 0 inputs, 3 outputs+front panel+SPDIF/Optical</string>
<key>Id</key>
<integer>2</integer>
<key>Path</key>
<string>layout2.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Toleda - ALC1150, 3 audio ports, native: 2 inputs, 1 output+front panel+SPDIF/Optical</string>
<key>Id</key>
<integer>3</integer>
<key>Path</key>
<string>layout3.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone 3 ports (Pink, Green, Blue)</string>
<key>Id</key>
<integer>5</integer>
<key>Path</key>
<string>layout5.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone 5/6 ports (Gray, Black, Orange, Pink, Green, Blue)</string>
<key>Id</key>
<integer>7</integer>
<key>Path</key>
<string>layout7.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone 5/6 ports (Gray, Black, Orange, Pink, Green, Blue) and mic boost</string>
<key>Id</key>
<integer>11</integer>
<key>Path</key>
<string>layout7.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>ALC1150 for Gigabyte GA-Z97X-UD5H by DalianSky</string>
<key>Id</key>
<integer>99</integer>
<key>Path</key>
<string>layout99.xml.zlib</string>
</dict>
</array>
<key>Platforms</key>
<array>
<dict>
<key>Comment</key>
<string>Toleda resources</string>
<key>Id</key>
<integer>1</integer>
<key>Path</key>
<string>PlatformsT.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Toleda resources</string>
<key>Id</key>
<integer>2</integer>
<key>Path</key>
<string>PlatformsT.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Toleda resources</string>
<key>Id</key>
<integer>3</integer>
<key>Path</key>
<string>PlatformsT.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone resources</string>
<key>Id</key>
<integer>5</integer>
<key>Path</key>
<string>PlatformsM.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone resources</string>
<key>Id</key>
<integer>7</integer>
<key>Path</key>
<string>PlatformsM.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>Mirone 5/6 ports (Gray, Black, Orange, Pink, Green, Blue) and mic boost</string>
<key>Id</key>
<integer>11</integer>
<key>Path</key>
<string>Platforms11.xml.zlib</string>
</dict>
<dict>
<key>Comment</key>
<string>ALC1150 for Gigabyte GA-Z97X-UD5H by DalianSky</string>
<key>Id</key>
<integer>99</integer>
<key>Path</key>
<string>Platforms99.xml.zlib</string>
</dict>
</array>
</dict>
<key>Patches</key>
<array>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>xgYASIu/aAE=</data>
<key>MinKernel</key>
<integer>18</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>xgYBSIu/aAE=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcYGAEmLvCQ=</data>
<key>MaxKernel</key>
<integer>13</integer>
<key>MinKernel</key>
<integer>12</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcYGAUmLvCQ=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcYGAEiLu2g=</data>
<key>MinKernel</key>
<integer>14</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcYGAUiLu2g=</data>
</dict>
<dict>
<key>Count</key>
<integer>1</integer>
<key>Find</key>
<data>QcaGQwEAAAA=</data>
<key>MinKernel</key>
<integer>12</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>QcaGQwEAAAE=</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>ixnUEQ==</data>
<key>MinKernel</key>
<integer>12</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAnsEA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>gxnUEQ==</data>
<key>MaxKernel</key>
<integer>15</integer>
<key>MinKernel</key>
<integer>15</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
<dict>
<key>Count</key>
<integer>2</integer>
<key>Find</key>
<data>ihnUEQ==</data>
<key>MinKernel</key>
<integer>16</integer>
<key>Name</key>
<string>AppleHDA</string>
<key>Replace</key>
<data>AAAAAA==</data>
</dict>
</array>
<key>Revisions</key>
<array>
<integer>1048577</integer>
</array>
<key>Vendor</key>
<string>Realtek</string>
</dict>
</plist>
``` | /content/code_sandbox/Resources/ALC1150/Info.plist | xml | 2016-03-07T20:45:58 | 2024-08-14T08:57:03 | AppleALC | acidanthera/AppleALC | 3,420 | 2,176 |
```xml
// See LICENSE in the project root for license information.
import { ChangeFile } from '../ChangeFile';
import { RushConfiguration } from '../RushConfiguration';
import { ChangeType } from '../ChangeManagement';
describe(ChangeFile.name, () => {
it('can add a change', () => {
const rushFilename: string = `${__dirname}/repo/rush-npm.json`;
const rushConfiguration: RushConfiguration = RushConfiguration.loadFromConfigurationFile(rushFilename);
const changeFile: ChangeFile = new ChangeFile(
{
packageName: 'a',
changes: [],
email: 'fake@microsoft.com'
},
rushConfiguration
);
changeFile.addChange({
packageName: 'a',
changeType: ChangeType.minor,
comment: 'for minor'
});
changeFile.addChange({
packageName: 'a',
changeType: ChangeType.patch,
comment: 'for patch'
});
expect(changeFile.getChanges('a')).toHaveLength(2);
expect(changeFile.getChanges('a')[0].comment).toEqual('for minor');
expect(changeFile.getChanges('a')[1].comment).toEqual('for patch');
});
});
``` | /content/code_sandbox/libraries/rush-lib/src/api/test/ChangeFile.test.ts | xml | 2016-09-30T00:28:20 | 2024-08-16T18:54:35 | rushstack | microsoft/rushstack | 5,790 | 251 |
```xml
import { Router } from 'react-router-dom';
import { createBrowserHistory as createHistory } from 'history';
import * as bootstrap from '@proton/account/bootstrap';
import { ApiProvider, ErrorBoundary, ProtonApp, StandardErrorPage } from '@proton/components';
import AuthenticationProvider from '@proton/components/containers/authentication/Provider';
import useInstance from '@proton/hooks/useInstance';
import { ProtonStoreProvider } from '@proton/redux-shared-store';
import createApi from '@proton/shared/lib/api/createApi';
import { replaceUrl } from '@proton/shared/lib/helpers/browser';
import { initSafariFontFixClassnames } from '@proton/shared/lib/helpers/initSafariFontFixClassnames';
import initLogicalProperties from '@proton/shared/lib/logical/logical';
import PrivateApp from './PrivateApp';
import PublicApp from './PublicApp';
import * as config from './config';
import locales from './locales';
import { extendStore, setupStore } from './store/store';
import { extraThunkArguments } from './store/thunk';
const bootstrapApp = () => {
const history = createHistory();
const api = createApi({ config });
const authentication = bootstrap.createAuthentication();
bootstrap.init({ config, authentication, locales });
initLogicalProperties();
initSafariFontFixClassnames();
extendStore({ authentication, api, history, config });
return setupStore({ mode: authentication.UID ? 'default' : 'public' });
};
const App = () => {
const store = useInstance(() => {
return bootstrapApp();
});
return (
<ProtonApp config={config}>
<ErrorBoundary component={<StandardErrorPage />}>
<AuthenticationProvider store={extraThunkArguments.authentication}>
<ApiProvider api={extraThunkArguments.api}>
<Router history={extraThunkArguments.history}>
<ProtonStoreProvider store={store}>
{extraThunkArguments.authentication.UID ? (
<PrivateApp store={store} locales={locales} />
) : (
<PublicApp
onLogin={(args) => {
const url = extraThunkArguments.authentication.login(args);
replaceUrl(url);
}}
locales={locales}
/>
)}
</ProtonStoreProvider>
</Router>
</ApiProvider>
</AuthenticationProvider>
</ErrorBoundary>
</ProtonApp>
);
};
export default App;
``` | /content/code_sandbox/applications/vpn-settings/src/app/App.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 500 |
```xml
import { Appearance } from 'react-native';
import { AppDispatch, AppThunk } from './Store.types';
import * as DevMenu from '../menu/DevMenuModule';
import LocalStorage from '../storage/LocalStorage';
type ColorSchemeName = Appearance.AppearancePreferences['colorScheme'];
export default {
loadSettings(): AppThunk {
return async (dispatch: AppDispatch) => {
const [localStorageSettings, devMenuSettings] = await Promise.all([
LocalStorage.getSettingsAsync(),
DevMenu.getSettingsAsync(),
]);
return dispatch({
type: 'loadSettings',
payload: {
...localStorageSettings,
preferredAppearance: localStorageSettings.preferredAppearance ?? undefined,
devMenuSettings,
},
});
};
},
setPreferredAppearance(preferredAppearance: ColorSchemeName): AppThunk {
return async (dispatch: AppDispatch) => {
try {
await LocalStorage.updateSettingsAsync({
preferredAppearance,
});
dispatch({
type: 'setPreferredAppearance',
payload: { preferredAppearance },
});
} catch {
alert('Oops, something went wrong and we were unable to change the preferred appearance');
}
};
},
setDevMenuSetting(key: keyof DevMenu.DevMenuSettings, value?: boolean): AppThunk {
return async (dispatch: AppDispatch) => {
try {
await DevMenu.setSettingAsync(key, value);
dispatch({
type: 'setDevMenuSettings',
payload: { [key]: value },
});
} catch {
alert('Oops, something went wrong and we were unable to change dev menu settings!');
}
};
},
};
``` | /content/code_sandbox/apps/expo-go/src/redux/SettingsActions.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 343 |
```xml
import Link from '@docusaurus/Link';
import React from 'react';
import { useColorMode } from '@docusaurus/theme-common';
import { SiTwitter } from 'react-icons/si';
export default function () {
const { colorMode } = useColorMode();
const darkFooter = colorMode === 'dark' ? 'footer-dark' : '';
return (
<footer
style={{ fontSize: 'small' }}
className={'footer text--sm ' + darkFooter}
>
<div className="container container-fluid">
<div className="row footer__links">
<div className="col footer__col">
<div className="footer__title">Docs</div>
<ul className="footer__items clean-list">
<li className="footer__item">
<a className="footer__link-item" href="/docs">
Getting Started
</a>
</li>
<li className="footer__item">
<a className="footer__link-item" href="/blog">
Blogs
</a>
</li>
<li className="footer__item">
<a className="footer__link-item" href="/docs/customizing">
Customizing
</a>
</li>
<li className="footer__item">
<a className="footer__link-item" href="/migration">
Migration Guides
</a>
</li>
</ul>
</div>
<div className="col footer__col">
<div className="footer__title">Contribution</div>
<ul className="footer__items clean-list">
<li className="footer__item">
<a
className="footer__link-item"
href="/docs/contributing#setup"
>
Setup Guide
</a>
</li>
<li className="footer__item">
<a className="footer__link-item" href="/docs/contributing">
Contribution Guide
</a>
</li>
<a
href="path_to_url"
target="_blank"
rel="noopener noreferrer"
className="footer__link-item"
>
Submit a bug or feature
</a>
</ul>
</div>
<div className="col footer__col">
<div className="footer__title">Community</div>
<ul className="footer__items clean-list">
<li className="footer__item">
<a
href="path_to_url"
target="_blank"
rel="noopener noreferrer"
className="footer__link-item"
>
Discord server
</a>
</li>
<li className="footer__item">
<a
href="path_to_url"
target="_blank"
rel="noopener noreferrer"
className="footer__link-item"
>
Twitter
</a>
</li>
<li className="footer__item">
<a
href="path_to_url"
target="_blank"
rel="noopener noreferrer"
className="footer__link-item"
>
GitHub Discussions
</a>
</li>
</ul>
</div>
<div className="col footer__col">
<div className="footer__title">More</div>
<ul className="footer__items clean-list">
<li className="footer__item">
<a
href="path_to_url"
target="_blank"
rel="noopener noreferrer"
className="footer__link-item"
>
StackOverflow
</a>
</li>
<li className="footer__item">
<a
href="path_to_url"
target="_blank"
rel="noopener noreferrer"
className="footer__link-item"
>
VS Code Extension
</a>
</li>
</ul>
</div>
</div>
<div className="footer__bottom text--center">
<div className="margin-bottom--sm">
<Link
to="path_to_url"
className="button button--primary button--md margin-horiz--sm margin-vert--sm "
style={{ backgroundColor: '#1DA1F2', color: 'white' }}
>
Follow us on Twitter <SiTwitter />
</Link>
<Link
to="path_to_url"
className="button button--secondary button--outline button--md margin-horiz--sm margin-vert--sm "
>
Sponsor us
<svg
style={{ margin: '0 5px -3px 8px ' }}
width={16}
fill="#EA4AAA"
role="img"
viewBox="0 0 24 24"
xmlns="path_to_url"
>
<title>Sponsor us</title>
<path d="M17.625 1.499c-2.32 0-4.354 1.203-5.625 3.03-1.271-1.827-3.305-3.03-5.625-3.03C3.129 1.499 0 4.253 0 8.249c0 4.275 3.068 7.847 5.828 10.227a33.14 33.14 0 0 0 5.616 3.876l.028.017.008.003-.001.003c.163.085.342.126.521.125.179.001.358-.041.521-.125l-.001-.003.008-.003.028-.017a33.14 33.14 0 0 0 5.616-3.876C20.932 16.096 24 12.524 24 8.249c0-3.996-3.129-6.75-6.375-6.75zm-.919 15.275a30.766 30.766 0 0 1-4.703 3.316l-.004-.002-.004.002a30.955 30.955 0 0 1-4.703-3.316c-2.677-2.307-5.047-5.298-5.047-8.523 0-2.754 2.121-4.5 4.125-4.5 2.06 0 3.914 1.479 4.544 3.684.143.495.596.797 1.086.796.49.001.943-.302 1.085-.796.63-2.205 2.484-3.684 4.544-3.684 2.004 0 4.125 1.746 4.125 4.5 0 3.225-2.37 6.216-5.048 8.523z" />
</svg>
</Link>
</div>
{/* <div className="margin-bottom--sm">
<img
src="/img/logo.png"
alt=""
className="themedImage_node_modules-@your_sha256_hashe themedImage--dark_node_modules-@your_sha256_hashe footer__logo"
/>
</div> */}
</div>
</div>
<div className="text--center"></div>
</footer>
);
}
``` | /content/code_sandbox/website/src/theme/Footer.tsx | xml | 2016-09-08T14:21:41 | 2024-08-16T10:11:29 | react-native-elements | react-native-elements/react-native-elements | 24,875 | 1,597 |
```xml
<Documentation>
<Docs DocId="T:CoreImage.CIConvolution9Horizontal">
<summary>A filter that performs a horizontal convolution of 9 elements.</summary>
<remarks>
<para>The following example shows this filter in use</para>
<example>
<code lang="csharp lang-csharp"><![CDATA[
// Create the CIImage from a file
CIImage heron = CIImage.FromCGImage (UIImage.FromFile ("heron.jpg").CGImage);
// Create a CIConvolution9Horizontal filter with the input image
var convolution_9_horizontal = new CIConvolution9Horizontal () {
Image = heron,
Weights = new CIVector (new float [] {1, -1, 1, 0, 1, 0, -1, 1, -1}),
};
// Get the altered image from the filter
var output = convolution_9_horizontal.OutputImage;
// To render the results, we need to create a context, and then
// use one of the context rendering APIs, in this case, we render the
// result into a CoreGraphics image, which is merely a useful representation
//
var context = CIContext.FromOptions (null);
var cgimage = context.CreateCGImage (output, output.Extent);
// The above cgimage can be added to a screen view, for example, this
// would add it to a UIImageView on the screen:
myImageView.Image = UIImage.FromImage (cgimage);
]]></code>
</example>
<para>
With the following image input:
</para>
<para>
<img href="~/CoreImage/_images/heron.jpg" alt="Photograph of a heron." />
</para>
<para>
Produces the following output:
</para>
<para>
<img href="~/CoreImage/_images/convolution_9_horizontal.png" alt="Result of applying the filter." />
</para>
<para>
"canon" 2012 cuatrok77 hernandez, used under a Creative Commons Attribution-ShareAlike license: path_to_url
</para>
</remarks>
</Docs>
</Documentation>
``` | /content/code_sandbox/docs/api/CoreImage/CIConvolution9Horizontal.xml | xml | 2016-04-20T18:24:26 | 2024-08-16T13:29:19 | xamarin-macios | xamarin/xamarin-macios | 2,436 | 467 |
```xml
import { z } from 'zod';
import { TRPCError } from '@trpc/server';
import { profileAnalysisDtoMapper } from '~/mappers/offers-mappers';
import { analysisInclusion } from '~/utils/offers/analysis/analysisInclusion';
import { createRouter } from '../context';
import { generateAnalysis } from '../../../utils/offers/analysis/analysisGeneration';
export const offersAnalysisRouter = createRouter()
.query('get', {
input: z.object({
profileId: z.string(),
}),
async resolve({ ctx, input }) {
const analysis = await ctx.prisma.offersAnalysis.findFirst({
include: analysisInclusion,
where: {
profileId: input.profileId,
},
});
if (!analysis) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'No analysis found on this profile',
});
}
return profileAnalysisDtoMapper(analysis);
},
})
.mutation('generate', {
input: z.object({
profileId: z.string(),
}),
async resolve({ ctx, input }) {
return generateAnalysis({ ctx, input });
},
});
``` | /content/code_sandbox/apps/portal/src/server/router/offers/offers-analysis-router.ts | xml | 2016-07-05T05:00:48 | 2024-08-16T19:01:19 | tech-interview-handbook | yangshun/tech-interview-handbook | 115,302 | 251 |
```xml
import { pxToRem } from '../../../../utils';
import { FlexProps } from '../../../../components/Flex/Flex';
type GapValues = Record<FlexProps['gap'], string>;
type PaddingValues = Record<FlexProps['padding'], string>;
export type FlexVariables = GapValues & PaddingValues;
export const flexVariables = (): FlexVariables => ({
// GAP VALUES
'gap.smaller': pxToRem(8),
'gap.small': pxToRem(10),
'gap.medium': pxToRem(15),
'gap.large': pxToRem(30),
// PADDING VALUES
'padding.medium': pxToRem(10),
});
``` | /content/code_sandbox/packages/fluentui/react-northstar/src/themes/teams/components/Flex/flexVariables.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 139 |
```xml
import AutoupdateImplBase from './autoupdate-impl-base';
import WindowsUpdater from './windows-updater';
import { localized } from '../intl';
export default class AutoupdateImplWin32 extends AutoupdateImplBase {
supportsUpdates() {
return WindowsUpdater.existsSync();
}
checkForUpdates() {
if (!this.feedURL) {
return;
}
if (!WindowsUpdater.existsSync()) {
console.error('SquirrelUpdate does not exist');
return;
}
this.emit('checking-for-update');
this.manuallyQueryUpdateServer(json => {
if (!json) {
this.emit('update-not-available');
return;
}
this.emit('update-available');
this.lastRetrievedUpdateURL = json.url;
WindowsUpdater.spawn(['--update', json.url], (error, stdout) => {
if (error) {
this.emitError(error);
return;
}
this.emit('update-downloaded', {}, localized('A new version is available!'), json.version);
});
});
}
quitAndInstall() {
WindowsUpdater.restartMailspring(require('electron').app);
}
}
``` | /content/code_sandbox/app/src/browser/autoupdate-impl-win32.ts | xml | 2016-10-13T06:45:50 | 2024-08-16T18:14:37 | Mailspring | Foundry376/Mailspring | 15,331 | 244 |
```xml
/**
* @license
*
* 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.
*/
/**
* Facility for drawing a scale bar to indicate pixel size in physical length
* units.
*
* The physical length with which the scale bar is labeled will be of the form:
*
* significand * 10^exponent
*
* Any exponent may be used, but the significand in the range [1, 10] will be
* equal to one of a
* discrete set of allowed significand values, in order to ensure that the scale
* bar is easy to
* understand.
*/
import type { RenderViewport } from "#src/display_context.js";
import type {
DisplayDimensionRenderInfo,
RelativeDisplayScales,
} from "#src/navigation_state.js";
import { TrackableValue } from "#src/trackable_value.js";
import { RefCounted } from "#src/util/disposable.js";
import {
verifyFloat,
verifyObjectProperty,
verifyString,
} from "#src/util/json.js";
import { pickSiPrefix } from "#src/util/si_units.js";
import type { GL } from "#src/webgl/context.js";
import { OffscreenCopyHelper } from "#src/webgl/offscreen.js";
import { setTextureFromCanvas } from "#src/webgl/texture.js";
/**
* Default set of allowed significand values. 1 is implicitly part of the set.
*/
const DEFAULT_ALLOWED_SIGNIFICANDS = [1.5, 2, 3, 5, 7.5, 10];
export interface LengthUnit {
unit: string;
lengthInNanometers: number;
}
export const ALLOWED_UNITS: LengthUnit[] = [
{ unit: "km", lengthInNanometers: 1e12 },
{ unit: "m", lengthInNanometers: 1e9 },
{ unit: "mm", lengthInNanometers: 1e6 },
{ unit: "m", lengthInNanometers: 1e3 },
{ unit: "nm", lengthInNanometers: 1 },
{ unit: "pm", lengthInNanometers: 1e-3 },
];
export function pickLengthUnit(lengthInNanometers: number) {
const numAllowedUnits = ALLOWED_UNITS.length;
let unit = ALLOWED_UNITS[numAllowedUnits - 1];
for (let i = 0; i < numAllowedUnits; ++i) {
const allowedUnit = ALLOWED_UNITS[i];
if (lengthInNanometers >= allowedUnit.lengthInNanometers) {
unit = allowedUnit;
break;
}
}
return unit;
}
export function pickVolumeUnit(volumeInCubicNanometers: number) {
const numAllowedUnits = ALLOWED_UNITS.length;
let unit = ALLOWED_UNITS[numAllowedUnits - 1];
for (let i = 0; i < numAllowedUnits; ++i) {
const allowedUnit = ALLOWED_UNITS[i];
if (volumeInCubicNanometers >= allowedUnit.lengthInNanometers ** 3) {
unit = allowedUnit;
break;
}
}
return unit;
}
export class ScaleBarDimensions {
/**
* Allowed significand values. 1 is not included, but is always considered
* part of the set.
*/
allowedSignificands = DEFAULT_ALLOWED_SIGNIFICANDS;
/**
* The target length in pixels. The closest
*/
targetLengthInPixels = 0;
/**
* Pixel size in base physical units.
*/
physicalSizePerPixel = 0;
/**
* Base physical unit, e.g. "m" (for meters) or "s" (for seconds).
*/
physicalBaseUnit: string;
// The following three fields are computed from the previous three fields.
/**
* Length that scale bar should be drawn, in pixels.
*/
lengthInPixels: number;
/**
* Physical length with which to label the scale bar.
*/
physicalLength: number;
physicalUnit: string;
prevPhysicalSizePerPixel = 0;
prevTargetLengthInPixels = 0;
prevPhysicalUnit = "\0";
/**
* Updates physicalLength, physicalUnit, and lengthInPixels to be the optimal values corresponding
* to targetLengthInPixels and physicalSizePerPixel.
*
* @returns true if the scale bar has changed, false if it is unchanged.
*/
update() {
const { physicalSizePerPixel, targetLengthInPixels } = this;
if (
this.prevPhysicalSizePerPixel === physicalSizePerPixel &&
this.prevTargetLengthInPixels === targetLengthInPixels &&
this.prevPhysicalUnit === this.physicalUnit
) {
return false;
}
this.prevPhysicalSizePerPixel = physicalSizePerPixel;
this.prevTargetLengthInPixels = targetLengthInPixels;
this.prevPhysicalUnit = this.physicalUnit;
const targetPhysicalSize = targetLengthInPixels * physicalSizePerPixel;
const exponent = Math.floor(Math.log10(targetPhysicalSize));
const tenToThePowerExponent = 10 ** exponent;
const targetSignificand = targetPhysicalSize / tenToThePowerExponent;
// Determine significand value in this.allowedSignificands that is closest
// to targetSignificand.
let bestSignificand = 1;
for (const allowedSignificand of this.allowedSignificands) {
if (
Math.abs(allowedSignificand - targetSignificand) <
Math.abs(bestSignificand - targetSignificand)
) {
bestSignificand = allowedSignificand;
} else {
// If distance did not decrease, then it can only increase from here.
break;
}
}
const physicalSize = bestSignificand * tenToThePowerExponent;
const siPrefix = pickSiPrefix(physicalSize);
this.lengthInPixels = Math.round(physicalSize / physicalSizePerPixel);
this.physicalUnit = `${siPrefix.prefix}${this.physicalBaseUnit}`;
this.physicalLength =
bestSignificand * 10 ** (exponent - siPrefix.exponent);
return true;
}
}
function makeScaleBarTexture(
dimensions: ScaleBarDimensions,
gl: GL,
texture: WebGLTexture | null,
label: string,
options: ScaleBarTextureOptions,
) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d")!;
const textHeight = options.textHeightInPixels * options.scaleFactor;
const font = `bold ${textHeight}px ${options.fontName}`;
ctx.font = font;
ctx.fillStyle = "white";
const text = `${label}${dimensions.physicalLength} ${dimensions.physicalUnit}`;
const textMetrics = ctx.measureText(text);
const innerWidth = Math.max(dimensions.lengthInPixels, textMetrics.width);
const barHeight = options.barHeightInPixels * options.scaleFactor;
const barTopMargin = options.barTopMarginInPixels * options.scaleFactor;
const innerHeight = barHeight + barTopMargin + textHeight;
const padding = options.paddingInPixels * options.scaleFactor;
const totalHeight = innerHeight + 2 * padding;
const totalWidth = innerWidth + 2 * padding;
canvas.width = totalWidth;
canvas.height = totalHeight;
ctx.font = font;
ctx.textAlign = "center";
ctx.fillStyle = "rgba(0, 0, 0, 0.3)";
ctx.fillRect(0, 0, totalWidth, totalHeight);
ctx.fillStyle = "white";
ctx.fillText(
text,
totalWidth / 2,
totalHeight - padding - barHeight - barTopMargin,
);
ctx.fillRect(
padding,
totalHeight - padding - barHeight,
dimensions.lengthInPixels,
barHeight,
);
setTextureFromCanvas(gl, texture, canvas);
return { width: totalWidth, height: totalHeight };
}
export class ScaleBarTexture extends RefCounted {
texture: WebGLTexture | null = null;
width = 0;
height = 0;
label = "";
factor = 1;
private priorOptions: ScaleBarTextureOptions | undefined = undefined;
private prevLabel = "";
constructor(
public gl: GL,
public dimensions = new ScaleBarDimensions(),
) {
super();
}
update(options: ScaleBarTextureOptions) {
const { dimensions, label } = this;
let { texture } = this;
if (
!dimensions.update() &&
texture !== null &&
options === this.priorOptions &&
label === this.prevLabel
) {
return;
}
if (texture === null) {
texture = this.texture = this.gl.createTexture();
}
const { width, height } = makeScaleBarTexture(
dimensions,
this.gl,
texture,
label,
options,
);
this.priorOptions = options;
this.prevLabel = label;
this.width = width;
this.height = height;
}
disposed() {
this.gl.deleteTexture(this.texture);
this.texture = null;
super.disposed();
}
}
export class MultipleScaleBarTextures extends RefCounted {
private scaleBarCopyHelper = this.registerDisposer(
OffscreenCopyHelper.get(this.gl),
);
private scaleBars: ScaleBarTexture[] = [];
constructor(public gl: GL) {
super();
for (let i = 0; i < 3; ++i) {
this.scaleBars.push(this.registerDisposer(new ScaleBarTexture(gl)));
}
}
draw(
viewport: RenderViewport,
displayDimensionRenderInfo: DisplayDimensionRenderInfo,
relativeDisplayScales: RelativeDisplayScales,
effectiveZoom: number,
options: ScaleBarOptions,
) {
const { scaleBars } = this;
const {
displayRank,
displayDimensionIndices,
canonicalVoxelFactors,
globalDimensionNames,
displayDimensionUnits,
displayDimensionScales,
} = displayDimensionRenderInfo;
const { factors } = relativeDisplayScales;
const targetLengthInPixels = Math.min(
options.maxWidthFraction * viewport.logicalWidth,
options.maxWidthInPixels * options.scaleFactor,
);
let numScaleBars = 0;
for (let i = 0; i < displayRank; ++i) {
const dim = displayDimensionIndices[i];
const unit = displayDimensionUnits[i];
const factor = factors[dim];
let barIndex;
let scaleBar: ScaleBarTexture;
let scaleBarDimensions: ScaleBarDimensions;
for (barIndex = 0; barIndex < numScaleBars; ++barIndex) {
scaleBar = scaleBars[barIndex];
scaleBarDimensions = scaleBar.dimensions;
if (
scaleBarDimensions.physicalBaseUnit === unit &&
scaleBar.factor === factor
) {
break;
}
}
if (barIndex === numScaleBars) {
++numScaleBars;
scaleBar = scaleBars[barIndex];
scaleBar.label = "";
scaleBarDimensions = scaleBar.dimensions;
scaleBar.factor = factor;
scaleBarDimensions.physicalBaseUnit = unit;
scaleBarDimensions.targetLengthInPixels = targetLengthInPixels;
scaleBarDimensions.physicalSizePerPixel =
(displayDimensionScales[i] * effectiveZoom) /
canonicalVoxelFactors[i];
}
scaleBar!.label += `${globalDimensionNames[dim]} `;
}
const { gl, scaleBarCopyHelper } = this;
let bottomPixelOffset = options.bottomPixelOffset * options.scaleFactor;
for (let barIndex = numScaleBars - 1; barIndex >= 0; --barIndex) {
const scaleBar = scaleBars[barIndex];
if (numScaleBars === 1) {
scaleBar.label = "";
} else {
scaleBar.label += ": ";
}
scaleBar.update(options);
gl.viewport(
options.leftPixelOffset * options.scaleFactor -
viewport.visibleLeftFraction * viewport.logicalWidth,
bottomPixelOffset -
(1 - (viewport.visibleTopFraction + viewport.visibleHeightFraction)) *
viewport.logicalHeight,
scaleBar.width,
scaleBar.height,
);
scaleBarCopyHelper.draw(scaleBar.texture);
bottomPixelOffset +=
scaleBar.height +
options.marginPixelsBetweenScaleBars * options.scaleFactor;
}
}
}
export interface ScaleBarTextureOptions {
textHeightInPixels: number;
barTopMarginInPixels: number;
fontName: string;
barHeightInPixels: number;
paddingInPixels: number;
scaleFactor: number;
}
export interface ScaleBarOptions extends ScaleBarTextureOptions {
maxWidthInPixels: number;
maxWidthFraction: number;
leftPixelOffset: number;
bottomPixelOffset: number;
marginPixelsBetweenScaleBars: number;
}
export const defaultScaleBarTextureOptions: ScaleBarTextureOptions = {
scaleFactor: 1,
textHeightInPixels: 15,
barHeightInPixels: 8,
barTopMarginInPixels: 5,
fontName: "sans-serif",
paddingInPixels: 2,
};
export const defaultScaleBarOptions: ScaleBarOptions = {
...defaultScaleBarTextureOptions,
maxWidthInPixels: 100,
maxWidthFraction: 0.25,
leftPixelOffset: 10,
bottomPixelOffset: 10,
marginPixelsBetweenScaleBars: 5,
};
function parseScaleBarOptions(obj: any): ScaleBarOptions {
const result = {
...defaultScaleBarOptions,
};
for (const k of <Exclude<keyof ScaleBarOptions, "fontName">[]>[
"textHeightInPixels",
"barTopMarginInPixels",
"barHeightInPixels",
"paddingInPixels",
"scaleFactor",
"maxWidthInPixels",
"maxWidthFraction",
"leftPixelOffset",
"bottomPixelOffset",
]) {
verifyObjectProperty(obj, k, (x) => {
if (x !== undefined) {
result[k] = verifyFloat(x);
}
});
}
verifyObjectProperty(obj, "fontName", (x) => {
if (x !== undefined) {
result.fontName = verifyString(x);
}
});
return result;
}
export class TrackableScaleBarOptions extends TrackableValue<ScaleBarOptions> {
constructor() {
super(defaultScaleBarOptions, parseScaleBarOptions);
}
}
``` | /content/code_sandbox/src/widget/scale_bar.ts | xml | 2016-05-27T02:37:25 | 2024-08-16T07:24:25 | neuroglancer | google/neuroglancer | 1,045 | 3,154 |
```xml
import * as React from 'react';
import { render } from '@testing-library/react';
import { isConformant } from '../../testing/isConformant';
import { CarouselAutoplayButton } from './CarouselAutoplayButton';
import { CarouselAutoplayButtonProps } from './CarouselAutoplayButton.types';
describe('CarouselAutoplayButton', () => {
isConformant({
Component: CarouselAutoplayButton as React.FunctionComponent<CarouselAutoplayButtonProps>,
displayName: 'CarouselAutoplayButton',
testOptions: {
'has-static-classnames': [
{
props: {
icon: 'Test Icon',
},
},
],
},
});
// TODO add more tests here, and create visual regression tests in /apps/vr-tests
it('renders a default state', () => {
const result = render(<CarouselAutoplayButton />);
expect(result.container).toMatchSnapshot();
});
});
``` | /content/code_sandbox/packages/react-components/react-carousel-preview/library/src/components/CarouselAutoplayButton/CarouselAutoplayButton.test.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 195 |
```xml
// *** WARNING: this file was generated by test. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "./utilities";
export class Dog extends pulumi.CustomResource {
/**
* Get an existing Dog resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): Dog {
return new Dog(name, undefined as any, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'example::Dog';
/**
* Returns true if the given object is an instance of Dog. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is Dog {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Dog.__pulumiType;
}
public /*out*/ readonly bone!: pulumi.Output<string | undefined>;
/**
* Create a Dog resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args?: DogArgs, opts?: pulumi.CustomResourceOptions) {
let resourceInputs: pulumi.Inputs = {};
opts = opts || {};
if (!opts.id) {
resourceInputs["bone"] = undefined /*out*/;
} else {
resourceInputs["bone"] = undefined /*out*/;
}
opts = pulumi.mergeOptions(utilities.resourceOptsDefaults(), opts);
const replaceOnChanges = { replaceOnChanges: ["bone"] };
opts = pulumi.mergeOptions(opts, replaceOnChanges);
super(Dog.__pulumiType, name, resourceInputs, opts);
}
}
/**
* The set of arguments for constructing a Dog resource.
*/
export interface DogArgs {
}
``` | /content/code_sandbox/tests/testdata/codegen/replace-on-change/nodejs/dog.ts | xml | 2016-10-31T21:02:47 | 2024-08-16T19:47:04 | pulumi | pulumi/pulumi | 20,743 | 533 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="path_to_url" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hans" original="../LocalizableStrings.resx">
<body>
<trans-unit id="PackageIdArgumentDescription">
<source>The workload ID(s) to uninstall.</source>
<target state="translated"> ID</target>
<note />
</trans-unit>
<trans-unit id="CommandDescription">
<source>Uninstall one or more workloads.</source>
<target state="translated"></target>
<note />
</trans-unit>
<trans-unit id="PackageIdArgumentName">
<source>WORKLOAD_ID</source>
<target state="translated">WORKLOAD_ID</target>
<note />
</trans-unit>
<trans-unit id="RemovingWorkloadInstallationRecord">
<source>Removing workload installation record for {0}...</source>
<target state="translated"> {0} ...</target>
<note />
</trans-unit>
<trans-unit id="SpecifyExactlyOnePackageId">
<source>Specify one workload ID to uninstall.</source>
<target state="translated"> ID</target>
<note />
</trans-unit>
<trans-unit id="UninstallSucceeded">
<source>Successfully uninstalled workload(s): {0}</source>
<target state="translated">: {0}</target>
<note />
</trans-unit>
<trans-unit id="WorkloadNotInstalled">
<source>Couldn't find workload ID(s): {0}</source>
<target state="translated"> ID: {0}</target>
<note />
</trans-unit>
<trans-unit id="WorkloadUninstallFailed">
<source>Workload uninstallation failed: {0}</source>
<target state="translated">: {0}</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/Cli/dotnet/commands/dotnet-workload/uninstall/xlf/LocalizableStrings.zh-Hans.xlf | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 496 |
```xml
import { gql } from "@apollo/client";
import * as compose from "lodash.flowright";
import React from "react";
import { graphql } from "@apollo/client/react/hoc";
import { Alert, withProps } from "@erxes/ui/src/utils";
import BoardSelect from "../components/BoardSelect";
import { queries } from "../graphql";
import {
BoardsQueryResponse,
IStage,
PipelinesQueryResponse,
StagesQueryResponse
} from "../types";
type Props = {
type: string;
stageId?: string;
boardId: string;
pipelineId: string;
callback?: () => void;
onChangeStage?: (stageId: string) => void;
onChangePipeline: (pipelineId: string, stages: IStage[]) => void;
onChangeBoard: (boardId: string) => void;
autoSelectStage?: boolean;
translator?: (key: string, options?: any) => string;
isRequired?: boolean;
};
type FinalProps = {
boardsQuery: BoardsQueryResponse;
pipelinesQuery: PipelinesQueryResponse;
stagesQuery: StagesQueryResponse;
} & Props;
class BoardSelectContainer extends React.Component<FinalProps> {
onChangeBoard = (boardId: string) => {
this.props.onChangeBoard(boardId);
this.props.pipelinesQuery
.refetch({ boardId })
.then(({ data }) => {
const pipelines = data.ticketsPipelines;
if (pipelines.length > 0) {
this.onChangePipeline(pipelines[0]._id);
}
})
.catch(e => {
Alert.error(e.message);
});
};
onChangePipeline = (pipelineId: string) => {
const { stagesQuery } = this.props;
stagesQuery
.refetch({ pipelineId })
.then(({ data }) => {
const stages = data.stages;
this.props.onChangePipeline(pipelineId, stages);
if (
stages.length > 0 &&
typeof this.props.autoSelectStage === "undefined"
) {
this.onChangeStage(stages[0]._id);
}
})
.catch(e => {
Alert.error(e.message);
});
};
onChangeStage = (stageId: string, callback?: any) => {
if (this.props.onChangeStage) {
this.props.onChangeStage(stageId);
}
if (callback) {
callback();
}
};
render() {
const { boardsQuery, pipelinesQuery, stagesQuery } = this.props;
const boards = boardsQuery.ticketsBoards || [];
const pipelines = pipelinesQuery.ticketsPipelines || [];
const stages = stagesQuery.ticketsStages || [];
const extendedProps = {
...this.props,
boards,
pipelines,
stages,
onChangeBoard: this.onChangeBoard,
onChangePipeline: this.onChangePipeline,
onChangeStage: this.onChangeStage
};
console.log(boards, pipelines, stages, "12312");
return <BoardSelect {...extendedProps} />;
}
}
export default withProps<Props>(
compose(
graphql<Props, BoardsQueryResponse>(gql(queries.boards), {
name: "boardsQuery",
options: ({ type }) => ({
variables: { type }
})
}),
graphql<Props, PipelinesQueryResponse, { boardId: string }>(
gql(queries.pipelines),
{
name: "pipelinesQuery",
options: ({ boardId = "" }) => ({
variables: { boardId }
})
}
),
graphql<Props, StagesQueryResponse, { pipelineId: string }>(
gql(queries.stages),
{
name: "stagesQuery",
options: ({ pipelineId = "" }) => ({
variables: { pipelineId }
})
}
)
)(BoardSelectContainer)
);
``` | /content/code_sandbox/packages/ui-tickets/src/boards/containers/BoardSelect.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 812 |
```xml
import { readFile, rm } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { AsyncQueue } from '@sapphire/async-queue';
import { ensureDir } from 'fs-extra';
import { lockAndCallback, lockAndWrite } from '../../background-handler/fs-utils';
import type { InternalRequest } from '../../resource-clients/request-queue';
import type { StorageImplementation } from '../common';
import type { CreateStorageImplementationOptions } from '.';
export class RequestQueueFileSystemEntry implements StorageImplementation<InternalRequest> {
private filePath: string;
private fsQueue = new AsyncQueue();
private data?: InternalRequest;
private directoryExists = false;
/**
* A "sweep" timeout that is created/refreshed whenever this entry is accessed/updated.
* It exists to ensure that the entry is not kept in memory indefinitely, by sweeping it after 60 seconds of inactivity (in order to keep memory usage low)
*/
private sweepTimeout?: NodeJS.Timeout;
public orderNo?: number | null;
constructor(options: CreateStorageImplementationOptions) {
this.filePath = resolve(options.storeDirectory, `${options.requestId}.json`);
}
async get(force = false) {
await this.fsQueue.wait();
this.setOrRefreshSweepTimeout();
if (this.data && !force) {
this.fsQueue.shift();
return this.data;
}
try {
return await lockAndCallback(this.filePath, async () => {
const req = JSON.parse(await readFile(this.filePath, 'utf-8'));
this.data = req;
this.orderNo = req.orderNo;
return req;
});
} finally {
this.fsQueue.shift();
}
}
async update(data: InternalRequest) {
await this.fsQueue.wait();
this.data = data;
try {
if (!this.directoryExists) {
await ensureDir(dirname(this.filePath));
this.directoryExists = true;
}
await lockAndWrite(this.filePath, data);
this.orderNo = data.orderNo;
} finally {
this.setOrRefreshSweepTimeout();
this.fsQueue.shift();
}
}
async delete() {
await this.fsQueue.wait();
await rm(this.filePath, { force: true });
this.fsQueue.shift();
}
private setOrRefreshSweepTimeout() {
if (this.sweepTimeout) {
this.sweepTimeout.refresh();
} else {
this.sweepTimeout = setTimeout(() => {
this.sweepTimeout = undefined;
this.data = undefined;
}, 60_000).unref();
}
}
}
``` | /content/code_sandbox/packages/memory-storage/src/fs/request-queue/fs.ts | xml | 2016-08-26T18:35:03 | 2024-08-16T16:40:08 | crawlee | apify/crawlee | 14,153 | 559 |
```xml
import * as React from "react";
import { shallow } from "enzyme";
import { Button } from "./Button";
describe("Button", () => {
it("should exist", () => {
expect(Button).toBeDefined();
});
it("should match snapshot", () => {
const tree = shallow(<Button />);
expect(tree).toMatchSnapshot();
});
});
``` | /content/code_sandbox/src/components/Button.spec.tsx | xml | 2016-01-21T17:02:22 | 2024-08-12T19:21:02 | datacamp-light | datacamp/datacamp-light | 1,304 | 76 |
```xml
<resources>
<!--Sections-->
<string name="modules"></string>
<string name="superuser"></string>
<string name="logs"></string>
<string name="settings"></string>
<string name="install"></string>
<string name="section_home"></string>
<string name="section_theme"></string>
<string name="denylist"></string>
<!--Home-->
<string name="no_connection"> </string>
<string name="app_changelog"> </string>
<string name="loading"></string>
<string name="update"></string>
<string name="not_available">N/A</string>
<string name="hide"></string>
<string name="home_package"></string>
<string name="home_app_title"></string>
<string name="home_notice_content"> Github Magisk . !</string>
<string name="home_support_title"></string>
<string name="home_item_source"></string>
<string name="home_support_content">Magisk , . .</string>
<string name="home_installed_version"></string>
<string name="home_latest_version"></string>
<string name="invalid_update_channel"> </string>
<string name="uninstall_magisk_title">Magisk </string>
<string name="uninstall_magisk_msg"> /. , .</string>
<!--Install-->
<string name="keep_force_encryption"> </string>
<string name="keep_dm_verity">AVB 2.0/dm-verity </string>
<string name="recovery_mode"> </string>
<string name="install_options_title"></string>
<string name="install_method_title"> </string>
<string name="install_next"></string>
<string name="install_start"></string>
<string name="manager_download_install"> </string>
<string name="direct_install"> ()</string>
<string name="install_inactive_slot"> (OTA )</string>
<string name="install_inactive_slot_msg"> !\nOTA .\n?</string>
<string name="setup_title"> </string>
<string name="select_patch_file"> </string>
<string name="patch_file_msg">raw (*.img) ODIN tar (*.tar) </string>
<string name="reboot_delay_toast">5 </string>
<string name="flash_screen_title"></string>
<!--Superuser-->
<string name="su_request_title"> </string>
<string name="touch_filtered_warning"> , Magisk .</string>
<string name="deny"> </string>
<string name="prompt"> </string>
<string name="grant"> </string>
<string name="su_warning"> .\n !</string>
<string name="forever"></string>
<string name="once"> </string>
<string name="tenmin">10</string>
<string name="twentymin">20</string>
<string name="thirtymin">30</string>
<string name="sixtymin">60</string>
<string name="su_allow_toast">%1$s </string>
<string name="su_deny_toast">%1$s </string>
<string name="su_snack_grant">%1$s </string>
<string name="su_snack_deny">%1$s </string>
<string name="su_snack_notif_on">%1$s </string>
<string name="su_snack_notif_off">%1$s </string>
<string name="su_snack_log_on">%1$s </string>
<string name="su_snack_log_off">%1$s </string>
<string name="su_revoke_title">?</string>
<string name="su_revoke_msg"> %1$s ?</string>
<string name="toast"></string>
<string name="none"></string>
<string name="superuser_toggle_notification"></string>
<string name="superuser_toggle_revoke"></string>
<string name="superuser_policy_none"> .</string>
<!--Logs-->
<string name="log_data_none"> . .</string>
<string name="log_data_magisk_none">Magisk .</string>
<string name="menuSaveLog"> </string>
<string name="menuClearLog"> </string>
<string name="logs_cleared"> .</string>
<string name="pid">PID: %1$d</string>
<string name="target_uid">Target UID: %1$d</string>
<!--SafetyNet-->
<!--MagiskHide-->
<string name="show_system_app"> </string>
<string name="show_os_app">OS </string>
<string name="hide_filter_hint"> </string>
<string name="hide_search"></string>
<!--Module-->
<string name="no_info_provided">( )</string>
<string name="reboot_userspace"> </string>
<string name="reboot_recovery"> </string>
<string name="reboot_bootloader"> </string>
<string name="reboot_download"> </string>
<string name="reboot_edl">EDL </string>
<string name="module_version_author">%1$s by %2$s</string>
<string name="module_state_remove"></string>
<string name="module_state_restore"></string>
<string name="module_action_install_external"> </string>
<string name="update_available"> </string>
<string name="suspend_text_riru">%1$s .</string>
<string name="suspend_text_zygisk">%1$s .</string>
<string name="zygisk_module_unloaded"> Zygisk .</string>
<!--Settings-->
<string name="settings_dark_mode_title"> </string>
<string name="settings_dark_mode_message"> !</string>
<string name="settings_dark_mode_light"></string>
<string name="settings_dark_mode_system"> </string>
<string name="settings_dark_mode_dark"> </string>
<string name="settings_download_path_title"> </string>
<string name="settings_download_path_message"> %1$s </string>
<string name="settings_hide_app_title">Magisk </string>
<string name="settings_hide_app_summary"> ID Magisk .</string>
<string name="settings_restore_app_title">Magisk </string>
<string name="settings_restore_app_summary"> APK .</string>
<string name="language"></string>
<string name="system_default">( )</string>
<string name="settings_check_update_title"> </string>
<string name="settings_check_update_summary"> .</string>
<string name="settings_update_channel_title"> </string>
<string name="settings_update_stable"></string>
<string name="settings_update_beta"></string>
<string name="settings_update_custom"> </string>
<string name="settings_update_custom_msg"> URL </string>
<string name="settings_zygisk_summary">zygote Magisk </string>
<string name="settings_denylist_title">DenyList </string>
<string name="settings_denylist_summary">DenyList Magisk .</string>
<string name="settings_denylist_config_title">DenyList </string>
<string name="settings_denylist_config_summary">Denylist .</string>
<string name="settings_hosts_title">Systemless hosts</string>
<string name="settings_hosts_summary"> systemless hosts .</string>
<string name="settings_hosts_toast">Systemless hosts </string>
<string name="settings_app_name_hint"> </string>
<string name="settings_app_name_helper"> .</string>
<string name="settings_app_name_error"> </string>
<string name="settings_su_app_adb"> ADB</string>
<string name="settings_su_app"></string>
<string name="settings_su_adb">ADB</string>
<string name="settings_su_disable"> </string>
<string name="settings_su_request_10">10</string>
<string name="settings_su_request_15">15</string>
<string name="settings_su_request_20">20</string>
<string name="settings_su_request_30">30</string>
<string name="settings_su_request_45">45</string>
<string name="settings_su_request_60">60</string>
<string name="superuser_access"> </string>
<string name="auto_response"> </string>
<string name="request_timeout"> </string>
<string name="superuser_notification"> </string>
<string name="settings_su_reauth_title"> </string>
<string name="settings_su_reauth_summary"> .</string>
<string name="settings_su_tapjack_title"> </string>
<string name="settings_su_tapjack_summary"> .</string>
<string name="settings_customization"></string>
<string name="setting_add_shortcut_summary"> .</string>
<string name="settings_doh_title">DNS over HTTPS</string>
<string name="settings_doh_description"> DNS .</string>
<string name="multiuser_mode"> </string>
<string name="settings_owner_only"> </string>
<string name="settings_owner_manage"> </string>
<string name="settings_user_independent"></string>
<string name="owner_only_summary"> .</string>
<string name="owner_manage_summary"> .</string>
<string name="user_independent_summary"> .</string>
<string name="mount_namespace_mode"> </string>
<string name="settings_ns_global"> </string>
<string name="settings_ns_requester"> </string>
<string name="settings_ns_isolate"> </string>
<string name="global_summary"> .</string>
<string name="requester_summary"> .</string>
<string name="isolate_summary"> .</string>
<!--Notifications-->
<string name="update_channel">Magisk </string>
<string name="progress_channel"> </string>
<string name="updated_channel"> </string>
<string name="download_complete"> </string>
<string name="download_file_error"> </string>
<string name="magisk_update_title"> Magisk !</string>
<string name="updated_title">Magisk !</string>
<string name="updated_text"> </string>
<!--Toasts, Dialogs-->
<string name="yes"></string>
<string name="no"></string>
<string name="repo_install_title">%1$s %2$s(%3$d) </string>
<string name="download"></string>
<string name="reboot"> </string>
<string name="release_notes"></string>
<string name="flashing"> </string>
<string name="done">!</string>
<string name="failure">!</string>
<string name="hide_app_title">Magisk </string>
<string name="open_link_failed_toast"> .</string>
<string name="complete_uninstall"> </string>
<string name="restore_img"> </string>
<string name="restore_img_msg"> </string>
<string name="restore_done"> !</string>
<string name="restore_fail"> !</string>
<string name="setup_fail"> </string>
<string name="env_fix_title"> </string>
<string name="env_fix_msg">Magisk . ?</string>
<string name="setup_msg"> </string>
<string name="unsupport_magisk_title"> Magisk </string>
<string name="unsupport_magisk_msg"> %1$s Magisk .\n\n Magisk . Magisk .</string>
<string name="unsupport_general_title"> </string>
<string name="unsupport_system_app_msg"> . .</string>
<string name="unsupport_other_su_msg">Magisk \"su\" . , Magisk .</string>
<string name="unsupport_external_storage_msg">Magisk . Magisk .</string>
<string name="unsupport_nonroot_stub_msg"> Magisk . APK .</string>
<string name="unsupport_nonroot_stub_title">@string/settings_restore_app_title</string>
<string name="external_rw_permission_denied"> .</string>
<string name="install_unknown_denied"> " " .</string>
<string name="add_shortcut_title"> </string>
<string name="add_shortcut_msg"> .</string>
<string name="app_not_found"> .</string>
<string name="reboot_apply_change"> .</string>
<string name="restore_app_confirmation"> ? .</string>
</resources>
``` | /content/code_sandbox/app/core/src/main/res/values-ko/strings.xml | xml | 2016-09-08T12:42:53 | 2024-08-16T19:41:25 | Magisk | topjohnwu/Magisk | 46,424 | 2,916 |
```xml
'use strict';
export const DebuggerTypeName = 'python';
export const PythonDebuggerTypeName = 'debugpy';
``` | /content/code_sandbox/src/client/debugger/constants.ts | xml | 2016-01-19T10:50:01 | 2024-08-12T21:05:24 | pythonVSCode | DonJayamanne/pythonVSCode | 2,078 | 23 |
```xml
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<dataset update-count="1">
<metadata data-nodes="passthrough.t_data_type_money">
<column name="id" type="numeric" />
<column name="val" type="varchar" />
</metadata>
<row data-node="passthrough.t_data_type_money" values="1001, $123.00" />
<row data-node="passthrough.t_data_type_money" values="1002, -$11,889.68" />
</dataset>
``` | /content/code_sandbox/test/e2e/sql/src/test/resources/cases/dml/dataset/passthrough/update_money_subtract_value.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 174 |
```xml
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import isNil from 'lodash/isNil';
import isFunction from 'lodash/isFunction';
import remove from 'lodash/remove';
import clone from 'lodash/clone';
import isArray from 'lodash/isArray';
import omit from 'lodash/omit';
import pick from 'lodash/pick';
import { shallowEqual, getDataGroupBy } from '@/internals/utils';
import { filterNodesOfTree } from '@/internals/Tree/utils';
import Plaintext, { type PlaintextProps } from '@/internals/Plaintext';
import { useClassNames, useCustom, useControlled, useEventCallback } from '@/internals/hooks';
import { KEY_VALUES } from '@/internals/constants';
import { createChainedFunction, tplTransform, mergeRefs, isOneOf } from '@/internals/utils';
import { oneOf } from '@/internals/propTypes';
import {
Listbox,
ListItem,
ListCheckItem,
PickerToggle,
PickerPopup,
PickerToggleTrigger,
useFocusItemValue,
usePickerClassName,
useSearch,
usePickerRef,
useToggleKeyDownEvent,
pickTriggerPropKeys,
omitTriggerPropKeys,
PositionChildProps,
PickerComponent,
listPickerPropTypes,
PickerToggleProps
} from '@/internals/Picker';
import Tag from '../Tag';
import TextBox from './TextBox';
import { useTagContext } from './InputPickerContext';
import Stack, { type StackProps } from '../Stack';
import useInput from './hooks/useInput';
import useData, { type InputItemDataType } from './hooks/useData';
import { convertSize } from './utils';
import type { ItemDataType, FormControlPickerProps } from '@/internals/types';
import type { InputPickerLocale } from '../locales';
import type { SelectProps } from '../SelectPicker';
export type ValueType = any;
export interface InputPickerProps<V = ValueType>
extends FormControlPickerProps<V, InputPickerLocale, InputItemDataType>,
SelectProps<V>,
Pick<PickerToggleProps, 'caretAs' | 'loading'> {
tabIndex?: number;
/** Settings can create new options */
creatable?: boolean;
/** Option to cache value when searching asynchronously */
cacheData?: InputItemDataType<V>[];
/** The `onBlur` attribute for the `input` element. */
onBlur?: React.FocusEventHandler;
/** The `onFocus` attribute for the `input` element. */
onFocus?: React.FocusEventHandler;
/** Called when the option is created */
onCreate?: (value: V, item: ItemDataType, event: React.SyntheticEvent) => void;
/**
* Customize whether to display "Create option" action with given textbox value
*
* By default, InputPicker hides "Create option" action when textbox value matches any filtered item's [valueKey] property
*
* @param searchKeyword Value of the textbox
* @param filteredData The items filtered by the searchKeyword
*/
shouldDisplayCreateOption?: (
searchKeyword: string,
filteredData: InputItemDataType<V>[]
) => boolean;
}
/**
* Single item selector with text box input.
*
* @see path_to_url
*/
const InputPicker: PickerComponent<InputPickerProps> = React.forwardRef(
(props: InputPickerProps, ref) => {
const {
as: Component = 'div',
appearance = 'default',
cleanable = true,
cacheData = [],
classPrefix = 'picker',
data: controlledData = [],
disabled,
readOnly,
plaintext,
defaultValue,
defaultOpen = false,
disabledItemValues = [],
locale: overrideLocale,
toggleAs,
style,
size,
searchable = true,
open: controlledOpen,
placeholder,
placement = 'bottomStart',
groupBy,
menuClassName,
menuStyle,
menuAutoWidth = true,
menuMaxHeight = 320,
creatable,
shouldDisplayCreateOption,
value: valueProp,
valueKey = 'value',
virtualized,
labelKey = 'label',
listProps,
id,
tabIndex,
sort,
renderMenu,
renderExtraFooter,
renderValue,
renderMenuItem,
renderMenuGroup,
onEnter,
onEntered,
onExit,
onExited,
onChange,
onClean,
onCreate,
onSearch,
onSelect,
onBlur,
onFocus,
searchBy,
...rest
} = props;
const { multi, tagProps, trigger, disabledOptions, onTagRemove, renderCheckbox } =
useTagContext();
if (groupBy === valueKey || groupBy === labelKey) {
throw Error('`groupBy` can not be equal to `valueKey` and `labelKey`');
}
const { trigger: triggerRef, root, target, overlay, list } = usePickerRef(ref);
const { locale } = useCustom<InputPickerLocale>(['Picker', 'InputPicker'], overrideLocale);
const { prefix, merge } = useClassNames(classPrefix);
const [open, setOpen] = useControlled(controlledOpen, defaultOpen);
const { inputRef, inputProps, focus, blur } = useInput({ multi, triggerRef });
const handleDataChange = (data: ItemDataType[]) => {
setFocusItemValue(data?.[0]?.[valueKey]);
};
const { data, dataWithCache, newData, setNewData } = useData({
controlledData,
cacheData,
onChange: handleDataChange
});
const [value, setValue, isControlled] = useControlled<ValueType>(
valueProp,
multi ? defaultValue || [] : defaultValue
);
const cloneValue = () => (multi ? clone(value) || [] : value);
const handleClose = useEventCallback(() => {
triggerRef?.current?.close();
// The focus is on the trigger button after closing
target.current?.focus?.();
});
const focusItemValueOptions = { data: dataWithCache, valueKey, target: () => overlay.current };
// Used to hover the focuse item when trigger `onKeydown`
const { focusItemValue, setFocusItemValue, onKeyDown } = useFocusItemValue(
multi ? value?.[0] : value,
focusItemValueOptions
);
const onSearchCallback = useEventCallback(
(searchKeyword: string, filteredData: InputItemDataType[], event: React.SyntheticEvent) => {
if (!disabledOptions) {
// The first option after filtering is the focus.
let firstItemValue = filteredData?.[0]?.[valueKey];
// If there is no value in the option and new options are supported, the search keyword is the first option
if (!firstItemValue && creatable) {
firstItemValue = searchKeyword;
}
setFocusItemValue(firstItemValue);
}
onSearch?.(searchKeyword, event);
}
);
const searchOptions = { labelKey, searchBy, callback: onSearchCallback };
// Use search keywords to filter options.
const { searchKeyword, resetSearch, checkShouldDisplay, handleSearch } = useSearch(
data,
searchOptions
);
// Update the position of the menu when the search keyword and value change
useEffect(() => {
triggerRef.current?.updatePosition?.();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchKeyword, value]);
const getDataItem = (value: any) => {
// Find active `MenuItem` by `value`
const activeItem = dataWithCache.find(item => shallowEqual(item[valueKey], value));
let itemNode: React.ReactNode = placeholder;
if (activeItem?.[labelKey]) {
itemNode = activeItem?.[labelKey];
}
return {
isValid: !!activeItem,
activeItem,
itemNode
};
};
/**
* Convert the string of the newly created option into an object.
*/
const createOption = (value: string) => {
const option = {
create: true,
[valueKey]: value,
[labelKey]: value
};
if (groupBy) {
return {
[groupBy]: locale?.newItem,
...option
};
}
return option;
};
const handleChange = useEventCallback((value: any, event: React.SyntheticEvent) => {
onChange?.(value, event);
});
const handleRemoveItemByTag = useEventCallback((tag: string, event: React.MouseEvent) => {
event.stopPropagation();
const val = cloneValue();
remove(val, itemVal => shallowEqual(itemVal, tag));
setValue(val);
handleChange(val, event);
onTagRemove?.(tag, event);
});
const handleSelect = useEventCallback(
(value: string | string[], item: InputItemDataType, event: React.SyntheticEvent) => {
onSelect?.(value, item, event);
if (creatable && item.create) {
delete item.create;
onCreate?.(value, item, event);
setNewData(newData.concat(item));
}
}
);
/**
* Callback triggered by single selection
* @param value
* @param item
* @param event
*/
const handleSelectItem = useEventCallback(
(value: string, item: InputItemDataType, event: React.MouseEvent) => {
setValue(value);
setFocusItemValue(value);
resetSearch();
handleSelect(value, item, event);
handleChange(value, event);
handleClose();
}
);
/**
* Callback triggered by multiple selection
* @param nextItemValue
* @param item
* @param event
* @param checked
*/
const handleCheckTag = useEventCallback(
(
nextItemValue: string,
item: InputItemDataType,
event: React.MouseEvent,
checked: boolean
) => {
const val = cloneValue();
if (checked) {
val.push(nextItemValue);
} else {
remove(val, itemVal => shallowEqual(itemVal, nextItemValue));
}
setValue(val);
resetSearch();
setFocusItemValue(nextItemValue);
handleSelect(val, item, event);
handleChange(val, event);
focus();
}
);
const handleTagKeyPress = useEventCallback((event: React.KeyboardEvent) => {
// When composing, ignore the keypress event.
if (event.nativeEvent.isComposing) {
return;
}
const val = cloneValue();
let newItemValue = focusItemValue || '';
// In TagInput
if (multi && disabledOptions) {
newItemValue = searchKeyword;
}
if (!newItemValue || !data) {
return;
}
// If the value is disabled in this option, it is returned.
if (disabledItemValues?.some(item => item === newItemValue)) {
return;
}
if (!val.some(v => shallowEqual(v, newItemValue))) {
val.push(newItemValue);
} else if (!disabledOptions) {
remove(val, itemVal => shallowEqual(itemVal, newItemValue));
}
let focusItem = data.find(item => shallowEqual(item?.[valueKey], newItemValue));
if (!focusItem) {
focusItem = createOption(newItemValue);
}
setValue(val);
resetSearch();
handleSelect(val, focusItem, event);
handleChange(val, event);
});
const handleMenuItemKeyPress = useEventCallback((event: React.KeyboardEvent) => {
if (!focusItemValue || !controlledData) {
return;
}
// If the value is disabled in this option, it is returned.
if (disabledItemValues?.some(item => item === focusItemValue)) {
return;
}
// Find active `MenuItem` by `value`
let focusItem = data.find(item => shallowEqual(item[valueKey], focusItemValue));
// FIXME Bad state flow
if (!focusItem && focusItemValue === searchKeyword) {
focusItem = createOption(searchKeyword);
}
setValue(focusItemValue);
resetSearch();
if (focusItem) {
handleSelect(focusItemValue, focusItem, event);
}
handleChange(focusItemValue, event);
handleClose();
});
/**
* Remove the last item, after pressing the back key on the keyboard.
* @param event
*/
const removeLastItem = useEventCallback((event: React.KeyboardEvent<HTMLInputElement>) => {
const target = event?.target as HTMLInputElement;
if (target?.tagName !== 'INPUT') {
focus();
return;
}
if (target?.tagName === 'INPUT' && target?.value) {
return;
}
const val = cloneValue();
val.pop();
setValue(val);
handleChange(val, event);
});
const handleClean = useEventCallback((event: React.SyntheticEvent) => {
if (disabled || searchKeyword !== '') {
return;
}
setValue(null);
setFocusItemValue(null);
resetSearch();
if (multi) {
handleChange([], event);
} else {
handleChange(null, event);
}
onClean?.(event);
});
const events = {
onMenuPressBackspace: multi ? removeLastItem : handleClean,
onMenuKeyDown: onKeyDown,
onMenuPressEnter: undefined as React.ReactEventHandler | undefined,
onKeyDown: undefined as React.ReactEventHandler | undefined
};
const handleKeyPress = useEventCallback((event: React.KeyboardEvent<any>) => {
// When typing a space, create a tag.
if (isOneOf('Space', trigger) && event.key === KEY_VALUES.SPACE) {
handleTagKeyPress(event);
event.preventDefault();
}
// When typing a comma, create a tag.
if (isOneOf('Comma', trigger) && event.key === KEY_VALUES.COMMA) {
handleTagKeyPress(event);
event.preventDefault();
}
});
if (multi) {
if (isOneOf('Enter', trigger)) {
events.onMenuPressEnter = handleTagKeyPress;
}
if (creatable) {
events.onKeyDown = handleKeyPress;
}
} else {
events.onMenuPressEnter = handleMenuItemKeyPress;
}
const onPickerKeyDown = useToggleKeyDownEvent({
trigger: triggerRef,
target,
overlay,
...events,
...rest
});
const handleExited = useEventCallback(() => {
setFocusItemValue(multi ? value?.[0] : value);
resetSearch();
});
const handleFocus = useEventCallback((event: React.FocusEvent) => {
if (!readOnly) {
setOpen(true);
triggerRef.current?.open();
}
onFocus?.(event);
});
const handleEnter = useEventCallback(() => {
focus();
setOpen(true);
});
const handleExit = useEventCallback(() => {
blur();
setOpen(false);
});
const renderListItem = (label: React.ReactNode, item: InputItemDataType) => {
// 'Create option "{0}"' => Create option "xxxxx"
const newLabel = item.create ? (
<span>{tplTransform(locale.createOption, label)}</span>
) : (
label
);
return renderMenuItem ? renderMenuItem(newLabel, item) : newLabel;
};
const checkValue = () => {
if (multi) {
return { isValid: false, itemNode: null };
}
const dataItem = getDataItem(value);
let itemNode = dataItem.itemNode;
if (!isNil(value) && isFunction(renderValue)) {
itemNode = renderValue(
value,
dataItem.activeItem as ItemDataType<string | number>,
itemNode
);
}
return { isValid: dataItem.isValid, itemNode };
};
const renderMultiValue = () => {
if (!multi) {
return null;
}
const { closable = true, onClose, ...tagRest } = tagProps;
const tags = value || [];
const items: (ItemDataType | undefined)[] = [];
const tagElements = tags
.map(tag => {
const { isValid, itemNode, activeItem } = getDataItem(tag);
items.push(activeItem);
if (!isValid) {
return null;
}
return (
<Tag
role="option"
{...tagRest}
key={tag}
size={convertSize(size)}
closable={!disabled && closable && !readOnly && !plaintext}
title={typeof itemNode === 'string' ? itemNode : undefined}
onClose={createChainedFunction(handleRemoveItemByTag.bind(null, tag), onClose)}
>
{itemNode}
</Tag>
);
})
.filter(item => item !== null);
if ((tags.length > 0 || isControlled) && isFunction(renderValue)) {
return renderValue(value, items, tagElements);
}
return tagElements;
};
const renderPopup = (positionProps: PositionChildProps, speakerRef) => {
const { left, top, className } = positionProps;
const menuClassPrefix = multi ? 'picker-check-menu' : 'picker-select-menu';
const classes = merge(className, menuClassName, prefix(multi ? 'check-menu' : 'select-menu'));
const styles = { ...menuStyle, left, top };
let items: ItemDataType[] = filterNodesOfTree(data, checkShouldDisplay);
if (
creatable &&
(typeof shouldDisplayCreateOption === 'function'
? shouldDisplayCreateOption(searchKeyword, items)
: searchKeyword && !items.find(item => item[valueKey] === searchKeyword))
) {
items = [...items, createOption(searchKeyword)];
}
// Create a tree structure data when set `groupBy`
if (groupBy) {
items = getDataGroupBy(items, groupBy, sort);
} else if (typeof sort === 'function') {
items = items.sort(sort(false));
}
if (disabledOptions) {
return <PickerPopup ref={mergeRefs(overlay, speakerRef)} />;
}
const menu = items.length ? (
<Listbox
listProps={listProps}
listRef={list}
disabledItemValues={disabledItemValues}
valueKey={valueKey}
labelKey={labelKey}
classPrefix={menuClassPrefix}
listItemClassPrefix={multi ? undefined : `${menuClassPrefix}-item`}
listItemAs={multi ? ListCheckItem : ListItem}
listItemProps={{ renderCheckbox }}
activeItemValues={multi ? value : [value]}
focusItemValue={focusItemValue}
maxHeight={menuMaxHeight}
data={items}
query={searchKeyword}
groupBy={groupBy}
onSelect={multi ? handleCheckTag : handleSelectItem}
renderMenuGroup={renderMenuGroup}
renderMenuItem={renderListItem}
virtualized={virtualized}
/>
) : (
<div className={prefix`none`}>{locale?.noResultsText}</div>
);
return (
<PickerPopup
ref={mergeRefs(overlay, speakerRef)}
autoWidth={menuAutoWidth}
className={classes}
style={styles}
target={triggerRef}
onKeyDown={onPickerKeyDown}
>
{renderMenu ? renderMenu(menu) : menu}
{renderExtraFooter?.()}
</PickerPopup>
);
};
const { isValid, itemNode } = checkValue();
const tagElements = renderMultiValue();
/**
* 1.Have a value and the value is valid.
* 2.Regardless of whether the value is valid, as long as renderValue is set, it is judged to have a value.
* 3.If renderValue returns null or undefined, hasValue is false.
*/
const hasSingleValue = !isNil(value) && isFunction(renderValue) && !isNil(itemNode);
const hasMultiValue =
isArray(value) && value.length > 0 && isFunction(renderValue) && !isNil(tagElements);
const hasValue = multi ? !!tagElements?.length || hasMultiValue : isValid || hasSingleValue;
const [pickerClasses, usedClassNamePropKeys] = usePickerClassName({
...props,
classPrefix,
appearance,
hasValue,
name: 'input',
cleanable
});
const classes = merge(pickerClasses, {
[prefix`tag`]: multi,
[prefix(`${multi ? 'tag' : 'input'}-${size}`)]: size,
[prefix`focused`]: open,
[prefix`disabled-options`]: disabledOptions
});
const searching = !!searchKeyword && open;
const editable = searchable && !disabled && !rest.loading;
if (plaintext) {
const plaintextProps: PlaintextProps & StackProps = {};
// When multiple selection, the tag is displayed in a stack layout.
if (multi && hasValue) {
plaintextProps.as = Stack;
plaintextProps.spacing = 6;
plaintextProps.wrap = true;
plaintextProps.childrenRenderMode = 'clone';
}
return (
<Plaintext localeKey="notSelected" ref={target} {...plaintextProps}>
{itemNode || (tagElements?.length ? tagElements : null) || placeholder}
</Plaintext>
);
}
const placeholderNode = placeholder || (disabledOptions ? null : locale?.placeholder);
return (
<PickerToggleTrigger
id={id}
multiple={multi}
pickerProps={pick(props, pickTriggerPropKeys)}
ref={triggerRef}
trigger="active"
onEnter={createChainedFunction(handleEnter, onEnter)}
onEntered={onEntered}
onExit={createChainedFunction(handleExit, onExit)}
onExited={createChainedFunction(handleExited, onExited)}
speaker={renderPopup}
placement={placement}
>
<Component
className={classes}
style={style}
onClick={focus}
onKeyDown={onPickerKeyDown}
ref={root}
>
<PickerToggle
{...omit(rest, [...omitTriggerPropKeys, ...usedClassNamePropKeys])}
appearance={appearance}
readOnly={readOnly}
plaintext={plaintext}
ref={target}
as={toggleAs}
tabIndex={tabIndex}
onClean={handleClean}
cleanable={cleanable && !disabled}
hasValue={hasValue}
active={open}
disabled={disabled}
placement={placement}
inputValue={value}
focusItemValue={focusItemValue}
caret={!disabledOptions}
size={size}
>
{searching || (multi && hasValue) ? null : itemNode || placeholderNode}
</PickerToggle>
<TextBox
showTagList={hasValue && multi}
inputRef={inputRef}
inputValue={open ? searchKeyword : ''}
inputProps={inputProps}
tags={tagElements}
editable={editable}
readOnly={readOnly}
disabled={disabled}
multiple={multi}
onBlur={onBlur}
onFocus={handleFocus}
onChange={handleSearch}
/>
</Component>
</PickerToggleTrigger>
);
}
);
InputPicker.displayName = 'InputPicker';
InputPicker.propTypes = {
...listPickerPropTypes,
locale: PropTypes.any,
appearance: oneOf(['default', 'subtle']),
cacheData: PropTypes.array,
menuAutoWidth: PropTypes.bool,
menuMaxHeight: PropTypes.number,
searchable: PropTypes.bool,
creatable: PropTypes.bool,
groupBy: PropTypes.any,
sort: PropTypes.func,
renderMenu: PropTypes.func,
renderMenuItem: PropTypes.func,
renderMenuGroup: PropTypes.func,
onCreate: PropTypes.func,
onSelect: PropTypes.func,
onGroupTitleClick: PropTypes.func,
onSearch: PropTypes.func,
virtualized: PropTypes.bool,
searchBy: PropTypes.func
};
export default InputPicker;
``` | /content/code_sandbox/src/InputPicker/InputPicker.tsx | xml | 2016-06-06T02:27:46 | 2024-08-16T16:41:54 | rsuite | rsuite/rsuite | 8,263 | 5,179 |
```xml
import { c } from 'ttag';
import promotionExpired from './promotionExpired.svg';
const PromotionExpired = () => {
return (
<div className="h-full flex flex-column justify-center items-center bg-norm text-center">
<img src={promotionExpired} alt="" />
<h1 className="text-bold text-2xl mb-2 mt-8">{c('Info').t`Promotion expired`}</h1>
<div>{c('Info').t`This promotion link has expired.`}</div>
<div>{c('Info').t`Stay tuned for future promotions.`}</div>
</div>
);
};
export default PromotionExpired;
``` | /content/code_sandbox/applications/account/src/lite/components/PromotionExpired/PromotionExpired.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 143 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="path_to_url">
<PropertyGroup Label="VSTSOutputDirectory">
<OutputSubDir>Tests\$(MSBuildProjectName)</OutputSubDir>
</PropertyGroup>
</Project>
``` | /content/code_sandbox/Tests/custom.props | xml | 2016-03-20T08:48:45 | 2024-08-16T07:55:40 | WinAppDriver | microsoft/WinAppDriver | 3,626 | 66 |
```xml
/**
* @license
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Event properties used by the adapter and foundation.
*/
export interface MDCMenuItemEventDetail {
index: number;
}
/**
* Event properties specific to the default component implementation.
*/
export interface MDCMenuItemComponentEventDetail extends
MDCMenuItemEventDetail {
item: Element;
}
// Note: CustomEvent<T> is not supported by Closure Compiler.
export interface MDCMenuItemEvent extends Event {
readonly detail: MDCMenuItemEventDetail;
}
export interface MDCMenuItemComponentEvent extends Event {
readonly detail: MDCMenuItemComponentEventDetail;
}
``` | /content/code_sandbox/packages/mdc-menu/types.ts | xml | 2016-12-05T16:04:09 | 2024-08-16T15:42:22 | material-components-web | material-components/material-components-web | 17,119 | 344 |
```xml
import { createElement, Fragment, ReactNode } from 'react'
import uniq from 'lodash/uniq'
import { SvgWrapper, useDimensions, Container } from '@nivo/core'
import { BoxLegendSvg } from '@nivo/legends'
import { svgDefaultProps } from './props'
import { useSankey } from './hooks'
import { SankeyNodes } from './SankeyNodes'
import { SankeyLinks } from './SankeyLinks'
import { SankeyLabels } from './SankeyLabels'
import {
DefaultLink,
DefaultNode,
SankeyLayerId,
SankeyLinkDatum,
SankeyNodeDatum,
SankeySvgProps,
} from './types'
type InnerSankeyProps<N extends DefaultNode, L extends DefaultLink> = Omit<
SankeySvgProps<N, L>,
'animate' | 'motionConfig' | 'renderWrapper' | 'theme'
>
const InnerSankey = <N extends DefaultNode, L extends DefaultLink>({
data,
valueFormat,
layout = svgDefaultProps.layout,
sort = svgDefaultProps.sort,
align = svgDefaultProps.align,
width,
height,
margin: partialMargin,
colors = svgDefaultProps.colors,
nodeThickness = svgDefaultProps.nodeThickness,
nodeSpacing = svgDefaultProps.nodeThickness,
nodeInnerPadding = svgDefaultProps.nodeInnerPadding,
nodeBorderColor = svgDefaultProps.nodeBorderColor,
nodeOpacity = svgDefaultProps.nodeOpacity,
nodeHoverOpacity = svgDefaultProps.nodeHoverOpacity,
nodeHoverOthersOpacity = svgDefaultProps.nodeHoverOthersOpacity,
nodeBorderWidth = svgDefaultProps.nodeBorderWidth,
nodeBorderRadius = svgDefaultProps.nodeBorderRadius,
linkOpacity = svgDefaultProps.linkOpacity,
linkHoverOpacity = svgDefaultProps.linkHoverOpacity,
linkHoverOthersOpacity = svgDefaultProps.linkHoverOthersOpacity,
linkContract = svgDefaultProps.linkContract,
linkBlendMode = svgDefaultProps.linkBlendMode,
enableLinkGradient = svgDefaultProps.enableLinkGradient,
enableLabels = svgDefaultProps.enableLabels,
labelPosition = svgDefaultProps.labelPosition,
labelPadding = svgDefaultProps.labelPadding,
labelOrientation = svgDefaultProps.labelOrientation,
label = svgDefaultProps.label,
labelTextColor = svgDefaultProps.labelTextColor,
nodeTooltip = svgDefaultProps.nodeTooltip,
linkTooltip = svgDefaultProps.linkTooltip,
isInteractive = svgDefaultProps.isInteractive,
onClick,
legends = svgDefaultProps.legends,
layers = svgDefaultProps.layers,
role = svgDefaultProps.role,
ariaLabel,
ariaLabelledBy,
ariaDescribedBy,
}: InnerSankeyProps<N, L>) => {
const { margin, innerWidth, innerHeight, outerWidth, outerHeight } = useDimensions(
width,
height,
partialMargin
)
const {
nodes,
links,
legendData,
getNodeBorderColor,
currentNode,
setCurrentNode,
currentLink,
setCurrentLink,
getLabelTextColor,
} = useSankey<N, L>({
data,
valueFormat,
layout,
width: innerWidth,
height: innerHeight,
sort,
align,
colors,
nodeThickness,
nodeSpacing,
nodeInnerPadding,
nodeBorderColor,
label,
labelTextColor,
})
let isCurrentNode: (node: SankeyNodeDatum<N, L>) => boolean = () => false
let isCurrentLink: (link: SankeyLinkDatum<N, L>) => boolean = () => false
if (currentLink) {
isCurrentNode = ({ id }: SankeyNodeDatum<N, L>) =>
id === currentLink.source.id || id === currentLink.target.id
isCurrentLink = ({ source, target }: SankeyLinkDatum<N, L>) =>
source.id === currentLink.source.id && target.id === currentLink.target.id
}
if (currentNode) {
let currentNodeIds = [currentNode.id]
links
.filter(
({ source, target }) => source.id === currentNode.id || target.id === currentNode.id
)
.forEach(({ source, target }) => {
currentNodeIds.push(source.id)
currentNodeIds.push(target.id)
})
currentNodeIds = uniq(currentNodeIds)
isCurrentNode = ({ id }) => currentNodeIds.includes(id)
isCurrentLink = ({ source, target }) =>
source.id === currentNode.id || target.id === currentNode.id
}
const layerProps = {
links,
nodes,
margin,
width,
height,
outerWidth,
outerHeight,
}
const layerById: Record<SankeyLayerId, ReactNode> = {
links: null,
nodes: null,
labels: null,
legends: null,
}
if (layers.includes('links')) {
layerById.links = (
<SankeyLinks<N, L>
key="links"
links={links}
layout={layout}
linkContract={linkContract}
linkOpacity={linkOpacity}
linkHoverOpacity={linkHoverOpacity}
linkHoverOthersOpacity={linkHoverOthersOpacity}
linkBlendMode={linkBlendMode}
enableLinkGradient={enableLinkGradient}
setCurrentLink={setCurrentLink}
currentNode={currentNode}
currentLink={currentLink}
isCurrentLink={isCurrentLink}
isInteractive={isInteractive}
onClick={onClick}
tooltip={linkTooltip}
/>
)
}
if (layers.includes('nodes')) {
layerById.nodes = (
<SankeyNodes<N, L>
key="nodes"
nodes={nodes}
nodeOpacity={nodeOpacity}
nodeHoverOpacity={nodeHoverOpacity}
nodeHoverOthersOpacity={nodeHoverOthersOpacity}
borderWidth={nodeBorderWidth}
borderRadius={nodeBorderRadius}
getBorderColor={getNodeBorderColor}
setCurrentNode={setCurrentNode}
currentNode={currentNode}
currentLink={currentLink}
isCurrentNode={isCurrentNode}
isInteractive={isInteractive}
onClick={onClick}
tooltip={nodeTooltip}
/>
)
}
if (layers.includes('labels') && enableLabels) {
layerById.labels = (
<SankeyLabels<N, L>
key="labels"
nodes={nodes}
layout={layout}
width={innerWidth}
height={innerHeight}
labelPosition={labelPosition}
labelPadding={labelPadding}
labelOrientation={labelOrientation}
getLabelTextColor={getLabelTextColor}
/>
)
}
if (layers.includes('legends')) {
layerById.legends = (
<Fragment key="legends">
{legends.map((legend, i) => (
<BoxLegendSvg
key={`legend${i}`}
{...legend}
containerWidth={innerWidth}
containerHeight={innerHeight}
data={legendData}
/>
))}
</Fragment>
)
}
return (
<SvgWrapper
width={outerWidth}
height={outerHeight}
margin={margin}
role={role}
ariaLabel={ariaLabel}
ariaLabelledBy={ariaLabelledBy}
ariaDescribedBy={ariaDescribedBy}
>
{layers.map((layer, i) => {
if (typeof layer === 'function') {
return <Fragment key={i}>{createElement(layer, layerProps)}</Fragment>
}
return layerById?.[layer] ?? null
})}
</SvgWrapper>
)
}
export const Sankey = <N extends DefaultNode = DefaultNode, L extends DefaultLink = DefaultLink>({
isInteractive = svgDefaultProps.isInteractive,
animate = svgDefaultProps.animate,
motionConfig = svgDefaultProps.motionConfig,
theme,
renderWrapper,
...otherProps
}: SankeySvgProps<N, L>) => (
<Container
{...{
animate,
isInteractive,
motionConfig,
renderWrapper,
theme,
}}
>
<InnerSankey<N, L> isInteractive={isInteractive} {...otherProps} />
</Container>
)
``` | /content/code_sandbox/packages/sankey/src/Sankey.tsx | xml | 2016-04-16T03:27:56 | 2024-08-16T03:38:37 | nivo | plouc/nivo | 13,010 | 1,734 |
```xml
import { G2Spec } from '../../../src';
export async function peopleIntervalSplitMerge(): Promise<G2Spec> {
const data = await fetch('data/people.json').then((res) => res.json());
return {
type: 'timingKeyframe',
duration: 1000,
children: [
{
type: 'interval',
transform: [{ type: 'groupX', y: 'mean' }],
data,
encode: {
x: 'gender',
y: 'weight',
color: 'gender',
key: 'gender',
},
},
{
type: 'point',
data,
encode: {
x: 'height',
y: 'weight',
color: 'gender',
shape: 'point',
groupKey: 'gender',
},
},
],
};
}
peopleIntervalSplitMerge.intervals = [false, [500], [500]];
``` | /content/code_sandbox/__tests__/plots/animation/people-interval-split-merge.ts | xml | 2016-05-26T09:21:04 | 2024-08-15T16:11:17 | G2 | antvis/G2 | 12,060 | 196 |
```xml
/** @jsx jsx */
import { Transforms } from 'slate'
import { jsx } from '../../..'
export const input = (
<editor>
<block>
<cursor />
one
</block>
<block>
<block>two</block>
</block>
</editor>
)
export const run = editor => {
Transforms.moveNodes(editor, { at: [0], to: [1, 1] })
}
export const output = (
<editor>
<block>
<block>two</block>
<block>
<cursor />
one
</block>
</block>
</editor>
)
``` | /content/code_sandbox/packages/slate/test/transforms/moveNodes/path/inside-next.tsx | xml | 2016-06-18T01:52:42 | 2024-08-16T18:43:42 | slate | ianstormtaylor/slate | 29,492 | 144 |
```xml
'use client'
import React from 'react'
function ClientComponent() {
const [state] = React.useState('component')
return <div>{`client-` + state}</div>
}
export const clientRef = <ClientComponent />
``` | /content/code_sandbox/test/e2e/app-dir/metadata-dynamic-routes/app/client-ref-dependency/client-component.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 50 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sample</groupId>
<artifactId>mavenlombok</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
``` | /content/code_sandbox/org.eclipse.jdt.ls.tests/projects/maven/mavenlombok/pom.xml | xml | 2016-06-27T13:06:53 | 2024-08-16T00:38:32 | eclipse.jdt.ls | eclipse-jdtls/eclipse.jdt.ls | 1,726 | 239 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="path_to_url">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="fastest_partial_icl_quantifier.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\test_type_lists.hpp">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>
``` | /content/code_sandbox/deps/boost_1_66_0/libs/icl/test/fastest_partial_icl_quantifier_/vc10_fastest_partial_icl_quantifier.vcxproj.filters | xml | 2016-09-05T10:18:44 | 2024-08-11T13:21:40 | LiquidCore | LiquidPlayer/LiquidCore | 1,010 | 342 |
```xml
declare interface IIceCreamLorryWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
}
declare module 'IceCreamLorryWebPartStrings' {
const strings: IIceCreamLorryWebPartStrings;
export = strings;
}
``` | /content/code_sandbox/samples/react-app-settings/src/webparts/iceCreamLorry/loc/mystrings.d.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 64 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="path_to_url" xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fuzzer</groupId>
<artifactId>fuzz-targets</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>fuzz</name>
<description>fuzz</description>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.code-intelligence</groupId>
<artifactId>jazzer-junit</artifactId>
<version>0.19.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>Fuzzing-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-jakarta-servlet-api</artifactId>
<version>5.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>11.0.14</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
</plugin>
</plugins>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
</build>
</project>
``` | /content/code_sandbox/projects/async-http-client/project-parent/fuzz-targets/pom.xml | xml | 2016-07-20T19:39:50 | 2024-08-16T10:54:09 | oss-fuzz | google/oss-fuzz | 10,251 | 501 |
```xml
import { draftMode } from 'next/headers'
export function GET() {
draftMode().disable()
return new Response(
'Disabled in Route Handler using draftMode().enable(), check cookies'
)
}
``` | /content/code_sandbox/test/e2e/app-dir/draft-mode/app/with-edge/disable/route.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 46 |
```xml
/**
* Static Props support
*/
import { createElement } from "react"; // eslint-disable-line
import { SubAppDef, SubAppFeatureFactory } from "@xarc/subapp";
import {
StaticPropsFeatureOptions,
_staticPropsFeatureId,
_staticPropsFeatureSubId
} from "../common/feat-static-props-types";
/**
* Add support for static props to a subapp
*
* TODO: handle hot module reload
*
* @param options - static props feature options
* @returns subapp feature factory for static props
*/
export function staticPropsFeature(options: StaticPropsFeatureOptions): SubAppFeatureFactory {
const id = _staticPropsFeatureId;
const subId = _staticPropsFeatureSubId;
return {
id,
subId,
add(subapp: SubAppDef) {
const serverModule = require(options.serverModule); // eslint-disable-line
const exportName = options.exportName || "getStaticProps";
subapp._features.staticProps = {
id,
subId,
async execute({ input, ssrData }) {
let res = serverModule[exportName]({ ssrData });
if (res.then) {
res = await res;
}
return {
Component: () => <input.Component {...res.props} />,
props: res.props
};
}
};
return subapp;
}
};
}
``` | /content/code_sandbox/packages/xarc-react/src/node/feat-static-props-node.tsx | xml | 2016-09-06T19:02:39 | 2024-08-11T11:43:11 | electrode | electrode-io/electrode | 2,103 | 300 |
```xml
class Person {
#name: string;
constructor(name: string) {
this.#name = name;
}
equals(other: unknown) {
return (
other &&
typeof other === "object" &&
#name in other && // <- this is new!
this.#name === other.#name
);
}
}
``` | /content/code_sandbox/tests/format/typescript/private-fields-in-in/basic.ts | xml | 2016-11-29T17:13:37 | 2024-08-16T17:29:57 | prettier | prettier/prettier | 48,913 | 74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.