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 <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <!-- Dark Buttons --> <style name="ThemeOverlay.MyDarkButton" parent="ThemeOverlay.AppCompat.Dark"> <item name="colorButtonNormal">@color/colorAccent</item> <item name="android:layout_marginRight">4dp</item> <item name="android:layout_marginLeft">4dp</item> <item name="android:textColor">@android:color/white</item> </style> </resources> ```
/content/code_sandbox/appdistribution/app/src/main/res/values/styles.xml
xml
2016-04-26T17:13:27
2024-08-16T18:37:58
quickstart-android
firebase/quickstart-android
8,797
218
```xml import { BasicTooltip, Chip } from '@nivo/tooltip' import { DefaultLink, DefaultNode, SankeyLinkDatum } from './types' const tooltipStyles = { container: { display: 'flex', alignItems: 'center', }, sourceChip: { marginRight: 7, }, targetChip: { marginLeft: 7, marginRight: 7, }, } export interface SankeyLinkTooltipProps<N extends DefaultNode, L extends DefaultLink> { link: SankeyLinkDatum<N, L> } export const SankeyLinkTooltip = <N extends DefaultNode, L extends DefaultLink>({ link, }: SankeyLinkTooltipProps<N, L>) => ( <BasicTooltip id={ <span style={tooltipStyles.container}> <Chip color={link.source.color} style={tooltipStyles.sourceChip} /> <strong>{link.source.label}</strong> {' > '} <strong>{link.target.label}</strong> <Chip color={link.target.color} style={tooltipStyles.targetChip} /> <strong>{link.formattedValue}</strong> </span> } /> ) ```
/content/code_sandbox/packages/sankey/src/SankeyLinkTooltip.tsx
xml
2016-04-16T03:27:56
2024-08-16T03:38:37
nivo
plouc/nivo
13,010
246
```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 { assert } from "chai"; import { type EnzymePropSelector, mount, type ReactWrapper } from "enzyme"; import * as React from "react"; import { spy, stub } from "sinon"; import { type OptionProps, Radio, RadioGroup } from "../../src"; import { RADIOGROUP_WARN_CHILDREN_OPTIONS_MUTEX } from "../../src/common/errors"; describe("<RadioGroup>", () => { const emptyHandler = () => { return; }; it("nothing is selected by default", () => { const group = mount( <RadioGroup onChange={emptyHandler}> <Radio value="one" label="One" /> <Radio value="two" label="Two" /> </RadioGroup>, ); assert.lengthOf(group.find({ checked: true }), 0); }); it("selectedValue checks that value", () => { const group = mount( <RadioGroup onChange={emptyHandler} selectedValue="two"> <Radio value="one" label="One" /> <Radio value="two" label="Two" /> </RadioGroup>, ); assert.isTrue(findInput(group, { checked: true }).is({ value: "two" })); }); it("invokes onChange handler when a radio is clicked", () => { const changeSpy = spy(); const group = mount( <RadioGroup onChange={changeSpy}> <Radio value="one" label="One" /> <Radio value="two" label="Two" /> </RadioGroup>, ); findInput(group, { value: "one" }).simulate("change"); findInput(group, { value: "two" }).simulate("change"); assert.equal(changeSpy.callCount, 2); }); it("renders options as radio buttons", () => { const OPTIONS: OptionProps[] = [ { className: "foo", label: "A", value: "a" }, { label: "B", value: "b" }, { disabled: true, label: "C", value: "c" }, ]; const group = mount(<RadioGroup onChange={emptyHandler} options={OPTIONS} selectedValue="b" />); const radios = group.find(Radio); assert.isTrue(radios.at(0).hasClass("foo"), "className"); assert.isTrue(radios.at(1).is({ checked: true }), "selectedValue"); assert.isTrue(radios.at(2).prop("disabled"), "disabled"); }); it("options label defaults to value", () => { const OPTIONS = [{ value: "text" }, { value: 23 }]; const group = mount(<RadioGroup onChange={emptyHandler} options={OPTIONS} selectedValue="b" />); OPTIONS.forEach(props => { assert.strictEqual(findInput(group, props).parents().first().text(), props.value.toString()); }); }); it("uses options if given both options and children (with conosle warning)", () => { const warnSpy = stub(console, "warn"); const group = mount( <RadioGroup onChange={emptyHandler} options={[]}> <Radio value="one" /> </RadioGroup>, ); assert.lengthOf(group.find(Radio), 0); assert.isTrue(warnSpy.alwaysCalledWith(RADIOGROUP_WARN_CHILDREN_OPTIONS_MUTEX)); warnSpy.restore(); }); it("renders non-Radio children too", () => { const group = mount( <RadioGroup onChange={emptyHandler}> <Radio /> <address /> <Radio /> </RadioGroup>, ); assert.lengthOf(group.find("address"), 1); assert.lengthOf(group.find(Radio), 2); }); function findInput(wrapper: ReactWrapper<any, any>, props: EnzymePropSelector) { return wrapper.find("input").filter(props); } }); ```
/content/code_sandbox/packages/core/test/controls/radioGroupTests.tsx
xml
2016-10-25T21:17:50
2024-08-16T15:14:48
blueprint
palantir/blueprint
20,593
862
```xml import * as assert from "assert"; import * as nls from "vscode-nls"; import { ErrorHelper } from "../../common/error/errorHelper"; import { InternalErrorCode } from "../../common/error/internalErrorCode"; import { PlatformType } from "../launchArgs"; import { AppLauncher } from "../appLauncher"; import { OutputChannelLogger } from "../log/OutputChannelLogger"; import { ExponentPlatform } from "../exponent/exponentPlatform"; import { getRunOptions } from "./util"; import { Command } from "./util/command"; const localize = nls.loadMessageBundle(); const logger = OutputChannelLogger.getMainChannel(); export class launchExpoWeb extends Command { codeName = "launchExpoWeb"; label = "Launch ExpoWeb"; error = ErrorHelper.getInternalError(InternalErrorCode.FailedToLaunchExpoWeb); async baseFn(launchArgs: any): Promise<any> { assert(this.project); const expoHelper = this.project.getExponentHelper(); logger.info(localize("CheckExpoEnvironment", "Checking Expo project environment.")); const isExpo = await expoHelper.isExpoManagedApp(true); if (!isExpo) { logger.info(localize("NotAnExpoProject", "This is not an Expo project.")); return; } await runExpoWeb(this.project); } } async function runExpoWeb(project: AppLauncher) { const platform = new ExponentPlatform(getRunOptions(project, PlatformType.ExpoWeb), { packager: project.getPackager(), }); platform; await platform.beforeStartPackager(); await platform.startPackager(); } ```
/content/code_sandbox/src/extension/commands/launchExpoWeb.ts
xml
2016-01-20T21:10:07
2024-08-16T15:29:52
vscode-react-native
microsoft/vscode-react-native
2,617
349
```xml <?xml version="1.0" encoding="UTF-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2"> <file source-language="en" target-language="sk" datatype="plaintext" original="validators.en.xlf"> <body> <trans-unit id="IkNxbBI" resname="This value is not a valid role."> <source>This value is not a valid role.</source> <target>Tto hodnota nie je platnou rolou.</target> </trans-unit> <trans-unit id="CLHaByy" resname="End date must not be earlier then start date."> <source>End date must not be earlier then start date.</source> <target>Dtum ukonenia nesmie by skor ako dtum zaiatku.</target> </trans-unit> <trans-unit id="ePrqiLM" resname="The begin date cannot be in the future."> <source>The begin date cannot be in the future.</source> <target>Dtum zaiatku neme by v budcnosti.</target> </trans-unit> <trans-unit id="VJSZSD0" resname="The given value is not a valid time."> <source>The given value is not a valid time.</source> <target>Tto hodnota nie je platn as.</target> </trans-unit> <trans-unit id="u2wjm2i" resname="You already have an entry for this time."> <source>You already have an entry for this time.</source> <target>Pre tento as u mte zznam.</target> </trans-unit> <trans-unit id="0o.pH3X" resname="This period is locked, please choose a later date."> <source>This period is locked, please choose a later date.</source> <target>Toto obdobie je uzamknut, vyberte prosm neskor dtum.</target> </trans-unit> <trans-unit id="yDlKSRw" resname="This invoice document cannot be used, please rename the file and upload it again."> <source>This invoice document cannot be used, please rename the file and upload it again.</source> <target>Tento fakturan dokument nie je mon poui. Sbor prosm premenujte a nahrajte znova.</target> </trans-unit> <trans-unit id="1V6BsD_" resname="You must select at least one user or team."> <source>You must select at least one user or team.</source> <target>Muste zvoli aspo jednho pouvatea alebo tm.</target> </trans-unit> <trans-unit id="6WAG.Xj" resname="The entered passwords don't match."> <source>The entered passwords don't match.</source> <target state="translated">Zadan hesl sa nezhoduj.</target> </trans-unit> <trans-unit id="INlaCgW" resname="An equal email is already used."> <source>An equal e-mail address is already in use.</source> <target state="translated">Rovnak emailov adresa sa u pouva.</target> </trans-unit> <trans-unit id="mjlH0la" resname="This timesheet is already exported."> <source>This timesheet is already exported.</source> <target state="translated">Tento pracovn vkaz u bol vyexportovan.</target> </trans-unit> <trans-unit id="gSAwscA" resname="Validation Failed"> <source>Validation Failed</source> <target state="translated">Pri ukladan dolo k chybe.</target> </trans-unit> <trans-unit resname="Cannot stop running timesheet" id="7HYTefs"> <source>Cannot stop running timesheet</source> <target state="translated">Mte aktvny asov zznam, ktor sa neme automaticky zastavi.</target> </trans-unit> <trans-unit id="xp0lmgm" resname="The given code is not the correct TOTP token."> <source>The given code is not the correct TOTP token.</source> <target state="translated">Zadan kd nie je sprvny TOTP token.</target> </trans-unit> <trans-unit id="7mqg3TC" resname="This value is not a valid role name."> <source>This value is not a valid role name.</source> <target state="translated">Toto nie je platn nzov pre pouvatesk rolu.</target> </trans-unit> <trans-unit id="S14XECA" resname="The username is already used."> <source>The username is already used.</source> <target state="translated">Toto pouvatek meno sa u pouva.</target> </trans-unit> <trans-unit id="Jz1y3yB" resname="Duration cannot be zero."> <source>Duration cannot be zero.</source> <target state="translated">Nie je povolen prdzna doba trvania.</target> </trans-unit> <trans-unit id="6rO8GZ1" resname="Maximum duration of {{ value }} hours exceeded."> <source>Maximum duration of {{ value }} hours exceeded.</source> <target state="translated">Povolen maximlne {{ value }} hodn.</target> </trans-unit> <trans-unit id="to1Q85W" resname="An activity needs to be selected."> <source>An activity needs to be selected.</source> <target state="translated">Mus by vybran aktivita.</target> </trans-unit> <trans-unit id="dcPei9G" resname="Sorry, the budget is used up."> <source>Sorry, the budget is used up.</source> <target state="translated">Pardon, rozpoet je u vyerpan.</target> </trans-unit> <trans-unit id="rmH78_V" resname="At least one team leader must be assigned to the team."> <source>At least one team leader must be assigned to the team.</source> <target state="translated">K tmu mus by priraden aspo jeden vedci.</target> </trans-unit> <trans-unit id="6u6oCwB" resname="The email is already used."> <source>This e-mail address is already in use.</source> <target state="translated">Tto emailov adresa sa u pouva.</target> </trans-unit> <trans-unit id="ekO5eXI" resname="An equal username is already used."> <source>An equal username is already used.</source> <target state="translated">Rovnak pouvatesk meno sa u pouva.</target> </trans-unit> <trans-unit id="rHd9_aA" resname="A project needs to be selected."> <source>A project needs to be selected.</source> <target state="translated">Mus by vybran projekt.</target> </trans-unit> <trans-unit id="1oKCOa5" resname="The budget is completely used."> <source>The budget is completely used.</source> <target state="translated">Rozpoet je vyerpan. Z plnovanho %budget% bolo %used%, me by ete pout %free%.</target> </trans-unit> </body> </file> </xliff> ```
/content/code_sandbox/translations/validators.sk.xlf
xml
2016-10-20T17:06:34
2024-08-16T18:27:30
kimai
kimai/kimai
3,084
1,704
```xml <?xml version='1.0' encoding='UTF-8'?> <services> <container version="1.0"> <!-- Avoid using DefaultLinguisticsProvider --> <component id="com.yahoo.language.simple.SimpleLinguistics" /> <search> <chain id="default" inherits="vespa"/> <provider id="bar" type="local" cluster="foo"> <searcher id="MockResultSearcher" class="com.yahoo.application.MockResultSearcher"/> </provider> </search> <accesslog type="disabled" /> </container> <content version="1.0" id="foo"> <redundancy>2</redundancy> <documents> <document type="mydoc" mode="index"/> </documents> <nodes> <node hostalias="node1" distribution-key="1"/> </nodes> </content> </services> ```
/content/code_sandbox/application/src/test/app-packages/withqueryprofile/services.xml
xml
2016-06-03T20:54:20
2024-08-16T15:32:01
vespa
vespa-engine/vespa
5,524
202
```xml import type { MaybeNull, UniqueItem } from '@proton/pass/types'; import type { CustomAliasCreateRequest } from '../api'; import type { ItemType } from '../protobuf'; import type { IndexedByShareIdAndItemId, Item, ItemRevision } from './items'; type AliasMailbox = { id: number; email: string }; export type AliasCreationDTO = { mailboxes: AliasMailbox[]; prefix: CustomAliasCreateRequest['Prefix']; signedSuffix: CustomAliasCreateRequest['SignedSuffix']; aliasEmail: string; }; export type LoginWithAliasCreationDTO = { withAlias: true; alias: ItemCreateIntent<'alias'> } | { withAlias: false }; /** * Item creation DTO indexed on ItemType keys * - alias specifics : extra parameters required for alias creation * - login specifics : support login with alias creation intent */ export type ItemCreateIntentDTO = { alias: AliasCreationDTO; login: LoginWithAliasCreationDTO; note: never; }; export type ItemEditIntentDTO = { alias: MaybeNull<{ aliasOwner: boolean; mailboxes: AliasMailbox[]; aliasEmail: string }>; login: never; note: never; creditCard: never; identity: never; }; export type ItemImportIntentDTO = { alias: { aliasEmail: string }; login: never; note: never; }; /* Intent payloads */ export type ItemCreateIntent<T extends ItemType = ItemType> = Item<T, ItemCreateIntentDTO> & { optimisticId: string; shareId: string; createTime: number; }; export type ItemEditIntent<T extends ItemType = ItemType> = Item<T, ItemEditIntentDTO> & { itemId: string; shareId: string; lastRevision: number; }; export type ItemImportIntent<T extends ItemType = ItemType> = Item<T, ItemImportIntentDTO> & { trashed: boolean; createTime?: number; modifyTime?: number; }; export type ItemMoveDTO = { before: ItemRevision; after: ItemRevision }; /** This data-structure does not uses lists to avoid * iterations when checking for inclusions */ export type BulkSelectionDTO = IndexedByShareIdAndItemId<true>; export type ItemRevisionsIntent = { itemId: string; pageSize: number; shareId: string; since: MaybeNull<string>; }; export type ItemRevisionsSuccess = { next: MaybeNull<string>; revisions: ItemRevision[]; since: MaybeNull<string>; total: number; }; export type SecureLinkItem = { item: Item; expirationDate: number; readCount?: number }; export type SecureLinkOptions = { expirationTime: number; maxReadCount: MaybeNull<number> }; export type SecureLinkCreationDTO = UniqueItem & SecureLinkOptions; export type SecureLinkDeleteDTO = UniqueItem & { linkId: string }; export type SecureLinkQuery = { token: string; linkKey: string }; export type SecureLink = UniqueItem & { active: boolean; expirationDate: number; readCount: number; maxReadCount: MaybeNull<number>; linkId: string; secureLink: string; }; ```
/content/code_sandbox/packages/pass/types/data/items.dto.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
672
```xml import React from 'react'; type IconProps = React.SVGProps<SVGSVGElement>; export declare const IcPinAngledFilled: (props: IconProps) => React.JSX.Element; export {}; ```
/content/code_sandbox/packages/icons/lib/icPinAngledFilled.d.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
45
```xml const commontTypes = ` _id: String key: OverallWorkKey workIds: [String] type: String jobRefer: JobRefer product: Product count: Float needProducts: JSON resultProducts: JSON inDepartment: Department inBranch: Branch outDepartment: Department outBranch: Branch `; export const types = ` type OverallWorkKey { inBranchId: String inDepartmentId: String outBranchId: String outDepartmentId: String type: String typeId: String } type OverallWork @key(fields: "_id") @cacheControl(maxAge: 3) { ${commontTypes} } type OverallWorkDetail @key(fields: "_id") @cacheControl(maxAge: 3) { ${commontTypes} startAt: Date dueDate: Date interval: JSON intervalId: String needProductsData: JSON resultProductsData: JSON } `; const paginateParams = ` page: Int perPage: Int sortField: String sortDirection: Int `; const qryParams = ` search: String type: String startDate: Date endDate: Date inBranchId: String outBranchId: String inDepartmentId: String outDepartmentId: String productCategoryId: String productIds: [String] vendorIds: [String] jobCategoryId: String jobReferId: String `; const detailParamsDef = ` startDate: Date endDate: Date type: String productCategoryId: String productIds: [String] jobReferId: String inBranchId: String outBranchId: String inDepartmentId: String outDepartmentId: String `; export const queries = ` overallWorks(${qryParams}, ${paginateParams}): [OverallWork] overallWorksCount(${qryParams}): Int overallWorkDetail(${detailParamsDef}): OverallWorkDetail `; export const mutations = ` `; ```
/content/code_sandbox/packages/plugin-processes-api/src/graphql/schema/overallWork.ts
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
470
```xml import { nextTestSetup } from 'e2e-utils' import { check, retry } from 'next-test-utils' describe('parallel-routes-revalidation', () => { const { next, isNextStart, isNextDeploy } = nextTestSetup({ files: __dirname, }) // This test is skipped when deployed as it relies on a shared data store // For testing purposes we just use an in-memory object, but when deployed // this could hit a separate lambda instance that won't share the same reference if (!isNextDeploy) { it('should submit the action and revalidate the page data', async () => { const browser = await next.browser('/') await check(() => browser.hasElementByCssSelector('#create-entry'), false) // there shouldn't be any data yet expect((await browser.elementsByCss('#entries li')).length).toBe(0) await browser.elementByCss("[href='/revalidate-modal']").click() await check(() => browser.hasElementByCssSelector('#create-entry'), true) await browser.elementById('create-entry').click() // we created an entry and called revalidate, so we should have 1 entry await retry(async () => { expect((await browser.elementsByCss('#entries li')).length).toBe(1) }) await browser.elementById('create-entry').click() // we created an entry and called revalidate, so we should have 2 entries await retry(async () => { expect((await browser.elementsByCss('#entries li')).length).toBe(2) }) await browser.elementByCss("[href='/']").click() // following a link back to `/` should close the modal await check(() => browser.hasElementByCssSelector('#create-entry'), false) await check(() => browser.elementByCss('body').text(), /Current Data/) }) } it('should handle router.refresh() when called in a slot', async () => { const browser = await next.browser('/') await check(() => browser.hasElementByCssSelector('#refresh-router'), false) const currentRandomNumber = ( await browser.elementById('random-number') ).text() await browser.elementByCss("[href='/refresh-modal']").click() await check(() => browser.hasElementByCssSelector('#refresh-router'), true) await browser.elementById('refresh-router').click() await check(async () => { const randomNumber = (await browser.elementById('random-number')).text() return randomNumber !== currentRandomNumber }, true) await browser.elementByCss("[href='/']").click() // following a link back to `/` should close the modal await check(() => browser.hasElementByCssSelector('#create-entry'), false) await check(() => browser.elementByCss('body').text(), /Current Data/) }) it('should handle a redirect action when called in a slot', async () => { const browser = await next.browser('/') await check(() => browser.hasElementByCssSelector('#redirect'), false) await browser.elementByCss("[href='/redirect-modal']").click() await check(() => browser.hasElementByCssSelector('#redirect'), true) await browser.elementById('redirect').click() await check(() => browser.hasElementByCssSelector('#redirect'), false) await check(() => browser.elementByCss('body').text(), /Current Data/) }) it.each([ { path: '/detail-page' }, { path: '/dynamic/foobar', param: 'foobar' }, { path: '/catchall/foobar', param: 'foobar' }, ])( 'should not trigger interception when calling router.refresh() on an intercepted route ($path)', async (route) => { const browser = await next.browser(route.path) // directly loaded the detail page, so it should not be intercepted. expect(await browser.elementById('detail-title').text()).toBe( 'Detail Page (Non-Intercepted)' ) const randomNumber = (await browser.elementById('random-number')).text() // confirm that if the route contained a dynamic parameter, that it's reflected in the UI if (route.param) { expect(await browser.elementById('params').text()).toBe(route.param) } // click the refresh button await browser.elementByCss('button').click() await retry(async () => { const newRandomNumber = await browser .elementById('random-number') .text() // we should have received a new random number, indicating the non-intercepted page was refreshed expect(randomNumber).not.toBe(newRandomNumber) // confirm that the page is still not intercepted expect(await browser.elementById('detail-title').text()).toBe( 'Detail Page (Non-Intercepted)' ) // confirm the params (if previously present) are still present if (route.param) { expect(await browser.elementById('params').text()).toBe(route.param) } }) } ) it('should not trigger full page when calling router.refresh() on an intercepted route', async () => { const browser = await next.browser('/dynamic') await browser.elementByCss('a').click() // we soft-navigated to the route, so it should be intercepted expect(await browser.elementById('detail-title').text()).toBe( 'Detail Page (Intercepted)' ) const randomNumber = (await browser.elementById('random-number')).text() // confirm the dynamic param is reflected in the UI expect(await browser.elementById('params').text()).toBe('foobar') // click the refresh button await browser.elementByCss('button').click() await retry(async () => { // confirm that the intercepted page data was refreshed const newRandomNumber = await browser.elementById('random-number').text() // confirm that the page is still intercepted expect(randomNumber).not.toBe(newRandomNumber) expect(await browser.elementById('detail-title').text()).toBe( 'Detail Page (Intercepted)' ) // confirm the paramsare still present expect(await browser.elementById('params').text()).toBe('foobar') }) }) it('should not trigger the intercepted route when lazy-fetching missing data', async () => { const browser = await next.browser('/') // trigger the interception page await browser.elementByCss("[href='/detail-page']").click() // we should see the intercepted page expect(await browser.elementById('detail-title').text()).toBe( 'Detail Page (Intercepted)' ) // refresh the page await browser.refresh() // we should see the detail page expect(await browser.elementById('detail-title').text()).toBe( 'Detail Page (Non-Intercepted)' ) // go back to the previous page await browser.back() // reload the page, which will cause the router to no longer have cache nodes await browser.refresh() // go forward, this will trigger a lazy fetch for the missing data, and should restore the detail page await browser.forward() expect(await browser.elementById('detail-title').text()).toBe( 'Detail Page (Non-Intercepted)' ) }) // This test is skipped when deployed as it relies on a shared data store // For testing purposes we just use an in-memory object, but when deployed // this could hit a separate lambda instance that won't share the same reference if (!isNextDeploy) { it('should refresh the correct page when a server action triggers a redirect', async () => { const browser = await next.browser('/redirect') await browser.elementByCss('button').click() await browser.elementByCss("[href='/revalidate-modal']").click() await check(() => browser.hasElementByCssSelector('#create-entry'), true) await browser.elementById('clear-entries').click() await retry(async () => { // confirm there aren't any entries yet expect((await browser.elementsByCss('#entries li')).length).toBe(0) }) await browser.elementById('create-entry').click() await retry(async () => { // we created an entry and called revalidate, so we should have 1 entry expect((await browser.elementsByCss('#entries li')).length).toBe(1) }) }) } describe.each([ { basePath: '/refreshing', label: 'regular', withSearchParams: false }, { basePath: '/refreshing', label: 'regular', withSearchParams: true }, { basePath: '/dynamic-refresh/foo', label: 'dynamic', withSearchParams: false, }, { basePath: '/dynamic-refresh/foo', label: 'dynamic', withSearchParams: true, }, ])( 'router.refresh ($label) - searchParams: $withSearchParams', ({ basePath, withSearchParams }) => { it('should correctly refresh data for the intercepted route and previously active page slot', async () => { const browser = await next.browser(basePath) let initialSearchParams: string | undefined if (withSearchParams) { // add some search params prior to proceeding await browser.elementById('update-search-params').click() await retry(async () => { initialSearchParams = await browser .elementById('search-params') .text() expect(initialSearchParams).toMatch(/^Params: "0\.\d+"$/) }) } let initialRandomNumber = await browser.elementById('random-number') await browser.elementByCss(`[href='${basePath}/login']`).click() // interception modal should be visible let initialModalRandomNumber = await browser .elementById('modal-random') .text() // trigger a refresh await browser.elementById('refresh-button').click() await retry(async () => { const newRandomNumber = await browser .elementById('random-number') .text() const newModalRandomNumber = await browser .elementById('modal-random') .text() expect(initialRandomNumber).not.toBe(newRandomNumber) expect(initialModalRandomNumber).not.toBe(newModalRandomNumber) // reset the initial values to be the new values, so that we can verify the revalidate case below. initialRandomNumber = newRandomNumber initialModalRandomNumber = newModalRandomNumber }) // trigger a revalidate await browser.elementById('revalidate-button').click() await retry(async () => { const newRandomNumber = await browser .elementById('random-number') .text() const newModalRandomNumber = await browser .elementById('modal-random') .text() expect(initialRandomNumber).not.toBe(newRandomNumber) expect(initialModalRandomNumber).not.toBe(newModalRandomNumber) if (withSearchParams) { // add additional search params in the new modal await browser.elementById('update-search-params-modal').click() expect( await browser.elementById('search-params-modal').text() ).toMatch(/^Params: "0\.\d+"$/) // make sure the old params are still there too expect(await browser.elementById('search-params').text()).toBe( initialSearchParams ) } }) // reload the page, triggering which will remove the interception route and show the full page await browser.refresh() const initialLoginPageRandomNumber = await browser .elementById('login-page-random') .text() // trigger a refresh await browser.elementById('refresh-button').click() await retry(async () => { const newLoginPageRandomNumber = await browser .elementById('login-page-random') .text() expect(newLoginPageRandomNumber).not.toBe( initialLoginPageRandomNumber ) }) }) it('should correctly refresh data for previously intercepted modal and active page slot', async () => { const browser = await next.browser(basePath) await browser.elementByCss(`[href='${basePath}/login']`).click() // interception modal should be visible let initialModalRandomNumber = await browser .elementById('modal-random') .text() await browser.elementByCss(`[href='${basePath}/other']`).click() // data for the /other page should be visible let initialOtherPageRandomNumber = await browser .elementById('other-page-random') .text() // trigger a refresh await browser.elementById('refresh-button').click() await retry(async () => { const newModalRandomNumber = await browser .elementById('modal-random') .text() const newOtherPageRandomNumber = await browser .elementById('other-page-random') .text() expect(initialModalRandomNumber).not.toBe(newModalRandomNumber) expect(initialOtherPageRandomNumber).not.toBe( newOtherPageRandomNumber ) // reset the initial values to be the new values, so that we can verify the revalidate case below. initialOtherPageRandomNumber = newOtherPageRandomNumber initialModalRandomNumber = newModalRandomNumber }) // trigger a revalidate await browser.elementById('revalidate-button').click() await retry(async () => { const newModalRandomNumber = await browser .elementById('modal-random') .text() const newOtherPageRandomNumber = await browser .elementById('other-page-random') .text() expect(initialModalRandomNumber).not.toBe(newModalRandomNumber) expect(initialOtherPageRandomNumber).not.toBe( newOtherPageRandomNumber ) }) }) } ) describe('server action revalidation', () => { it('handles refreshing when multiple parallel slots are active', async () => { const browser = await next.browser('/nested-revalidate') const currentPageTime = await browser.elementById('page-now').text() expect(await browser.hasElementByCssSelector('#modal')).toBe(false) expect(await browser.hasElementByCssSelector('#drawer')).toBe(false) // renders the drawer parallel slot await browser.elementByCss("[href='/nested-revalidate/drawer']").click() await browser.waitForElementByCss('#drawer') // renders the modal slot await browser.elementByCss("[href='/nested-revalidate/modal']").click() await browser.waitForElementByCss('#modal') // Both should be visible, despite only one "matching" expect(await browser.hasElementByCssSelector('#modal')).toBe(true) expect(await browser.hasElementByCssSelector('#drawer')).toBe(true) // grab the current time of the drawer const currentDrawerTime = await browser.elementById('drawer-now').text() // trigger the revalidation action in the modal. await browser.elementById('modal-submit-button').click() await retry(async () => { // Revalidation should close the modal expect(await browser.hasElementByCssSelector('#modal')).toBe(false) // But the drawer should still be open expect(await browser.hasElementByCssSelector('#drawer')).toBe(true) // And the drawer should have a new time expect(await browser.elementById('drawer-now').text()).not.toEqual( currentDrawerTime ) // And the underlying page should have a new time expect(await browser.elementById('page-now').text()).not.toEqual( currentPageTime ) }) }) it('should not trigger a refresh for the page that is being redirected to', async () => { const rscRequests = [] const prefetchRequests = [] const browser = await next.browser('/redirect', { beforePageLoad(page) { page.on('request', async (req) => { const headers = await req.allHeaders() if (headers['rsc']) { const pathname = new URL(req.url()).pathname if (headers['next-router-prefetch']) { prefetchRequests.push(pathname) } else { rscRequests.push(pathname) } } }) }, }) await browser.elementByCss('button').click() await browser.waitForElementByCss('#root-page') await browser.waitForIdleNetwork() await retry(async () => { expect(rscRequests.length).toBe(0) if (isNextStart) { expect(prefetchRequests.length).toBe(4) } }) }) }) }) ```
/content/code_sandbox/test/e2e/app-dir/parallel-routes-revalidation/parallel-routes-revalidation.test.ts
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
3,507
```xml export const saveColor = 'var(--green11)'; export const primaryColor = 'var(--cyan9)'; export const primaryTextColor = 'var(--cyan11)'; export const waveformColorLight = '#000000'; // Must be hex because used by ffmpeg export const waveformColorDark = '#ffffff'; // Must be hex because used by ffmpeg export const controlsBackground = 'var(--gray4)'; export const timelineBackground = 'var(--gray2)'; export const darkModeTransition = 'background .5s'; ```
/content/code_sandbox/src/renderer/src/colors.ts
xml
2016-10-30T10:49:56
2024-08-16T19:12:59
lossless-cut
mifi/lossless-cut
25,459
105
```xml <vector xmlns:android="path_to_url" xmlns:tools="path_to_url" android:width="640dp" android:height="512dp" android:viewportWidth="640.0" android:viewportHeight="512.0" tools:keep="@drawable/fa_mixcloud"> <path android:fillColor="#FFFFFFFF" android:pathData="M424.4,219.7C416.1,134.7 344.1,68 256.9,68c-72.3,0 -136.2,46.5 -159.2,114.1 -54.5,8 -96.6,54.8 -96.6,111.6 0,62.3 50.7,113 113.2,113h289.6c52.3,0 95,-42.4 95,-94.7 0,-45.1 -32.1,-83.1 -74.5,-92.2zM403.9,364.3L114.3,364.3c-39,0 -70.9,-31.6 -70.9,-70.6s31.8,-70.6 70.9,-70.6c18.8,0 36.5,7.5 49.8,20.8 20,20 50.1,-10.2 30.2,-30.2 -14.7,-14.4 -32.7,-24.4 -52.1,-29.3 19.9,-44.3 64.8,-73.9 114.6,-73.9 69.5,0 126,56.5 126,125.7 0,13.6 -2.2,26.9 -6.4,39.6 -8.9,27.5 32.1,38.9 40.1,13.3 2.8,-8.3 5,-16.9 6.4,-25.5 19.4,7.5 33.5,26.3 33.5,48.5 0,28.8 -23.5,52.3 -52.6,52.3zM639,311.9c0,44 -12.7,86.4 -37.1,122.7 -4.2,6.1 -10.8,9.4 -17.7,9.4 -16.3,0 -27.1,-18.8 -17.4,-32.9 19.4,-29.3 29.9,-63.7 29.9,-99.1s-10.5,-69.8 -29.9,-98.8c-15.7,-22.8 19.4,-47.2 35.2,-23.5 24.4,36 37.1,78.4 37.1,122.4zM568.1,311.9c0,31.6 -9.1,62 -26.9,88.3 -4.2,6.1 -10.8,9.1 -17.7,9.1 -17.2,0 -27,-19 -17.4,-32.9 13,-19.1 19.7,-41.3 19.7,-64.5 0,-23 -6.6,-45.4 -19.7,-64.5 -15.8,-23 19,-47.1 35.2,-23.5 17.7,26 26.9,56.5 26.9,88z"/> </vector> ```
/content/code_sandbox/mobile/src/main/res/drawable/fa_mixcloud.xml
xml
2016-10-24T13:23:25
2024-08-16T07:20:37
freeotp-android
freeotp/freeotp-android
1,387
809
```xml import { BrowserWindowNotifier } from "@Core/BrowserWindowNotifier"; import type { SearchResultItem } from "@common/Core"; import { describe, expect, it, vi } from "vitest"; import { InMemorySearchIndex } from "./InMemorySearchIndex"; describe(InMemorySearchIndex, () => { it("should return an empty list of search result items if the search index is empty", () => { const searchIndex = new InMemorySearchIndex(<BrowserWindowNotifier>{}); searchIndex.setIndex({}); expect(searchIndex.getSearchResultItems()).toEqual([]); }); it("should return all search result items if the search index is not empty", () => { const searchResultItems: SearchResultItem[] = [ <SearchResultItem>{ description: "item1", id: "item1", name: "item1" }, <SearchResultItem>{ description: "item2", id: "item2", name: "item2" }, <SearchResultItem>{ description: "item3", id: "item3", name: "item3" }, ]; const searchIndex = new InMemorySearchIndex(<BrowserWindowNotifier>{}); searchIndex.setIndex({ testExtensionId: searchResultItems }); expect(searchIndex.getSearchResultItems()).toEqual(searchResultItems); }); it("should add search result items to the index with the extension id as a key and emit an event", () => { const notifyMock = vi.fn(); const eventEmitter = <BrowserWindowNotifier>{ notify: (c) => notifyMock(c) }; const searchResultItems: SearchResultItem[] = [ <SearchResultItem>{ description: "item1", id: "item1", name: "item1" }, <SearchResultItem>{ description: "item2", id: "item2", name: "item2" }, <SearchResultItem>{ description: "item3", id: "item3", name: "item3" }, ]; const searchIndex = new InMemorySearchIndex(eventEmitter); searchIndex.addSearchResultItems("extensionId1", searchResultItems); expect(searchIndex.getIndex()).toEqual({ extensionId1: searchResultItems }); expect(notifyMock).toHaveBeenCalledWith("searchIndexUpdated"); }); it("should delete the key from the index and emit an event when removing search result items by extension id", () => { const notifyMock = vi.fn(); const eventEmitter = <BrowserWindowNotifier>{ notify: (c) => notifyMock(c) }; const searchIndex = new InMemorySearchIndex(eventEmitter); searchIndex.setIndex({ extensionId1: [ <SearchResultItem>{ description: "item1", id: "item1", name: "item1" }, <SearchResultItem>{ description: "item2", id: "item2", name: "item2" }, <SearchResultItem>{ description: "item3", id: "item3", name: "item3" }, ], }); searchIndex.removeSearchResultItems("extensionId1"); expect(searchIndex.getIndex()).toEqual({}); expect(notifyMock).toHaveBeenCalledWith("searchIndexUpdated"); }); }); ```
/content/code_sandbox/src/main/Core/SearchIndex/InMemorySearchIndex.test.ts
xml
2016-10-11T04:59:52
2024-08-16T11:53:31
ueli
oliverschwendener/ueli
3,543
672
```xml import { getMetadataArgsStorage } from "../../globals" import { ColumnMetadataArgs } from "../../metadata-args/ColumnMetadataArgs" /** * Creates a "level"/"length" column to the table that holds a closure table. */ export function TreeLevelColumn(): PropertyDecorator { return function (object: Object, propertyName: string) { getMetadataArgsStorage().columns.push({ target: object.constructor, propertyName: propertyName, mode: "treeLevel", options: {}, } as ColumnMetadataArgs) } } ```
/content/code_sandbox/src/decorator/tree/TreeLevelColumn.ts
xml
2016-02-29T07:41:14
2024-08-16T18:28:52
typeorm
typeorm/typeorm
33,875
112
```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> <parent> <groupId>ai.clipper</groupId> <artifactId>clipper-parent</artifactId> <version>0.1</version> </parent> <artifactId>clipper-examples</artifactId> <name>${project.artifactId}</name> <packaging>jar</packaging> <!--<properties>--> <!--<spark.driver.memory>2g</spark.driver.memory>--> <!--</properties>--> <dependencies> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-core_${scala.binary.version}</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-mllib_${scala.binary.version}</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.json4s</groupId> <artifactId>json4s-jackson_${scala.compat.version}</artifactId> </dependency> <!-- <dependency> --> <!-- <groupId>org.apache.xbean</groupId> --> <!-- <artifactId>xbean&#45;asm5&#45;shaded</artifactId> --> <!-- </dependency> --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> <!-- <dependency> --> <!-- <groupId>org.ow2.asm</groupId> --> <!-- <artifactId>asm</artifactId> --> <!-- </dependency> --> <!-- <dependency> --> <!-- <groupId>org.apache.bcel</groupId> --> <!-- <artifactId>bcel</artifactId> --> <!-- </dependency> --> <dependency> <groupId>ai.clipper</groupId> <artifactId>clipper-container</artifactId> </dependency> <dependency> <groupId>ai.clipper</groupId> <artifactId>clipper-rpc</artifactId> </dependency> <dependency> <groupId>ai.clipper</groupId> <artifactId>clipper-spark</artifactId> </dependency> <dependency> <groupId>org.scalatest</groupId> <artifactId>scalatest_${scala.compat.version}</artifactId> </dependency> </dependencies> <build> <outputDirectory>target/scala-${scala.binary.version}/classes</outputDirectory> <testOutputDirectory>target/scala-${scala.binary.version}/test-classes</testOutputDirectory> <plugins> <plugin> <groupId>org.scalatest</groupId> <artifactId>scalatest-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <configuration> <!-- <relocations> --> <!-- <relocation> --> <!-- <pattern>org.eclipse.jetty</pattern> --> <!-- <shadedPattern>edu.berkeley.veloxms.jetty</shadedPattern> --> <!-- </relocation> --> <!-- </relocations> --> <createDependencyReducedPom>true</createDependencyReducedPom> <!-- <minimizeJar>true</minimizeJar> --> <!-- <promoteTransitiveDependencies>true</promoteTransitiveDependencies> --> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> </excludes> </filter> </filters> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> </transformer> <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"> <resource>reference.conf</resource> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> ```
/content/code_sandbox/containers/jvm/clipper-examples/pom.xml
xml
2016-10-27T17:30:27
2024-07-31T01:29:41
clipper
ucbrise/clipper
1,397
1,002
```xml import { render } from '@testing-library/react'; import Card from './Card'; describe('<Card />', () => { it('renders with a border and background by default', () => { const { container } = render(<Card>Lorem ipsum dolor sit amet consectetur adipisicing elit.</Card>); expect(container.firstChild).toHaveClass('border'); expect(container.firstChild).toHaveClass('bg-weak'); }); it('renders without a border and background if explicitly specified', () => { const { container } = render( <Card bordered={false} background={false}> Lorem ipsum dolor sit amet consectetur adipisicing elit. </Card> ); expect(container.firstChild).not.toHaveClass('border'); expect(container.firstChild).not.toHaveClass('bg-weak'); }); it('renders rounded', () => { const { container } = render(<Card rounded>Lorem ipsum dolor sit amet consectetur adipisicing elit.</Card>); expect(container.firstChild).toHaveClass('rounded'); }); }); ```
/content/code_sandbox/packages/atoms/Card/Card.test.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
208
```xml import getValue from '../../utils/getValue'; describe('getValue', () => { it('should return props.value if it exists', () => { const actual = getValue({ value: 1 }, 0); expect(actual).toEqual(1); }); it('should return props.defaultValue if it exists', () => { const actual = getValue({ defaultValue: 1 }, 0); expect(actual).toEqual(1); }); it("should return default value if props.value and props.defaultValue don't exist", () => { const actual = getValue({}, 1); expect(actual).toEqual(1); }); it('should return default value if props.defaultValue is 0', () => { const actual = getValue({ defaultValue: 0 }, 1); expect(actual).toEqual(1); }); }); ```
/content/code_sandbox/packages/zarm/src/slider/__tests__/utils/getValue.test.ts
xml
2016-07-13T11:45:37
2024-08-12T19:23:48
zarm
ZhongAnTech/zarm
1,707
173
```xml <?xml version="1.0" encoding="UTF-8" ?> <ContentPage xmlns="path_to_url" xmlns:x="path_to_url" x:Class="Xamarin.Forms.Xaml.UnitTests.ResourceLoader"> <ContentPage.Resources> <ResourceDictionary Source="AppResources/Colors.xaml" /> </ContentPage.Resources> <Label x:Name="label" TextColor="{StaticResource GreenColor}"/> </ContentPage> ```
/content/code_sandbox/Xamarin.Forms.Xaml.UnitTests/ResourceLoader.xaml
xml
2016-03-18T15:52:03
2024-08-16T16:25:43
Xamarin.Forms
xamarin/Xamarin.Forms
5,637
96
```xml import * as React from 'react'; import { cloneElement, createElement, isValidElement, useCallback, useRef, useEffect, FC, ComponentType, ReactElement, useMemo, } from 'react'; import { sanitizeListRestProps, useListContextWithProps, Identifier, OptionalResourceContextProvider, RaRecord, SortPayload, } from 'ra-core'; import { Table, TableProps, SxProps } from '@mui/material'; import clsx from 'clsx'; import union from 'lodash/union'; import difference from 'lodash/difference'; import { DatagridHeader } from './DatagridHeader'; import DatagridLoading from './DatagridLoading'; import DatagridBody, { PureDatagridBody } from './DatagridBody'; import { RowClickFunction } from './DatagridRow'; import DatagridContextProvider from './DatagridContextProvider'; import { DatagridClasses, DatagridRoot } from './useDatagridStyles'; import { BulkActionsToolbar } from '../BulkActionsToolbar'; import { BulkDeleteButton } from '../../button'; import { ListNoResults } from '../ListNoResults'; const defaultBulkActionButtons = <BulkDeleteButton />; /** * The Datagrid component renders a list of records as a table. * It is usually used as a child of the <List> and <ReferenceManyField> components. * * Props: * - body * - bulkActionButtons * - children * - empty * - expand * - header * - hover * - isRowExpandable * - isRowSelectable * - optimized * - rowClick * - rowSx * - size * - sx * * @example // Display all posts as a datagrid * const postRowSx = (record, index) => ({ * backgroundColor: record.nb_views >= 500 ? '#efe' : 'white', * }); * export const PostList = () => ( * <List> * <Datagrid rowSx={postRowSx}> * <TextField source="id" /> * <TextField source="title" /> * <TextField source="body" /> * <EditButton /> * </Datagrid> * </List> * ); * * @example // Display all the comments of the current post as a datagrid * <ReferenceManyField reference="comments" target="post_id"> * <Datagrid> * <TextField source="id" /> * <TextField source="body" /> * <DateField source="created_at" /> * <EditButton /> * </Datagrid> * </ReferenceManyField> * * @example // Usage outside of a <List> or a <ReferenceManyField>. * * const sort = { field: 'published_at', order: 'DESC' }; * * export const MyCustomList = (props) => { * const { data, total, isPending } = useGetList( * 'posts', * { pagination: { page: 1, perPage: 10 }, sort: sort } * ); * * return ( * <Datagrid * data={data} * total={total} * isPending={isPending} * sort={sort} * selectedIds={[]} * setSort={() => { * console.log('set sort'); * }} * onSelect={() => { * console.log('on select'); * }} * onToggleItem={() => { * console.log('on toggle item'); * }} * > * <TextField source="id" /> * <TextField source="title" /> * </Datagrid> * ); * } */ export const Datagrid: React.ForwardRefExoticComponent< Omit<DatagridProps, 'ref'> & React.RefAttributes<HTMLTableElement> > = React.forwardRef<HTMLTableElement, DatagridProps>((props, ref) => { const { optimized = false, body = optimized ? PureDatagridBody : DatagridBody, header = DatagridHeader, children, className, empty = DefaultEmpty, expand, bulkActionButtons = defaultBulkActionButtons, hover, isRowSelectable, isRowExpandable, resource, rowClick, rowSx, rowStyle, size = 'small', sx, expandSingle = false, ...rest } = props; const { sort, data, isPending, onSelect, onToggleItem, selectedIds, setSort, total, } = useListContextWithProps(props); const hasBulkActions = !!bulkActionButtons !== false; const contextValue = useMemo( () => ({ isRowExpandable, expandSingle }), [isRowExpandable, expandSingle] ); const lastSelected = useRef(null); useEffect(() => { if (!selectedIds || selectedIds.length === 0) { lastSelected.current = null; } }, [JSON.stringify(selectedIds)]); // eslint-disable-line react-hooks/exhaustive-deps // we manage row selection at the datagrid level to allow shift+click to select an array of rows const handleToggleItem = useCallback( (id, event) => { if (!data) return; const ids = data.map(record => record.id); const lastSelectedIndex = ids.indexOf(lastSelected.current); lastSelected.current = event.target.checked ? id : null; if (event.shiftKey && lastSelectedIndex !== -1) { const index = ids.indexOf(id); const idsBetweenSelections = ids.slice( Math.min(lastSelectedIndex, index), Math.max(lastSelectedIndex, index) + 1 ); const newSelectedIds = event.target.checked ? union(selectedIds, idsBetweenSelections) : difference(selectedIds, idsBetweenSelections); onSelect?.( isRowSelectable ? newSelectedIds.filter((id: Identifier) => isRowSelectable( data.find(record => record.id === id) ) ) : newSelectedIds ); } else { onToggleItem?.(id); } }, [data, isRowSelectable, onSelect, onToggleItem, selectedIds] ); if (isPending === true) { return ( <DatagridLoading className={className} expand={expand} hasBulkActions={hasBulkActions} nbChildren={React.Children.count(children)} size={size} /> ); } /** * Once loaded, the data for the list may be empty. Instead of * displaying the table header with zero data rows, * the Datagrid displays the empty component. */ if (data == null || data.length === 0 || total === 0) { if (empty) { return empty; } return null; } /** * After the initial load, if the data for the list isn't empty, * and even if the data is refreshing (e.g. after a filter change), * the datagrid displays the current data. */ return ( <DatagridContextProvider value={contextValue}> <OptionalResourceContextProvider value={resource}> <DatagridRoot sx={sx} className={clsx(DatagridClasses.root, className)} > {bulkActionButtons !== false ? ( <BulkActionsToolbar> {isValidElement(bulkActionButtons) ? bulkActionButtons : defaultBulkActionButtons} </BulkActionsToolbar> ) : null} <div className={DatagridClasses.tableWrapper}> <Table ref={ref} className={DatagridClasses.table} size={size} {...sanitizeRestProps(rest)} > {createOrCloneElement( header, { children, sort, data, hasExpand: !!expand, hasBulkActions, isRowSelectable, onSelect, selectedIds, setSort, }, children )} {createOrCloneElement( body, { expand, rowClick, data, hasBulkActions, hover, onToggleItem: handleToggleItem, resource, rowSx, rowStyle, selectedIds, isRowSelectable, }, children )} </Table> </div> </DatagridRoot> </OptionalResourceContextProvider> </DatagridContextProvider> ); }); const createOrCloneElement = (element, props, children) => isValidElement(element) ? cloneElement(element, props, children) : createElement(element, props, children); export interface DatagridProps<RecordType extends RaRecord = any> extends Omit<TableProps, 'size' | 'classes' | 'onSelect'> { /** * The component used to render the body of the table. Defaults to <DatagridBody>. * * @see path_to_url#body */ body?: ReactElement | ComponentType; /** * A class name to apply to the root table element */ className?: string; /** * The component used to render the bulk action buttons. Defaults to <BulkDeleteButton>. * * @see path_to_url#bulkactionbuttons * @example * import { List, Datagrid, BulkDeleteButton } from 'react-admin'; * import { Button } from '@mui/material'; * import ResetViewsButton from './ResetViewsButton'; * * const PostBulkActionButtons = () => ( * <> * <ResetViewsButton label="Reset Views" /> * <BulkDeleteButton /> * </> * ); * * export const PostList = () => ( * <List> * <Datagrid bulkActionButtons={<PostBulkActionButtons />}> * ... * </Datagrid> * </List> * ); */ bulkActionButtons?: ReactElement | false; /** * The component used to render the expand panel for each row. * * @see path_to_url#expand * @example * import { List, Datagrid, useRecordContext } from 'react-admin'; * * const PostPanel = () => { * const record = useRecordContext(); * return ( * <div dangerouslySetInnerHTML={{ __html: record.body }} /> * ); * }; * * const PostList = () => ( * <List> * <Datagrid expand={<PostPanel />}> * ... * </Datagrid> * </List> * ) */ expand?: | ReactElement | FC<{ id: Identifier; record: RecordType; resource: string; }>; /** * The component used to render the header row. Defaults to <DatagridHeader>. * * @see path_to_url#header */ header?: ReactElement | ComponentType; /** * Whether to allow only one expanded row at a time. Defaults to false. * * @see path_to_url#expandsingle * @example * import { List, Datagrid } from 'react-admin'; * * export const PostList = () => ( * <List> * <Datagrid expandSingle> * ... * </Datagrid> * </List> * ); */ expandSingle?: boolean; /** * Set to false to disable the hover effect on rows. * * @see path_to_url#hover * @example * import { List, Datagrid } from 'react-admin'; * * const PostList = () => ( * <List> * <Datagrid hover={false}> * ... * </Datagrid> * </List> * ); */ hover?: boolean; /** * The component used to render the empty table. * * @see path_to_url#empty * @example * import { List, Datagrid } from 'react-admin'; * * const CustomEmpty = () => <div>No books found</div>; * * const PostList = () => ( * <List> * <Datagrid empty={<CustomEmpty />}> * ... * </Datagrid> * </List> * ); */ empty?: ReactElement; /** * A function that returns whether the row for a record is expandable. * * @see path_to_url#isrowexpandable * @example * import { List, Datagrid, useRecordContext } from 'react-admin'; * * const PostPanel = () => { * const record = useRecordContext(); * return ( * <div dangerouslySetInnerHTML={{ __html: record.body }} /> * ); * }; * * const PostList = () => ( * <List> * <Datagrid * expand={<PostPanel />} * isRowExpandable={row => row.has_detail} * > * ... * </Datagrid> * </List> * ) */ isRowExpandable?: (record: RecordType) => boolean; /** * A function that returns whether the row for a record is selectable. * * @see path_to_url#isrowselectable * @example * import { List, Datagrid } from 'react-admin'; * * export const PostList = () => ( * <List> * <Datagrid isRowSelectable={ record => record.id > 300 }> * ... * </Datagrid> * </List> * ); */ isRowSelectable?: (record: RecordType) => boolean; /** * Set to true to optimize datagrid rendering if the children never vary. * * @see path_to_url#optimized */ optimized?: boolean; /** * The action to trigger when the user clicks on a row. * * @see path_to_url#rowclick * @example * import { List, Datagrid } from 'react-admin'; * * export const PostList = () => ( * <List> * <Datagrid rowClick="edit"> * ... * </Datagrid> * </List> * ); */ rowClick?: string | RowClickFunction | false; /** * A function that returns the sx prop to apply to a row. * * @see path_to_url#rowsx * @example * import { List, Datagrid } from 'react-admin'; * * const postRowSx = (record, index) => ({ * backgroundColor: record.nb_views >= 500 ? '#efe' : 'white', * }); * export const PostList = () => ( * <List> * <Datagrid rowSx={postRowSx}> * ... * </Datagrid> * </List> * ); */ rowSx?: (record: RecordType, index: number) => SxProps; /** * @deprecated use rowSx instead */ rowStyle?: (record: RecordType, index: number) => any; /** * Density setting, can be either 'small' or 'medium'. Defaults to 'small'. * * @see path_to_url#size * @example * import { List, Datagrid } from 'react-admin'; * * export const PostList = () => ( * <List> * <Datagrid size="medium"> * ... * </Datagrid> * </List> * ); */ size?: 'medium' | 'small'; // can be injected when using the component without context sort?: SortPayload; data?: RecordType[]; isLoading?: boolean; isPending?: boolean; onSelect?: (ids: Identifier[]) => void; onToggleItem?: (id: Identifier) => void; setSort?: (sort: SortPayload) => void; selectedIds?: Identifier[]; total?: number; } const injectedProps = [ 'isRequired', 'setFilter', 'setPagination', 'limitChoicesToValue', 'translateChoice', // Datagrid may be used as an alternative to SelectInput 'field', 'fieldState', 'formState', ]; const sanitizeRestProps = props => Object.keys(sanitizeListRestProps(props)) .filter( propName => !injectedProps.includes(propName) || propName === 'ref' ) .reduce((acc, key) => ({ ...acc, [key]: props[key] }), {}); Datagrid.displayName = 'Datagrid'; const DefaultEmpty = <ListNoResults />; ```
/content/code_sandbox/packages/ra-ui-materialui/src/list/datagrid/Datagrid.tsx
xml
2016-07-13T07:58:54
2024-08-16T18:32:27
react-admin
marmelab/react-admin
24,624
3,716
```xml import { EncString } from "../../platform/models/domain/enc-string"; import { FieldType, LinkedIdType } from "../../vault/enums"; import { Field as FieldDomain } from "../../vault/models/domain/field"; import { FieldView } from "../../vault/models/view/field.view"; import { safeGetString } from "./utils"; export class FieldExport { static template(): FieldExport { const req = new FieldExport(); req.name = "Field name"; req.value = "Some value"; req.type = FieldType.Text; return req; } static toView(req: FieldExport, view = new FieldView()) { view.type = req.type; view.value = req.value; view.name = req.name; view.linkedId = req.linkedId; return view; } static toDomain(req: FieldExport, domain = new FieldDomain()) { domain.type = req.type; domain.value = req.value != null ? new EncString(req.value) : null; domain.name = req.name != null ? new EncString(req.name) : null; domain.linkedId = req.linkedId; return domain; } name: string; value: string; type: FieldType; linkedId: LinkedIdType; constructor(o?: FieldView | FieldDomain) { if (o == null) { return; } this.name = safeGetString(o.name); this.value = safeGetString(o.value); this.type = o.type; this.linkedId = o.linkedId; } } ```
/content/code_sandbox/libs/common/src/models/export/field.export.ts
xml
2016-03-09T23:14:01
2024-08-16T15:07:51
clients
bitwarden/clients
8,877
332
```xml <?xml version="1.0" encoding="utf-8"?> <!-- path_to_url Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <manifest package="com.yanzhenjie.recyclerview"/> ```
/content/code_sandbox/support/src/main/AndroidManifest.xml
xml
2016-08-03T15:43:34
2024-08-14T01:11:22
SwipeRecyclerView
yanzhenjie/SwipeRecyclerView
5,605
62
```xml export * from 'rxjs-compat/operator/window'; ```
/content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/operator/window.d.ts
xml
2016-09-05T10:18:44
2024-08-11T13:21:40
LiquidCore
LiquidPlayer/LiquidCore
1,010
11
```xml import { createServiceFactory, SpectatorService, SpyObject } from '@ngneat/spectator/jest'; import { LocalizationPipe } from '../pipes/localization.pipe'; import { LocalizationService } from '../services/localization.service'; describe('LocalizationPipe', () => { let spectator: SpectatorService<LocalizationPipe>; let pipe: LocalizationPipe; let localizationService: SpyObject<LocalizationService>; const createService = createServiceFactory({ service: LocalizationPipe, mocks: [LocalizationService], }); beforeEach(() => { spectator = createService(); pipe = spectator.inject(LocalizationPipe); localizationService = spectator.inject(LocalizationService); }); it('should call getLocalization selector', () => { const translateSpy = jest.spyOn(localizationService, 'instant'); pipe.transform('test', '1', '2'); pipe.transform('test2', ['3', '4'] as any); expect(translateSpy).toHaveBeenCalledWith('test', '1', '2'); expect(translateSpy).toHaveBeenCalledWith('test2', '3', '4'); }); }); ```
/content/code_sandbox/npm/ng-packs/packages/core/src/lib/tests/localization.pipe.spec.ts
xml
2016-12-03T22:56:24
2024-08-16T16:24:05
abp
abpframework/abp
12,657
233
```xml import * as React from 'react'; import { Image, IImageProps, ImageFit } from '@fluentui/react/lib/Image'; // These props are defined up here so they can easily be applied to multiple Images. // Normally specifying them inline would be fine. const imageProps: IImageProps = { imageFit: ImageFit.cover, src: 'path_to_url // Show a border around the image (just for demonstration purposes) styles: props => ({ root: { border: '1px solid ' + props.theme.palette.neutralSecondary } }), }; export const ImageCoverExample = () => { return ( <div> <p> Setting the <code>imageFit</code> property to <code>ImageFit.cover</code> will cause the image to scale up or down proportionally, while cropping from either the top and bottom or sides to completely fill the frame. </p> <p> This image has a wider aspect ratio (more landscape) than the frame, so it's scaled to fit the height and the sides are cropped evenly. </p> <Image {...imageProps} alt='Example of the image fit value "cover" on an image wider than the frame.' width={150} height={250} /> <p> This image has a taller aspect ratio (more portrait) than the frame, so it's scaled to fit the width and the top and bottom are cropped evenly. </p> <Image {...imageProps} alt='Example of the image fit value "cover" on an image taller than the frame.' width={250} height={150} /> </div> ); }; ```
/content/code_sandbox/packages/react-examples/src/react/Image/Image.Cover.Example.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
369
```xml import { getRoutes } from '../getRoutes'; import { inMemoryContext } from '../testing-library/context-stubs'; const originalEnv = process.env.NODE_ENV; afterEach(() => { process.env.NODE_ENV = originalEnv; }); describe('getRoutes', () => { it(`should append a _layout, sitemap and +not-found`, () => { expect( getRoutes( inMemoryContext({ './(app)/index': () => null, }), { internal_stripLoadRoute: true } ) ).toEqual({ children: [ { type: 'route', children: [], contextKey: 'expo-router/build/views/Sitemap.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', 'expo-router/build/views/Sitemap.js', ], generated: true, internal: true, route: '_sitemap', }, { type: 'route', children: [], contextKey: 'expo-router/build/views/Unmatched.js', dynamic: [ { deep: true, name: '+not-found', notFound: true, }, ], entryPoints: [ 'expo-router/build/views/Navigator.js', 'expo-router/build/views/Unmatched.js', ], generated: true, internal: true, route: '+not-found', }, { type: 'route', children: [], contextKey: './(app)/index.js', dynamic: null, entryPoints: ['expo-router/build/views/Navigator.js', './(app)/index.js'], route: '(app)/index', }, ], contextKey: 'expo-router/build/views/Navigator.js', dynamic: null, generated: true, type: 'layout', route: '', }); }); it(`should not append a _layout if there already is a top level layout`, () => { expect( getRoutes( inMemoryContext({ './(app)/index': () => null, './_layout': () => null, }), { internal_stripLoadRoute: true } ) ).toEqual({ children: [ { type: 'route', children: [], contextKey: 'expo-router/build/views/Sitemap.js', dynamic: null, entryPoints: ['./_layout.js', 'expo-router/build/views/Sitemap.js'], generated: true, internal: true, route: '_sitemap', }, { type: 'route', children: [], contextKey: 'expo-router/build/views/Unmatched.js', dynamic: [ { deep: true, name: '+not-found', notFound: true, }, ], entryPoints: ['./_layout.js', 'expo-router/build/views/Unmatched.js'], generated: true, internal: true, route: '+not-found', }, { type: 'route', children: [], contextKey: './(app)/index.js', dynamic: null, entryPoints: ['./_layout.js', './(app)/index.js'], route: '(app)/index', }, ], contextKey: './_layout.js', dynamic: null, type: 'layout', route: '', }); }); it(`allows index routes be one level higher in the file-tree than their subroutes`, () => { expect( getRoutes( inMemoryContext({ './[a].tsx': () => null, // In v2 this would error and require moving to ./[a]/index.tsx './[a]/[b].tsx': () => null, // }), { internal_stripLoadRoute: true, skipGenerated: true } ) ).toEqual({ children: [ { children: [], contextKey: './[a].tsx', dynamic: [ { deep: false, name: 'a', }, ], entryPoints: ['expo-router/build/views/Navigator.js', './[a].tsx'], route: '[a]', type: 'route', }, { children: [], contextKey: './[a]/[b].tsx', dynamic: [ { deep: false, name: 'a', }, { deep: false, name: 'b', }, ], entryPoints: ['expo-router/build/views/Navigator.js', './[a]/[b].tsx'], route: '[a]/[b]', type: 'route', }, ], contextKey: 'expo-router/build/views/Navigator.js', dynamic: null, generated: true, route: '', type: 'layout', }); }); it(`will throw if a route ends in group syntax`, () => { expect(() => { getRoutes( inMemoryContext({ './folder/(b).tsx': () => null, }) ); }).toThrowErrorMatchingInlineSnapshot( `"Invalid route ./folder/(b).tsx. Routes cannot end with '(group)' syntax"` ); }); it(`should name routes relative to the closest _layout`, () => { expect( getRoutes( inMemoryContext({ './(b)/_layout': () => null, './(a,b)/page': () => null, // /(b)/page should have a different route name as it }), { internal_stripLoadRoute: true, skipGenerated: true } ) ).toEqual({ children: [ { contextKey: './(b)/_layout.js', type: 'layout', dynamic: null, route: '(b)', children: [ { type: 'route', contextKey: './(a,b)/page.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './(b)/_layout.js', './(a,b)/page.js', ], route: 'page', children: [], }, ], }, { type: 'route', contextKey: './(a,b)/page.js', dynamic: null, entryPoints: ['expo-router/build/views/Navigator.js', './(a,b)/page.js'], route: '(a)/page', children: [], }, ], contextKey: 'expo-router/build/views/Navigator.js', type: 'layout', dynamic: null, generated: true, route: '', }); }); }); describe('tutorial', () => { it(`will return null if there are no _layout or routes`, () => { expect(getRoutes(inMemoryContext({}))).toBeNull(); }); }); describe('duplicate routes', () => { it(`throws if there are duplicate routes`, () => { expect(() => { getRoutes( inMemoryContext({ 'a.js': () => null, 'a.tsx': () => null, }) ); }).toThrowErrorMatchingInlineSnapshot( `"The route files "./a.tsx" and "./a.js" conflict on the route "/a". Please remove or rename one of these files."` ); }); it(`doesn't throw if running in production`, () => { process.env.NODE_ENV = 'production'; expect(() => { getRoutes( inMemoryContext({ 'a.js': () => null, 'a.tsx': () => null, }) ); }).not.toThrow(); }); it(`will not throw if the routes are in separate groups`, () => { expect(() => { getRoutes( inMemoryContext({ './(a)/c': () => null, './(b)/c': () => null, }) ); }).not.toThrow(); }); it(`throws if there are duplicate nested routes`, () => { expect(() => { getRoutes( inMemoryContext({ 'a.js': () => null, './test/folder/b.tsx': () => null, './test/folder/b.js': () => null, }) ); }).toThrowErrorMatchingInlineSnapshot( `"The route files "./test/folder/b.js" and "./test/folder/b.tsx" conflict on the route "/test/folder/b". Please remove or rename one of these files."` ); }); it(`doesn't throw if similarly named routes are in different groupings`, () => { expect(() => { getRoutes( inMemoryContext({ './(a)/b.tsx': () => null, './(a,b)/b.tsx': () => null, }) ); }).toThrowErrorMatchingInlineSnapshot( `"The route files "./(a,b)/b.tsx" and "./(a)/b.tsx" conflict on the route "/(a)/b". Please remove or rename one of these files."` ); }); it(`will not throw of the groupings are present at different levels`, () => { expect(() => { getRoutes( inMemoryContext({ './(a)/test/c': () => null, './test/(a)/c': () => null, }) ); }).not.toThrow(); }); }); describe('+html', () => { it(`should ignore top-level +html files`, () => { expect( getRoutes( inMemoryContext({ './+html': () => null, }), { internal_stripLoadRoute: true } ) ).toEqual(null); }); it(`errors if there are nested +html routes`, () => { expect(() => { getRoutes( inMemoryContext({ './folder/+html': () => null, }), { internal_stripLoadRoute: true, skipGenerated: true } ); }).toThrowErrorMatchingInlineSnapshot( `"Invalid route ./folder/+html.js. Route nodes cannot start with the '+' character. "Please rename to folder/html.js""` ); }); }); describe('+not-found', () => { it(`should not append a +not-found if there already is a top level +not+found`, () => { expect( getRoutes( inMemoryContext({ './(app)/index': () => null, './+not-found': () => null, }), { internal_stripLoadRoute: true } ) ).toEqual({ children: [ { children: [], type: 'route', contextKey: './+not-found.js', dynamic: [ { deep: true, name: '+not-found', notFound: true, }, ], entryPoints: ['expo-router/build/views/Navigator.js', './+not-found.js'], route: '+not-found', }, { children: [], type: 'route', contextKey: 'expo-router/build/views/Sitemap.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', 'expo-router/build/views/Sitemap.js', ], generated: true, internal: true, route: '_sitemap', }, { children: [], type: 'route', contextKey: './(app)/index.js', dynamic: null, entryPoints: ['expo-router/build/views/Navigator.js', './(app)/index.js'], route: '(app)/index', }, ], contextKey: 'expo-router/build/views/Navigator.js', type: 'layout', dynamic: null, generated: true, route: '', }); }); it(`should not match top-level deep dynamic with nested index`, () => { let routes = getRoutes( inMemoryContext({ './(group)/+not-found/(group)/index.tsx': () => null, './+not-found/index.tsx': () => null, './+not-found/(group)/index.tsx': () => null, './(group1)/+not-found/(group2)/index.tsx': () => null, './(group1)/+not-found/(group2)/(group3)/index.tsx': () => null, }), { internal_stripLoadRoute: true } ); expect(routes).not.toBeNull(); routes = routes!; const notFound = routes.children.find((route) => route.route === '+not-found')!; // Ensure this is the generated +not-found expect(notFound.generated).toBeTruthy(); expect(notFound.internal).toBeTruthy(); expect(notFound.entryPoints).toContain('expo-router/build/views/Unmatched.js'); }); }); describe('entry points', () => { it('should allow skipping entry point logic', () => { expect( getRoutes( inMemoryContext({ './(app)/index': () => null, }), { internal_stripLoadRoute: true, ignoreEntryPoints: true } ) ).toEqual({ children: [ { children: [], type: 'route', contextKey: 'expo-router/build/views/Sitemap.js', dynamic: null, generated: true, internal: true, route: '_sitemap', }, { children: [], type: 'route', contextKey: 'expo-router/build/views/Unmatched.js', dynamic: [ { deep: true, name: '+not-found', notFound: true, }, ], generated: true, internal: true, route: '+not-found', }, { children: [], type: 'route', contextKey: './(app)/index.js', dynamic: null, route: '(app)/index', }, ], contextKey: 'expo-router/build/views/Navigator.js', type: 'layout', dynamic: null, generated: true, route: '', }); }); it(`should append entry points for all parent _layouts`, () => { expect( getRoutes( inMemoryContext({ './a/_layout': () => null, './a/b/_layout': () => null, './a/b/(c,d)/_layout': () => null, './a/b/(c,d)/e': () => null, }), { internal_stripLoadRoute: true, skipGenerated: true } ) ).toEqual({ contextKey: 'expo-router/build/views/Navigator.js', type: 'layout', dynamic: null, generated: true, route: '', children: [ { contextKey: './a/_layout.js', type: 'layout', dynamic: null, route: 'a', children: [ { contextKey: './a/b/_layout.js', type: 'layout', dynamic: null, route: 'b', children: [ { contextKey: './a/b/(c,d)/_layout.js', type: 'layout', dynamic: null, route: '(c)', children: [ { children: [], type: 'route', contextKey: './a/b/(c,d)/e.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './a/_layout.js', './a/b/_layout.js', './a/b/(c,d)/_layout.js', './a/b/(c,d)/e.js', ], route: 'e', }, ], }, { contextKey: './a/b/(c,d)/_layout.js', type: 'layout', dynamic: null, route: '(d)', children: [ { children: [], type: 'route', contextKey: './a/b/(c,d)/e.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './a/_layout.js', './a/b/_layout.js', './a/b/(c,d)/_layout.js', './a/b/(c,d)/e.js', ], route: 'e', }, ], }, ], }, ], }, ], }); }); }); describe('initialRouteName', () => { it(`should append entry points for all parent _layouts`, () => { expect( getRoutes( inMemoryContext({ _layout: { unstable_settings: { initialRouteName: 'a', }, default: () => null, }, a: () => null, b: () => null, }), { skipGenerated: true } ) ).toEqual({ children: [ { children: [], contextKey: './a.js', dynamic: null, entryPoints: ['./_layout.js', './a.js'], route: 'a', type: 'route', loadRoute: expect.any(Function), }, { children: [], contextKey: './b.js', dynamic: null, entryPoints: ['./_layout.js', './a.js', './b.js'], route: 'b', type: 'route', loadRoute: expect.any(Function), }, ], loadRoute: expect.any(Function), contextKey: './_layout.js', dynamic: null, initialRouteName: 'a', route: '', type: 'layout', }); }); it(`throws if initialRouteName does not match a route`, () => { expect(() => { getRoutes( inMemoryContext({ _layout: { unstable_settings: { initialRouteName: 'c', }, default: () => null, }, a: () => null, b: () => null, }) ); }).toThrowErrorMatchingInlineSnapshot( `"Layout ./_layout.js has invalid initialRouteName 'c'. Valid options are: 'a', 'b'"` ); }); it(`throws if initialRouteName with group selection does not match a route`, () => { expect(() => { getRoutes( inMemoryContext({ '(a,b)/_layout': { unstable_settings: { a: { initialRouteName: 'c', }, b: { initialRouteName: 'd', }, }, default: () => null, }, '(a,b)/c': () => null, }) ); }).toThrowErrorMatchingInlineSnapshot( `"Layout ./(a,b)/_layout.js has invalid initialRouteName 'd' for group '(b)'. Valid options are: 'c'"` ); }); }); describe('dynamic routes', () => { it('parses dynamic routes', () => { expect( getRoutes( inMemoryContext({ './[single]': () => null, './a/b/c/[single]': () => null, './[...catchAll]': () => null, }), { internal_stripLoadRoute: true, skipGenerated: true } ) ).toEqual({ children: [ { children: [], type: 'route', contextKey: './[single].js', dynamic: [ { deep: false, name: 'single', }, ], entryPoints: ['expo-router/build/views/Navigator.js', './[single].js'], route: '[single]', }, { children: [], type: 'route', contextKey: './[...catchAll].js', dynamic: [ { deep: true, name: 'catchAll', }, ], entryPoints: ['expo-router/build/views/Navigator.js', './[...catchAll].js'], route: '[...catchAll]', }, { children: [], type: 'route', contextKey: './a/b/c/[single].js', dynamic: [ { deep: false, name: 'single', }, ], entryPoints: ['expo-router/build/views/Navigator.js', './a/b/c/[single].js'], route: 'a/b/c/[single]', }, ], contextKey: 'expo-router/build/views/Navigator.js', type: 'layout', dynamic: null, generated: true, route: '', }); }); }); describe('api routes', () => { it('should ignore api routes by default', () => { expect( getRoutes( inMemoryContext({ './(app)/page': () => null, './(app)/page+api': () => null, }), { internal_stripLoadRoute: true, skipGenerated: true } ) ).toEqual({ children: [ { type: 'route', children: [], contextKey: './(app)/page.js', dynamic: null, entryPoints: ['expo-router/build/views/Navigator.js', './(app)/page.js'], route: '(app)/page', }, ], type: 'layout', contextKey: 'expo-router/build/views/Navigator.js', dynamic: null, generated: true, route: '', }); }); it('should include api routes is preserveApiRoutes is enabled', () => { expect( getRoutes( inMemoryContext({ './(app)/page': () => null, './(app)/page+api': () => null, }), { internal_stripLoadRoute: true, skipGenerated: true, preserveApiRoutes: true } ) ).toEqual({ children: [ { type: 'route', children: [], contextKey: './(app)/page.js', dynamic: null, entryPoints: ['expo-router/build/views/Navigator.js', './(app)/page.js'], route: '(app)/page', }, { type: 'api', children: [], contextKey: './(app)/page+api.js', dynamic: null, route: '(app)/page', }, ], type: 'layout', contextKey: 'expo-router/build/views/Navigator.js', dynamic: null, generated: true, route: '', }); }); }); it('ignores API routes with platform extensions', () => { expect(() => { getRoutes( inMemoryContext({ './folder/one.tsx': () => null, './folder/two+api.web.tsx': () => null, }), { internal_stripLoadRoute: true, platform: 'web', skipGenerated: true, preserveApiRoutes: true, } ); }).toThrowErrorMatchingInlineSnapshot( `"Api routes cannot have platform extensions. Please remove '.web' from './folder/two+api.web.tsx'"` ); }); describe('group expansion', () => { it(`array syntax`, () => { expect( getRoutes( inMemoryContext({ './(single)/directory/(a,b)/mixed': () => null, }), { internal_stripLoadRoute: true, skipGenerated: true } ) ).toEqual({ children: [ { children: [], contextKey: './(single)/directory/(a,b)/mixed.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './(single)/directory/(a,b)/mixed.js', ], route: '(single)/directory/(a)/mixed', type: 'route', }, { children: [], contextKey: './(single)/directory/(a,b)/mixed.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './(single)/directory/(a,b)/mixed.js', ], route: '(single)/directory/(b)/mixed', type: 'route', }, ], contextKey: 'expo-router/build/views/Navigator.js', dynamic: null, generated: true, route: '', type: 'layout', }); }); it(`multiple arrays`, () => { expect( getRoutes( inMemoryContext({ './(a,b)/(c,d)/multiple-arrays': () => null, }), { internal_stripLoadRoute: true, skipGenerated: true } ) ).toEqual({ children: [ { children: [], contextKey: './(a,b)/(c,d)/multiple-arrays.js', dynamic: null, entryPoints: ['expo-router/build/views/Navigator.js', './(a,b)/(c,d)/multiple-arrays.js'], route: '(a)/(c)/multiple-arrays', type: 'route', }, { children: [], contextKey: './(a,b)/(c,d)/multiple-arrays.js', dynamic: null, entryPoints: ['expo-router/build/views/Navigator.js', './(a,b)/(c,d)/multiple-arrays.js'], route: '(a)/(d)/multiple-arrays', type: 'route', }, { children: [], contextKey: './(a,b)/(c,d)/multiple-arrays.js', dynamic: null, entryPoints: ['expo-router/build/views/Navigator.js', './(a,b)/(c,d)/multiple-arrays.js'], route: '(b)/(c)/multiple-arrays', type: 'route', }, { children: [], contextKey: './(a,b)/(c,d)/multiple-arrays.js', dynamic: null, entryPoints: ['expo-router/build/views/Navigator.js', './(a,b)/(c,d)/multiple-arrays.js'], route: '(b)/(d)/multiple-arrays', type: 'route', }, ], contextKey: 'expo-router/build/views/Navigator.js', dynamic: null, generated: true, route: '', type: 'layout', }); }); it(`multiple arrays with brackets`, () => { expect( getRoutes( inMemoryContext({ './(a,b)/((c),d,(e))/multiple-arrays-with-brackets': () => null, }), { internal_stripLoadRoute: true, skipGenerated: true } ) ).toEqual({ children: [ { children: [], contextKey: './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', ], route: '(a)/((c))/multiple-arrays-with-brackets', type: 'route', }, { children: [], contextKey: './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', ], route: '(a)/(d)/multiple-arrays-with-brackets', type: 'route', }, { children: [], contextKey: './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', ], route: '(a)/((e))/multiple-arrays-with-brackets', type: 'route', }, { children: [], contextKey: './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', ], route: '(b)/((c))/multiple-arrays-with-brackets', type: 'route', }, { children: [], contextKey: './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', ], route: '(b)/(d)/multiple-arrays-with-brackets', type: 'route', }, { children: [], contextKey: './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', dynamic: null, entryPoints: [ 'expo-router/build/views/Navigator.js', './(a,b)/((c),d,(e))/multiple-arrays-with-brackets.js', ], route: '(b)/((e))/multiple-arrays-with-brackets', type: 'route', }, ], contextKey: 'expo-router/build/views/Navigator.js', dynamic: null, generated: true, route: '', type: 'layout', }); }); }); ```
/content/code_sandbox/packages/expo-router/src/__tests__/getRoutes.test.ios.ts
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
6,222
```xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="launcher_background">#FFFFFF</color> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> </resources> ```
/content/code_sandbox/pjsip-apps/src/swig/csharp/pjsua2xamarin/pjsua2xamarin.Android/Resources/values/colors.xml
xml
2016-01-24T05:00:33
2024-08-16T03:31:21
pjproject
pjsip/pjproject
1,960
79
```xml interface Filters { /* dangling=<boolean> When set to true (or 1), returns all networks that are not in use by a container. When set to false (or 0), only networks that are in use by one or more containers are returned. */ dangling?: [boolean]; // Matches a network's driver driver?: string[]; // Matches all or part of a network ID id?: string[]; // `label=<key>` or `label=<key>=<value>` of a network label. label?: string[]; // Matches all or part of a network name. name?: string[]; // Filters networks by scope (swarm, global, or local). scope?: ('swarm' | 'global' | 'local')[]; // Filters networks by type. The custom keyword returns all user-defined networks. type?: ('custom' | 'builtin')[]; } export interface NetworksQuery { local?: boolean; swarm?: boolean; swarmAttachable?: boolean; filters?: Filters; } ```
/content/code_sandbox/app/react/docker/networks/queries/types.ts
xml
2016-05-19T20:15:28
2024-08-16T19:15:14
portainer
portainer/portainer
30,083
220
```xml <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="path_to_url" xmlns:x="path_to_url" x:Class="Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries.EmptyViewGalleries.EmptyViewTemplateGallery"> <ContentPage.Content> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <SearchBar x:Name="SearchBar" Placeholder="Filter" /> <CollectionView x:Name="CollectionView" Grid.Row="1"> <CollectionView.ItemsLayout> <GridItemsLayout Span="3" Orientation="Vertical"></GridItemsLayout> </CollectionView.ItemsLayout> <CollectionView.EmptyViewTemplate> <DataTemplate> <StackLayout> <Label FontAttributes="Bold" FontSize="18" Margin="10,25,10,10" HorizontalOptions="Fill" HorizontalTextAlignment="Center" Text="{Binding Filter, StringFormat='Your filter term of {0} did not match any records'}"></Label> </StackLayout> </DataTemplate> </CollectionView.EmptyViewTemplate> </CollectionView> </Grid> </ContentPage.Content> </ContentPage> ```
/content/code_sandbox/Xamarin.Forms.Controls/GalleryPages/CollectionViewGalleries/EmptyViewGalleries/EmptyViewTemplateGallery.xaml
xml
2016-03-18T15:52:03
2024-08-16T16:25:43
Xamarin.Forms
xamarin/Xamarin.Forms
5,637
295
```xml <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion> <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked> <LangVersion>latest</LangVersion> <ImplicitUsings>enable</ImplicitUsings> <NeutralLanguage>en</NeutralLanguage> <Nullable>enable</Nullable> <NoWarn>1701;1702;CS1591;IDE0060;NETSDK1206;NU1608</NoWarn> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebugType>full</DebugType> <DebugSymbols>True</DebugSymbols> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\extensions\Squidex.Extensions\Squidex.Extensions.csproj" /> <ProjectReference Include="..\Migrations\Migrations.csproj" /> <ProjectReference Include="..\Squidex.Domain.Apps.Core.Model\Squidex.Domain.Apps.Core.Model.csproj" /> <ProjectReference Include="..\Squidex.Domain.Apps.Core.Operations\Squidex.Domain.Apps.Core.Operations.csproj" /> <ProjectReference Include="..\Squidex.Domain.Apps.Entities\Squidex.Domain.Apps.Entities.csproj" /> <ProjectReference Include="..\Squidex.Domain.Apps.Entities.MongoDb\Squidex.Domain.Apps.Entities.MongoDb.csproj" /> <ProjectReference Include="..\Squidex.Domain.Apps.Events\Squidex.Domain.Apps.Events.csproj" /> <ProjectReference Include="..\Squidex.Domain.Users\Squidex.Domain.Users.csproj" /> <ProjectReference Include="..\Squidex.Domain.Users.MongoDb\Squidex.Domain.Users.MongoDb.csproj" /> <ProjectReference Include="..\Squidex.Infrastructure.GetEventStore\Squidex.Infrastructure.GetEventStore.csproj" /> <ProjectReference Include="..\Squidex.Infrastructure\Squidex.Infrastructure.csproj" /> <ProjectReference Include="..\Squidex.Infrastructure.MongoDb\Squidex.Infrastructure.MongoDb.csproj" /> <ProjectReference Include="..\Squidex.Shared\Squidex.Shared.csproj" /> <ProjectReference Include="..\Squidex.Web\Squidex.Web.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="AspNet.Security.OAuth.GitHub" Version="8.1.0" /> <PackageReference Include="Google.Cloud.Trace.V2" Version="3.6.0" /> <PackageReference Include="GraphQL" Version="7.8.0" /> <PackageReference Include="GraphQL.MicrosoftDI" Version="7.8.0" /> <PackageReference Include="GraphQL.SystemTextJson" Version="7.8.0" /> <PackageReference Include="Meziantou.Analyzer" Version="2.0.159"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="8.0.6" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.MicrosoftAccount" Version="8.0.6" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.6" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="8.0.6" /> <PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="8.0.6" /> <PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="8.0.0" /> <PackageReference Include="Microsoft.CodeAnalysis.RulesetToEditorconfigConverter" Version="3.3.3" /> <PackageReference Include="Microsoft.Data.Edm" Version="5.8.5" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" /> <PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" /> <PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="7.6.2" /> <PackageReference Include="Microsoft.OData.Core" Version="7.21.3" /> <PackageReference Include="MongoDB.Driver" Version="2.27.0" /> <PackageReference Include="MongoDB.Driver.Core.Extensions.OpenTelemetry" Version="1.0.0" /> <PackageReference Include="NetTopologySuite.IO.GeoJSON4STJ" Version="4.0.0" /> <PackageReference Include="NJsonSchema" Version="11.0.1" /> <PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.2.0" /> <PackageReference Include="NSwag.AspNetCore" Version="14.0.8" /> <PackageReference Include="OpenCover" Version="4.7.1221" PrivateAssets="all" /> <PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" /> <PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" /> <PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" /> <PackageReference Include="ReportGenerator" Version="5.3.7" PrivateAssets="all" /> <PackageReference Include="Squidex.Assets.Azure" Version="6.18.0" /> <PackageReference Include="Squidex.Assets.GoogleCloud" Version="6.18.0" /> <PackageReference Include="Squidex.Assets.FTP" Version="6.18.0" /> <PackageReference Include="Squidex.Assets.ImageMagick" Version="6.18.0" /> <PackageReference Include="Squidex.Assets.ImageSharp" Version="6.18.0" /> <PackageReference Include="Squidex.Assets.Mongo" Version="6.18.0" /> <PackageReference Include="Squidex.Assets.S3" Version="6.18.0" /> <PackageReference Include="Squidex.Assets.TusAdapter" Version="6.18.0" /> <PackageReference Include="Squidex.ClientLibrary" Version="19.2.0" /> <PackageReference Include="Squidex.Hosting" Version="6.18.0" /> <PackageReference Include="Squidex.Messaging.All" Version="6.18.0" /> <PackageReference Include="Squidex.Messaging.Subscriptions" Version="6.18.0" /> <PackageReference Include="Squidex.OpenIddict.MongoDb" Version="5.1.0" /> <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" /> <PackageReference Include="YDotNet" Version="0.4.0" /> <PackageReference Include="YDotNet.Native" Version="0.4.0" /> <PackageReference Include="YDotNet.Server" Version="0.4.0" /> <PackageReference Include="YDotNet.Server.MongoDB" Version="0.4.0" /> <PackageReference Include="YDotNet.Server.Redis" Version="0.4.0" /> <PackageReference Include="YDotNet.Server.WebSockets" Version="0.4.0" /> </ItemGroup> <PropertyGroup> <GenerateDocumentationFile>true</GenerateDocumentationFile> </PropertyGroup> <ItemGroup> <AdditionalFiles Include="..\..\stylecop.json" Link="stylecop.json" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Areas\Api\Controllers\Users\Assets\Avatar.png" /> <EmbeddedResource Include="Pipeline\Squid\icon-happy-sm.svg" /> <EmbeddedResource Include="Pipeline\Squid\icon-happy.svg" /> <EmbeddedResource Include="Pipeline\Squid\icon-sad-sm.svg" /> <EmbeddedResource Include="Pipeline\Squid\icon-sad.svg" /> <EmbeddedResource Remove="Assets\**" /> <EmbeddedResource Remove="wwwroot\build\**" /> </ItemGroup> <ItemGroup> <Compile Remove="Assets\**" /> <Compile Remove="wwwroot\build\**" /> </ItemGroup> <ItemGroup> <None Remove="Areas\Api\Controllers\Users\Assets\Avatar.png" /> <None Remove="Pipeline\Squid\icon-happy-sm.svg" /> <None Remove="Pipeline\Squid\icon-happy.svg" /> <None Remove="Pipeline\Squid\icon-sad-sm.svg" /> <None Remove="Pipeline\Squid\icon-sad.svg" /> </ItemGroup> <ItemGroup> <None Remove="Assets\**" /> <None Remove="wwwroot\build\**" /> </ItemGroup> <ItemGroup> <Content Remove="Assets\**" /> <Content Remove="wwwroot\build\**" /> </ItemGroup> <ItemGroup> <Folder Include="Areas\Frontend\Resources\" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="..\..\i18n\frontend_en.json" Link="Areas\Frontend\Resources\frontend_en.json" /> <EmbeddedResource Include="..\..\i18n\frontend_it.json" Link="Areas\Frontend\Resources\frontend_it.json" /> <EmbeddedResource Include="..\..\i18n\frontend_nl.json" Link="Areas\Frontend\Resources\frontend_nl.json" /> <EmbeddedResource Include="..\..\i18n\frontend_pt.json" Link="Areas\Frontend\Resources\frontend_pt.json" /> <EmbeddedResource Include="..\..\i18n\frontend_zh.json" Link="Areas\Frontend\Resources\frontend_zh.json" /> <EmbeddedResource Include="..\..\i18n\frontend_fr.json" Link="Areas\Frontend\Resources\frontend_fr.json" /> </ItemGroup> <ItemGroup> <None Include="wwwroot\scripts\outdatedbrowser\outdatedbrowser.min.js" /> </ItemGroup> <ItemGroup> <Compile Update="Properties\Resources.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>Resources.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="Properties\Resources.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> </Project> ```
/content/code_sandbox/backend/src/Squidex/Squidex.csproj
xml
2016-08-29T05:53:40
2024-08-16T17:39:38
squidex
Squidex/squidex
2,222
2,384
```xml import { Platform } from 'react-native'; import setColor from 'color'; import { grey400, grey800, grey50, grey700, white, black, } from '../../styles/themes/v2/colors'; import type { InternalTheme } from '../../types'; type BaseProps = { theme: InternalTheme; disabled?: boolean; value?: boolean; }; const getCheckedColor = ({ theme, color, }: { theme: InternalTheme; color?: string; }) => { if (color) { return color; } if (theme.isV3) { return theme.colors.primary; } return theme.colors.accent; }; const getThumbTintColor = ({ theme, disabled, value, checkedColor, }: BaseProps & { checkedColor: string }) => { const isIOS = Platform.OS === 'ios'; if (isIOS) { return undefined; } if (disabled) { if (theme.dark) { return grey800; } return grey400; } if (value) { return checkedColor; } if (theme.dark) { return grey400; } return grey50; }; const getOnTintColor = ({ theme, disabled, value, checkedColor, }: BaseProps & { checkedColor: string }) => { const isIOS = Platform.OS === 'ios'; if (isIOS) { return checkedColor; } if (disabled) { if (theme.dark) { if (theme.isV3) { return setColor(white).alpha(0.06).rgb().string(); } return setColor(white).alpha(0.1).rgb().string(); } return setColor(black).alpha(0.12).rgb().string(); } if (value) { return setColor(checkedColor).alpha(0.5).rgb().string(); } if (theme.dark) { return grey700; } return 'rgb(178, 175, 177)'; }; export const getSwitchColor = ({ theme, disabled, value, color, }: BaseProps & { color?: string }) => { const checkedColor = getCheckedColor({ theme, color }); return { onTintColor: getOnTintColor({ theme, disabled, value, checkedColor }), thumbTintColor: getThumbTintColor({ theme, disabled, value, checkedColor }), checkedColor, }; }; ```
/content/code_sandbox/src/components/Switch/utils.ts
xml
2016-10-19T05:56:53
2024-08-16T08:48:04
react-native-paper
callstack/react-native-paper
12,646
533
```xml <!-- *********************************************************************************************** Xamarin.TVOS.Common.props WARNING: DO NOT MODIFY this file unless you are knowledgeable about MSBuild and have created a backup copy. Incorrect changes to this file will make it impossible to load or build your projects from the command-line or the IDE. This file defines default properties for iOS App Extension projects. *********************************************************************************************** --> <Project xmlns="path_to_url"> <Import Project="$(MSBuildThisFileDirectory)$(MSBuildThisFileName).Before.props" Condition="Exists('$(MSBuildThisFileDirectory)$(MSBuildThisFileName).Before.props')"/> <Import Project="$(MSBuildThisFileDirectory)$(MSBuildThisFileName).After.props" Condition="Exists('$(MSBuildThisFileDirectory)$(MSBuildThisFileName).After.props')"/> </Project> ```
/content/code_sandbox/msbuild/Xamarin.Shared/Xamarin.TVOS.Common.props
xml
2016-04-20T18:24:26
2024-08-16T13:29:19
xamarin-macios
xamarin/xamarin-macios
2,436
174
```xml <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <IsPackable>false</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="CommandLineParser" Version="2.9.1" /> <PackageReference Include="xunit" Version="2.4.2" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3"/> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Dafny\Dafny.csproj" /> <ProjectReference Include="..\XUnitExtensions\XUnitExtensions.csproj" /> </ItemGroup> <ItemGroup> <Content Include="..\..\Binaries\z3\**\*.*" LinkBase="z3"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup> </Project> ```
/content/code_sandbox/Source/TestDafny/TestDafny.csproj
xml
2016-04-16T20:05:38
2024-08-16T13:55:18
dafny
dafny-lang/dafny
2,863
246
```xml import React, { FunctionComponent, useCallback, useEffect, useState, } from "react"; import { graphql } from "react-relay"; import ModerationReason from "coral-admin/components/ModerationReason/ModerationReason"; import { useViewerEvent } from "coral-framework/lib/events"; import { useMutation, withFragmentContainer } from "coral-framework/lib/relay"; import CLASSES from "coral-stream/classes"; import { ShowModerationPopoverEvent } from "coral-stream/events"; import { Dropdown } from "coral-ui/components/v2"; import { ModerationDropdownContainer_comment } from "coral-stream/__generated__/ModerationDropdownContainer_comment.graphql"; import { ModerationDropdownContainer_settings } from "coral-stream/__generated__/ModerationDropdownContainer_settings.graphql"; import { ModerationDropdownContainer_story } from "coral-stream/__generated__/ModerationDropdownContainer_story.graphql"; import { ModerationDropdownContainer_viewer } from "coral-stream/__generated__/ModerationDropdownContainer_viewer.graphql"; import { RejectCommentReasonInput } from "coral-stream/__generated__/RejectCommentMutation.graphql"; import UserBanPopoverContainer from "../UserBanPopover/UserBanPopoverContainer"; import ModerationActionsContainer from "./ModerationActionsContainer"; import RejectCommentMutation from "./RejectCommentMutation"; import styles from "./ModerationDropdownContainer.css"; export type ModerationDropdownView = | "MODERATE" | "REJECT_REASON" | "BAN" | "SITE_BAN" | "CONFIRM_BAN"; interface Props { comment: ModerationDropdownContainer_comment; story: ModerationDropdownContainer_story; viewer: ModerationDropdownContainer_viewer; settings: ModerationDropdownContainer_settings; onDismiss: () => void; scheduleUpdate: () => void; view?: ModerationDropdownView; } const ModerationDropdownContainer: FunctionComponent<Props> = ({ comment, story, viewer, settings, onDismiss, scheduleUpdate, view: viewProp, }) => { const rejectMutation = useMutation(RejectCommentMutation); const emitShowEvent = useViewerEvent(ShowModerationPopoverEvent); const [view, setView] = useState<ModerationDropdownView>( viewProp ?? "MODERATE" ); const onBan = useCallback(() => { setView("BAN"); scheduleUpdate(); }, [setView, scheduleUpdate]); const onSiteBan = useCallback(() => { setView("SITE_BAN"); scheduleUpdate(); }, [setView, scheduleUpdate]); const onRectionReason = useCallback(() => { setView("REJECT_REASON"); scheduleUpdate(); }, [setView, scheduleUpdate]); const reject = useCallback( async (reason: RejectCommentReasonInput) => { if (!comment.revision) { return; } await rejectMutation({ commentID: comment.id, storyID: story.id, commentRevisionID: comment.revision.id, reason, }); }, [comment.id, comment.revision, rejectMutation, story.id] ); // run once. useEffect(() => { emitShowEvent({ commentID: comment.id }); }, []); return ( <div> {view === "MODERATE" ? ( <Dropdown className={CLASSES.moderationDropdown.$root}> <ModerationActionsContainer comment={comment} story={story} viewer={viewer} settings={settings} onDismiss={onDismiss} onBan={onBan} onRejectionReason={onRectionReason} onSiteBan={onSiteBan} /> </Dropdown> ) : view === "REJECT_REASON" ? ( <ModerationReason id={comment.id} onReason={reject} onCancel={onDismiss} linkClassName={styles.link} /> ) : ( <UserBanPopoverContainer comment={comment} settings={settings} story={story} viewer={viewer} onDismiss={onDismiss} view={view} /> )} </div> ); }; const enhanced = withFragmentContainer<Props>({ comment: graphql` fragment ModerationDropdownContainer_comment on Comment { id author { id username } revision { id } status tags { code } ...ModerationActionsContainer_comment ...UserBanPopoverContainer_comment } `, story: graphql` fragment ModerationDropdownContainer_story on Story { id ...ModerationActionsContainer_story ...UserBanPopoverContainer_story } `, settings: graphql` fragment ModerationDropdownContainer_settings on Settings { ...ModerationActionsContainer_settings ...UserBanPopoverContainer_settings } `, viewer: graphql` fragment ModerationDropdownContainer_viewer on User { ...ModerationActionsContainer_viewer ...UserBanPopoverContainer_viewer } `, })(ModerationDropdownContainer); export default enhanced; ```
/content/code_sandbox/client/src/core/client/stream/tabs/Comments/Comment/ModerationDropdown/ModerationDropdownContainer.tsx
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
1,080
```xml import { createContext, useContext } from 'react' /** * A React context for sharing the `selected` state of an element. */ export const SelectedContext = createContext(false) /** * Get the current `selected` state of an element. */ export const useSelected = (): boolean => { return useContext(SelectedContext) } ```
/content/code_sandbox/packages/slate-react/src/hooks/use-selected.ts
xml
2016-06-18T01:52:42
2024-08-16T18:43:42
slate
ianstormtaylor/slate
29,492
67
```xml import { Observable } from '../Observable'; import { Operator } from '../Operator'; import { Subscriber } from '../Subscriber'; import { OperatorFunction } from '../types'; /** * Ignores all items emitted by the source Observable and only passes calls of `complete` or `error`. * * ![](ignoreElements.png) * * ## Examples * ### Ignores emitted values, reacts to observable's completion. * ```javascript * of('you', 'talking', 'to', 'me').pipe( * ignoreElements(), * ) * .subscribe( * word => console.log(word), * err => console.log('error:', err), * () => console.log('the end'), * ); * // result: * // 'the end' * ``` * @return {Observable} An empty Observable that only calls `complete` * or `error`, based on which one is called by the source Observable. * @method ignoreElements * @owner Observable */ export function ignoreElements(): OperatorFunction<any, never> { return function ignoreElementsOperatorFunction(source: Observable<any>) { return source.lift(new IgnoreElementsOperator()); }; } class IgnoreElementsOperator<T, R> implements Operator<T, R> { call(subscriber: Subscriber<R>, source: any): any { return source.subscribe(new IgnoreElementsSubscriber(subscriber)); } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ class IgnoreElementsSubscriber<T> extends Subscriber<T> { protected _next(unused: T): void { // Do nothing } } ```
/content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/src/internal/operators/ignoreElements.ts
xml
2016-09-05T10:18:44
2024-08-11T13:21:40
LiquidCore
LiquidPlayer/LiquidCore
1,010
340
```xml import type { ReactNode, RefObject } from 'react'; import { createContext, useContext, useEffect } from 'react'; import { useHandler } from '@proton/components'; const MailContentRefContext = createContext<RefObject<HTMLDivElement>>(null as any); /** * Call the handler whenever the user click on the mail app content * but not on any kind of modal / notification / composer window */ export const useClickMailContent = (handler: (event: Event) => void) => { const stableHandler = useHandler(handler); const mailContentRef = useContext(MailContentRefContext); // mousedown and touchstart avoid issue with the click in portal (modal, notification, composer, dropdown) useEffect(() => { mailContentRef.current?.addEventListener('mousedown', stableHandler, { passive: true }); mailContentRef.current?.addEventListener('touchstart', stableHandler, { passive: true }); return () => { mailContentRef.current?.removeEventListener('mousedown', stableHandler); mailContentRef.current?.removeEventListener('touchstart', stableHandler); }; }, []); }; interface Props { children: ReactNode; mailContentRef: RefObject<HTMLDivElement>; } export const MailContentRefProvider = ({ children, mailContentRef }: Props) => { return <MailContentRefContext.Provider value={mailContentRef}>{children}</MailContentRefContext.Provider>; }; ```
/content/code_sandbox/applications/mail/src/app/hooks/useClickMailContent.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
292
```xml import versions from './versions'; /// <reference types="@types/compression" /> export * from './presets'; export * from './utils/cache'; export * from './utils/cli'; export * from './utils/check-addon-order'; export * from './utils/envs'; export * from './utils/common-glob-options'; export * from './utils/framework-to-renderer'; export * from './utils/get-builder-options'; export * from './utils/get-framework-name'; export * from './utils/get-renderer-name'; export * from './utils/get-storybook-configuration'; export * from './utils/get-storybook-info'; export * from './utils/get-storybook-refs'; export * from './utils/glob-to-regexp'; export * from './utils/HandledError'; export * from './utils/handlebars'; export * from './utils/interpolate'; export * from './utils/interpret-files'; export * from './utils/interpret-require'; export * from './utils/load-custom-presets'; export * from './utils/load-main-config'; export * from './utils/load-manager-or-addons-file'; export * from './utils/load-preview-or-config-file'; export * from './utils/log'; export * from './utils/log-config'; export * from './utils/normalize-stories'; export * from './utils/paths'; export * from './utils/readTemplate'; export * from './utils/remove'; export * from './utils/resolve-path-in-sb-cache'; export * from './utils/symlinks'; export * from './utils/template'; export * from './utils/validate-config'; export * from './utils/validate-configuration-files'; export * from './utils/satisfies'; export * from './utils/strip-abs-node-modules-path'; export * from './utils/formatter'; export * from './utils/get-story-id'; export * from './utils/posix'; export * from './js-package-manager'; export { versions }; export { createFileSystemCache } from './utils/file-cache'; ```
/content/code_sandbox/code/core/src/common/index.ts
xml
2016-03-18T04:23:44
2024-08-16T19:22:08
storybook
storybookjs/storybook
83,755
400
```xml <?xml version="1.0" encoding="UTF-8"?> <!-- Generated with glade 3.20.4 --> <interface> <requires lib="gtk+" version="3.10"/> <object class="GtkAdjustment" id="adjDiagonalRange"> <property name="lower">1</property> <property name="upper">89</property> <property name="value">45</property> <property name="step_increment">1</property> <property name="page_increment">10</property> </object> <object class="GtkAdjustment" id="adjMenuPosX"> <property name="upper">4096</property> <property name="value">10</property> <property name="step_increment">1</property> <property name="page_increment">10</property> </object> <object class="GtkAdjustment" id="adjMenuPosY"> <property name="upper">4096</property> <property name="value">10</property> <property name="step_increment">1</property> <property name="page_increment">10</property> </object> <object class="GtkAdjustment" id="adjMenuSize"> <property name="upper">100</property> <property name="step_increment">1</property> <property name="page_increment">2</property> </object> <object class="GtkListStore" id="lstButton"> <columns> <!-- column-name text --> <column type="gchararray"/> <!-- column-name button --> <column type="gchararray"/> </columns> <data> <row> <col id="0" translatable="yes">(Controller Default)</col> <col id="1">DEFAULT</col> </row> <row> <col id="0" translatable="yes">-</col> <col id="1">x</col> </row> <row> <col id="0" translatable="yes">A</col> <col id="1">A</col> </row> <row> <col id="0" translatable="yes">B</col> <col id="1">B</col> </row> <row> <col id="0" translatable="yes">X</col> <col id="1">X</col> </row> <row> <col id="0" translatable="yes">Y</col> <col id="1">Y</col> </row> <row> <col id="0" translatable="yes">-</col> <col id="1">x</col> </row> <row> <col id="0" translatable="yes">Back (select)</col> <col id="1">BACK</col> </row> <row> <col id="0" translatable="yes">Center</col> <col id="1">C</col> </row> <row> <col id="0" translatable="yes">Start</col> <col id="1">START</col> </row> <row> <col id="0" translatable="yes">-</col> <col id="1">x</col> </row> <row> <col id="0" translatable="yes">Left Grip</col> <col id="1">LGRIP</col> </row> <row> <col id="0" translatable="yes">Right Grip</col> <col id="1">RGRIP</col> </row> <row> <col id="0" translatable="yes">-</col> <col id="1">x</col> </row> <row> <col id="0" translatable="yes">Left Bumper</col> <col id="1">LB</col> </row> <row> <col id="0" translatable="yes">Right Bumper</col> <col id="1">RB</col> </row> <row> <col id="0" translatable="yes">Left Trigger</col> <col id="1">LT</col> </row> <row> <col id="0" translatable="yes">Right Trigger</col> <col id="1">RT</col> </row> <row> <col id="0" translatable="yes">-</col> <col id="1">x</col> </row> <row> <col id="0" translatable="yes">Stick Press</col> <col id="1">STICKPRESS</col> </row> <row> <col id="0" translatable="yes">Left Pad Press</col> <col id="1">LPAD</col> </row> <row> <col id="0" translatable="yes">Right Pad Press</col> <col id="1">RPAD</col> </row> </data> </object> <object class="GtkListStore" id="lstMenu"> <columns> <!-- column-name name --> <column type="gchararray"/> <!-- column-name key --> <column type="gchararray"/> </columns> </object> <object class="GtkListStore" id="lstMenuPosX"> <columns> <!-- column-name id --> <column type="gint"/> <!-- column-name text --> <column type="gchararray"/> </columns> <data> <row> <col id="0">1</col> <col id="1" translatable="yes">From Left</col> </row> <row> <col id="0">-1</col> <col id="1" translatable="yes">From Right</col> </row> </data> </object> <object class="GtkListStore" id="lstMenuPosY"> <columns> <!-- column-name id --> <column type="gint"/> <!-- column-name text --> <column type="gchararray"/> </columns> <data> <row> <col id="0">1</col> <col id="1" translatable="yes">From Top</col> </row> <row> <col id="0">-1</col> <col id="1" translatable="yes">From Bottom</col> </row> </data> </object> <object class="GtkListStore" id="lstMenuType"> <columns> <!-- column-name text --> <column type="gchararray"/> <!-- column-name action --> <column type="gchararray"/> </columns> <data> <row> <col id="0" translatable="yes">List</col> <col id="1">menu</col> </row> <row> <col id="0" translatable="yes">Grid</col> <col id="1">gridmenu</col> </row> <row> <col id="0" translatable="yes">Radial</col> <col id="1">radialmenu</col> </row> <row> <col id="0" translatable="yes">Horizontal Menu</col> <col id="1">hmenu</col> </row> </data> </object> <object class="GtkListStore" id="lstOutType"> <columns> <!-- column-name text --> <column type="gchararray"/> <!-- column-name action --> <column type="gchararray"/> </columns> <data> <row> <col id="0" translatable="yes">Simple DPAD</col> <col id="1">dpad</col> </row> <row> <col id="0" translatable="yes">8-Way DPAD</col> <col id="1">dpad8</col> </row> <row> <col id="0" translatable="yes">WSAD (DPAD)</col> <col id="1">wsad</col> </row> <row> <col id="0" translatable="yes">Arrows (DPAD)</col> <col id="1">arrows</col> </row> <row> <col id="0" translatable="yes">Emulated DPAD</col> <col id="1">actual_dpad</col> </row> <row> <col id="0" translatable="yes">Menu</col> <col id="1">menu</col> </row> </data> </object> <object class="GtkGrid" id="dpad"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkStack" id="stActionData"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="hexpand">True</property> <property name="vexpand">True</property> <property name="transition_type">crossfade</property> <child> <object class="GtkGrid" id="grDPAD"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="row_spacing">5</property> <property name="column_spacing">5</property> <child> <object class="GtkButton" id="btDPAD2"> <property name="name">2</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="margin_top">20</property> <property name="hexpand">True</property> <signal name="clicked" handler="on_btDPAD_clicked" swapped="no"/> <child> <object class="GtkBox" id="box1"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkImage" id="image2"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="stock">gtk-go-back</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkSeparator" id="separator3"> <property name="visible">True</property> <property name="can_focus">False</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkLabel" id="lblDPAD2"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">(...)</property> </object> <packing> <property name="expand">True</property> <property name="fill">True</property> <property name="position">2</property> </packing> </child> </object> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">1</property> </packing> </child> <child> <object class="GtkButton" id="btDPAD1"> <property name="name">1</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="margin_top">20</property> <property name="hexpand">True</property> <signal name="clicked" handler="on_btDPAD_clicked" swapped="no"/> <child> <object class="GtkBox" id="box2"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkImage" id="image3"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="stock">gtk-go-down</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkSeparator" id="separator4"> <property name="visible">True</property> <property name="can_focus">False</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkLabel" id="lblDPAD1"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">(...)</property> </object> <packing> <property name="expand">True</property> <property name="fill">True</property> <property name="position">2</property> </packing> </child> </object> </child> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">2</property> </packing> </child> <child> <object class="GtkButton" id="btDPAD0"> <property name="name">0</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="margin_top">20</property> <property name="hexpand">True</property> <signal name="clicked" handler="on_btDPAD_clicked" swapped="no"/> <child> <object class="GtkBox" id="box6"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkImage" id="image4"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="stock">gtk-go-up</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkSeparator" id="separator5"> <property name="visible">True</property> <property name="can_focus">False</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkLabel" id="lblDPAD0"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">(...)</property> </object> <packing> <property name="expand">True</property> <property name="fill">True</property> <property name="position">2</property> </packing> </child> </object> </child> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkButton" id="btDPAD3"> <property name="name">3</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="margin_top">20</property> <property name="hexpand">True</property> <signal name="clicked" handler="on_btDPAD_clicked" swapped="no"/> <child> <object class="GtkBox" id="box7"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkLabel" id="lblDPAD3"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">(...)</property> </object> <packing> <property name="expand">True</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkSeparator" id="separator6"> <property name="visible">True</property> <property name="can_focus">False</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkImage" id="image5"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="stock">gtk-go-forward</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">2</property> </packing> </child> </object> </child> </object> <packing> <property name="left_attach">2</property> <property name="top_attach">1</property> </packing> </child> <child> <object class="GtkButton" id="btDPAD4"> <property name="label" translatable="yes">(...)</property> <property name="name">4</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="no_show_all">True</property> <property name="margin_top">20</property> <property name="hexpand">True</property> <signal name="clicked" handler="on_btDPAD_clicked" swapped="no"/> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkButton" id="btDPAD5"> <property name="label" translatable="yes">(...)</property> <property name="name">5</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="no_show_all">True</property> <property name="margin_top">20</property> <property name="hexpand">True</property> <signal name="clicked" handler="on_btDPAD_clicked" swapped="no"/> </object> <packing> <property name="left_attach">2</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkButton" id="btDPAD6"> <property name="label" translatable="yes">(...)</property> <property name="name">6</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="no_show_all">True</property> <property name="margin_top">20</property> <property name="hexpand">True</property> <signal name="clicked" handler="on_btDPAD_clicked" swapped="no"/> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">2</property> </packing> </child> <child> <object class="GtkButton" id="btDPAD7"> <property name="label" translatable="yes">(...)</property> <property name="name">7</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="no_show_all">True</property> <property name="margin_top">20</property> <property name="hexpand">True</property> <signal name="clicked" handler="on_btDPAD_clicked" swapped="no"/> </object> <packing> <property name="left_attach">2</property> <property name="top_attach">2</property> </packing> </child> <child> <object class="GtkBox" id="vbDiagonalRange"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_left">10</property> <property name="margin_right">10</property> <property name="margin_top">5</property> <child> <object class="GtkLabel" id="lblDiagonalRange"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Diagonal Range</property> <property name="xalign">0</property> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkScale" id="sclDiagonalRange"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="margin_left">10</property> <property name="margin_right">10</property> <property name="adjustment">adjDiagonalRange</property> <property name="round_digits">1</property> <property name="digits">0</property> <property name="value_pos">right</property> <signal name="format-value" handler="on_sclDiagonalRange_format_value" swapped="no"/> <signal name="value-changed" handler="on_sclDiagonalRange_value_changed" swapped="no"/> </object> <packing> <property name="expand">True</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkButton" id="btClearDiagonalRange"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <signal name="clicked" handler="on_btClearDiagonalRange_clicked" swapped="no"/> <child> <object class="GtkImage" id="image10"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="stock">gtk-clear</property> </object> </child> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">2</property> </packing> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">3</property> <property name="width">3</property> </packing> </child> <child> <placeholder/> </child> </object> <packing> <property name="name">page0</property> <property name="title" translatable="yes">page0</property> </packing> </child> <child> <object class="GtkGrid" id="grMenu"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_left">20</property> <property name="margin_right">20</property> <property name="margin_top">40</property> <child> <object class="GtkLabel" id="label4"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_top">10</property> <property name="margin_bottom">5</property> <property name="label" translatable="yes">Menu</property> <property name="xalign">0</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">2</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkComboBox" id="cbMenus"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_right">5</property> <property name="hexpand">True</property> <property name="model">lstMenu</property> <signal name="button-press-event" handler="on_cbMenus_button_press_event" swapped="no"/> <signal name="changed" handler="on_cbMenus_changed" swapped="no"/> <child> <object class="GtkCellRendererText" id="cellrenderertext3"/> <attributes> <attribute name="text">0</attribute> </attributes> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">3</property> </packing> </child> <child> <object class="GtkButton" id="btEditMenu"> <property name="label">gtk-edit</property> <property name="visible">True</property> <property name="sensitive">False</property> <property name="can_focus">True</property> <property name="receives_default">True</property> <property name="margin_left">5</property> <property name="use_stock">True</property> <signal name="clicked" handler="on_btEditMenu_clicked" swapped="no"/> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">3</property> </packing> </child> <child> <object class="GtkLabel" id="label1"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_bottom">5</property> <property name="label" translatable="yes">Menu Type</property> <property name="xalign">0</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">0</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkComboBox" id="cbMenuType"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="hexpand">True</property> <property name="model">lstMenuType</property> <property name="active">0</property> <signal name="changed" handler="on_cbMenus_changed" swapped="no"/> <child> <object class="GtkCellRendererText" id="cellrenderertext2"/> <attributes> <attribute name="text">0</attribute> </attributes> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">1</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkRevealer" id="rvMenuSize"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkBox" id="vbMenuSize"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="orientation">vertical</property> <child> <object class="GtkLabel" id="lblMenuSize"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_top">10</property> <property name="margin_bottom">5</property> <property name="label" translatable="yes">Items per row</property> <property name="xalign">0</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkSpinButton" id="spMenuSize"> <property name="can_focus">True</property> <property name="no_show_all">True</property> <property name="adjustment">adjMenuSize</property> <signal name="changed" handler="on_cbMenus_changed" swapped="no"/> <signal name="output" handler="on_spMenuSize_format_value" swapped="no"/> </object> <packing> <property name="expand">True</property> <property name="fill">True</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkScale" id="sclMenuSize"> <property name="can_focus">True</property> <property name="no_show_all">True</property> <property name="adjustment">adjMenuSize</property> <property name="round_digits">1</property> <property name="value_pos">right</property> <signal name="format-value" handler="on_sclMenuSize_format_value" swapped="no"/> </object> <packing> <property name="expand">False</property> <property name="fill">True</property> <property name="position">2</property> </packing> </child> </object> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">4</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkExpander" id="exMenuControl"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="margin_top">10</property> <signal name="activate" handler="on_exMenuControl_activate" swapped="no"/> <child> <placeholder/> </child> <child type="label"> <object class="GtkLabel" id="label67"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Control Options...</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">5</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkRevealer" id="rvMenuControl"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkGrid" id="grMenuControl"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_left">20</property> <property name="margin_right">20</property> <property name="margin_top">5</property> <property name="margin_bottom">10</property> <child> <object class="GtkLabel" id="lblConfirmWith"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_right">20</property> <property name="margin_bottom">5</property> <property name="label" translatable="yes">Confirm Button</property> <property name="xalign">0</property> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkLabel" id="lblCancelWith"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_right">20</property> <property name="margin_bottom">5</property> <property name="label" translatable="yes">Cancel Button</property> <property name="xalign">0</property> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">1</property> </packing> </child> <child> <object class="GtkComboBox" id="cbConfirmWith"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_bottom">5</property> <property name="hexpand">True</property> <property name="model">lstButton</property> <property name="active">0</property> <signal name="changed" handler="on_cbMenus_changed" swapped="no"/> <child> <object class="GtkCellRendererText" id="cellrenderertext6"/> <attributes> <attribute name="text">0</attribute> </attributes> </child> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkComboBox" id="cbCancelWith"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_bottom">5</property> <property name="hexpand">True</property> <property name="model">lstButton</property> <property name="active">0</property> <signal name="changed" handler="on_cbMenus_changed" swapped="no"/> <child> <object class="GtkCellRendererText" id="cellrenderertext7"/> <attributes> <attribute name="text">0</attribute> </attributes> </child> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">1</property> </packing> </child> <child> <object class="GtkCheckButton" id="cbMenuAutoConfirm"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="margin_top">5</property> <property name="draw_indicator">True</property> <signal name="toggled" handler="on_cbMenus_changed" swapped="no"/> <signal name="toggled" handler="prevent_confirm_cancel_nonsense" swapped="no"/> <child> <object class="GtkLabel" id="lblMenuAutoConfirm"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Confirm selection when pad is released</property> <property name="xalign">0</property> </object> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">3</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="cbMenuAutoCancel"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="margin_top">5</property> <property name="draw_indicator">True</property> <signal name="toggled" handler="on_cbMenus_changed" swapped="no"/> <signal name="toggled" handler="prevent_confirm_cancel_nonsense" swapped="no"/> <child> <object class="GtkLabel" id="lblMenuAutoCancel"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Cancel menu when pad is released</property> <property name="xalign">0</property> </object> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">4</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkCheckButton" id="cbMenuConfirmWithClick"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="margin_top">5</property> <property name="draw_indicator">True</property> <signal name="toggled" handler="on_cbMenus_changed" swapped="no"/> <signal name="toggled" handler="prevent_confirm_cancel_nonsense" swapped="no"/> <child> <object class="GtkLabel" id="lblMenuConfirmWithClick"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Confirm selection by clicking the pad</property> <property name="xalign">0</property> </object> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">2</property> <property name="width">2</property> </packing> </child> </object> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">6</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkExpander" id="exMenuPosition"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="margin_top">10</property> <signal name="activate" handler="on_exMenuPosition_activate" swapped="no"/> <child> <placeholder/> </child> <child type="label"> <object class="GtkLabel" id="label8"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">Menu Position...</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">7</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkRevealer" id="rvMenuPosition"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkGrid" id="grid7"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_left">20</property> <property name="margin_right">20</property> <property name="margin_top">5</property> <property name="margin_bottom">10</property> <child> <object class="GtkSpinButton" id="spMenuPosX"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="hexpand">True</property> <property name="adjustment">adjMenuPosX</property> <signal name="value-changed" handler="on_cbMenus_changed" swapped="no"/> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkSpinButton" id="spMenuPosY"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="margin_top">5</property> <property name="hexpand">True</property> <property name="adjustment">adjMenuPosY</property> <signal name="value-changed" handler="on_cbMenus_changed" swapped="no"/> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">1</property> </packing> </child> <child> <object class="GtkComboBox" id="cbMenuPosX"> <property name="width_request">200</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_left">20</property> <property name="model">lstMenuPosX</property> <property name="active">0</property> <signal name="changed" handler="on_cbMenus_changed" swapped="no"/> <child> <object class="GtkCellRendererText" id="crMenuPosX"/> <attributes> <attribute name="text">1</attribute> </attributes> </child> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkComboBox" id="cbMenuPosY"> <property name="width_request">200</property> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_left">20</property> <property name="margin_top">5</property> <property name="model">lstMenuPosY</property> <property name="active">1</property> <signal name="changed" handler="on_cbMenus_changed" swapped="no"/> <child> <object class="GtkCellRendererText" id="crMenuPosY"/> <attributes> <attribute name="text">1</attribute> </attributes> </child> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">1</property> </packing> </child> </object> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">8</property> <property name="width">2</property> </packing> </child> </object> <packing> <property name="name">page1</property> <property name="title" translatable="yes">page1</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">1</property> <property name="width">2</property> </packing> </child> <child> <object class="GtkLabel" id="label12"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="margin_right">20</property> <property name="label" translatable="yes">Output Type</property> <property name="xalign">0</property> <attributes> <attribute name="weight" value="bold"/> </attributes> </object> <packing> <property name="left_attach">0</property> <property name="top_attach">0</property> </packing> </child> <child> <object class="GtkComboBox" id="cbActionType"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="hexpand">True</property> <property name="model">lstOutType</property> <property name="active">0</property> <signal name="changed" handler="on_cbActionType_changed" swapped="no"/> <child> <object class="GtkCellRendererText" id="cellrenderertext1"/> <attributes> <attribute name="text">0</attribute> </attributes> </child> </object> <packing> <property name="left_attach">1</property> <property name="top_attach">0</property> </packing> </child> </object> <object class="GtkMenu" id="mnuMenu"> <property name="visible">True</property> <property name="can_focus">False</property> <child> <object class="GtkMenuItem" id="mnuMenuNew"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">_New Menu</property> <property name="use_underline">True</property> <signal name="activate" handler="on_mnuMenuNew_activate" swapped="no"/> </object> </child> <child> <object class="GtkMenuItem" id="mnuMenuCopy"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">_Copy Menu</property> <property name="use_underline">True</property> <signal name="activate" handler="on_mnuMenuCopy_activate" swapped="no"/> </object> </child> <child> <object class="GtkMenuItem" id="mnuMenuRename"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">_Rename Menu</property> <property name="use_underline">True</property> <signal name="activate" handler="on_mnuMenuRename_activate" swapped="no"/> </object> </child> <child> <object class="GtkMenuItem" id="mnuMenuDelete"> <property name="visible">True</property> <property name="can_focus">False</property> <property name="label" translatable="yes">_Delete Menu</property> <property name="use_underline">True</property> <signal name="activate" handler="on_mnuMenuDelete_activate" swapped="no"/> </object> </child> </object> </interface> ```
/content/code_sandbox/glade/ae/dpad.glade
xml
2016-04-24T07:57:04
2024-08-12T02:37:39
sc-controller
kozec/sc-controller
1,522
10,863
```xml /* * path_to_url * * or in the 'license' file accompanying this file. This file is distributed * on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either */ import { LambdaHandler } from 'ask-sdk-core'; import { SkillInvokerConfig } from '../config/SkillInvokerConfig'; export class SkillInvokerConfigBuilder { private _skillHandler: LambdaHandler; public withHandler(handlerName: LambdaHandler): SkillInvokerConfigBuilder { this._skillHandler = handlerName; return this; } public get handler(): LambdaHandler { return this._skillHandler; } public build(): SkillInvokerConfig { return new SkillInvokerConfig(this); } } ```
/content/code_sandbox/ask-sdk-local-debug/lib/builder/SkillInvokerConfigBuilder.ts
xml
2016-06-24T06:26:05
2024-08-14T12:39:19
alexa-skills-kit-sdk-for-nodejs
alexa/alexa-skills-kit-sdk-for-nodejs
3,118
153
```xml import { Matcher } from './Matcher' import { joinPaths } from './URLTools' import { NaviRequest } from './NaviRequest' export const KEY_WILDCARD = '\0' export const MEMO_KEY_PREFIX = '\0' /** * An object that holds information about a path that can be matched * in *part* of a URL. */ export interface Mapping { /** * The relative path of a Map to its parent, with wildcards * represented by a colon `:`, followed by the name of the param where * their value should be placed. */ pattern: string /** * A string where wildcards have been replaced with the null character * '\0', so that no two identical keys will match the same URL. */ key: string /** * A regex that matches the path. * It should start with ^, but should not end with $.` */ regExp: RegExp /** * The names of params that correspond to wildcards in the relative path. */ pathParamNames?: string[] /** * The node that will be used to handle detailed matching of this path, * once a tentative match is found. */ matcher: Matcher<any> } export function createRootMapping( matcher: Matcher<any>, rootPath: string = '', ): Mapping { return rootPath !== '' ? createMapping(rootPath, matcher) : { pattern: rootPath, key: '', regExp: new RegExp(''), matcher, } } export function createMapping(pattern: string, matcher: Matcher<any>): Mapping { let processedPattern = pattern if (processedPattern.length > 1 && processedPattern.substr(-1) === '/') { if (process.env.NODE_ENV !== 'production') { console.warn( `The pattern "${pattern}" ends with the character '/', so it has been automatically removed. To avoid this warning, don't add a final "/" to patterns.`, ) } processedPattern = processedPattern.substr(0, processedPattern.length - 1) } if (processedPattern[0] !== '/') { if (process.env.NODE_ENV !== 'production') { console.warn( `The pattern "${pattern}" does not start with the character '/', so it has been automatically added. To avoid this warning, make sure to add the leading "/" to all patterns.`, ) } processedPattern = '/' + processedPattern } if (/\/{2,}/.test(processedPattern)) { if (process.env.NODE_ENV !== 'production') { console.warn( `The pattern "${pattern} has adjacent '/' characters, which have been combined into single '/' characters. To avoid this warning, don't use adjacent '/' characters within patterns.`, ) } processedPattern = processedPattern.replace(/\/{2,}/g, '/') } if (processedPattern.length === 0) { throw new Error(`You cannot use an empty string "" as a pattern!`) } let parts = processedPattern.split('/').slice(1) let pathParams: string[] = [] let keyParts: string[] = [] let regExpParts = ['^'] for (let i = 0; i < parts.length; i++) { let part = parts[i] if (part.length > 1 && part[0] === ':') { pathParams.push(part.slice(1)) keyParts.push(KEY_WILDCARD) regExpParts.push('([^/]+)') } else { keyParts.push(part) regExpParts.push(escapeRegExp(part)) } } return { key: keyParts.join('/'), matcher, pattern: processedPattern, pathParamNames: pathParams.length ? pathParams : undefined, regExp: processedPattern === '/' ? /^\/$/ : new RegExp(regExpParts.join('/')), } } export function matchAgainstPathname( request: NaviRequest, mapping: Mapping, ): NaviRequest | undefined { let match = mapping.regExp.exec(request.path || '/') if (!match) { return } let matchedPathname = match[0] let unmatchedPath = request.path.slice(matchedPathname.length) || '' if (unmatchedPath.length && unmatchedPath[0] !== '/') { return } // Set path params using RegExp match let params = request.params if (mapping.pathParamNames) { params = { ...request.params } for (let i = 0; i < mapping.pathParamNames.length; i++) { let paramName = mapping.pathParamNames[i] params[paramName] = match[i + 1] } } let mountpath = joinPaths(request.mountpath, matchedPathname) || '/' return { ...request, params, mountpath, path: unmatchedPath, url: unmatchedPath + request.search, } } // From path_to_url // Originally from path_to_url (dead link) function escapeRegExp(value) { return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } ```
/content/code_sandbox/packages/navi/src/Mapping.ts
xml
2016-09-24T07:44:26
2024-07-11T14:52:12
navi
frontarm/navi
2,070
1,111
```xml <dict> <key>CommonPeripheralDSP</key> <array> <dict> <key>DeviceID</key> <integer>0</integer> <key>DeviceType</key> <string>Headphone</string> </dict> <dict> <key>DeviceID</key> <integer>0</integer> <key>DeviceType</key> <string>Microphone</string> </dict> </array> <key>PathMaps</key> <array> <dict> <key>PathMap</key> <array> <array> <array> <array> <dict> <key>Amp</key> <dict> <key>Channels</key> <array> <dict> <key>Bind</key> <integer>1</integer> <key>Channel</key> <integer>1</integer> </dict> <dict> <key>Bind</key> <integer>2</integer> <key>Channel</key> <integer>2</integer> </dict> </array> <key>MuteInputAmp</key> <true/> <key>PublishMute</key> <true/> <key>PublishVolume</key> <true/> <key>VolumeInputAmp</key> <true/> </dict> <key>NodeID</key> <integer>9</integer> </dict> <dict> <key>NodeID</key> <integer>34</integer> </dict> <dict> <key>NodeID</key> <integer>18</integer> </dict> </array> </array> <array> <array> <dict> <key>Amp</key> <dict> <key>Channels</key> <array> <dict> <key>Bind</key> <integer>1</integer> <key>Channel</key> <integer>1</integer> </dict> <dict> <key>Bind</key> <integer>2</integer> <key>Channel</key> <integer>2</integer> </dict> </array> <key>MuteInputAmp</key> <true/> <key>PublishMute</key> <true/> <key>PublishVolume</key> <true/> <key>VolumeInputAmp</key> <true/> </dict> <key>NodeID</key> <integer>8</integer> </dict> <dict> <key>NodeID</key> <integer>35</integer> </dict> <dict> <key>NodeID</key> <integer>24</integer> </dict> </array> </array> </array> <array> <array> <array> <dict> <key>Amp</key> <dict> <key>MuteInputAmp</key> <false/> <key>PublishMute</key> <true/> <key>PublishVolume</key> <true/> <key>VolumeInputAmp</key> <false/> </dict> <key>NodeID</key> <integer>21</integer> </dict> <dict> <key>Amp</key> <dict> <key>MuteInputAmp</key> <true/> <key>PublishMute</key> <true/> <key>PublishVolume</key> <true/> <key>VolumeInputAmp</key> <false/> </dict> <key>NodeID</key> <integer>12</integer> </dict> <dict> <key>Amp</key> <dict> <key>Channels</key> <array> <dict> <key>Bind</key> <integer>1</integer> <key>Channel</key> <integer>1</integer> </dict> <dict> <key>Bind</key> <integer>2</integer> <key>Channel</key> <integer>2</integer> </dict> </array> <key>MuteInputAmp</key> <true/> <key>PublishMute</key> <true/> <key>PublishVolume</key> <true/> <key>VolumeInputAmp</key> <false/> </dict> <key>NodeID</key> <integer>2</integer> </dict> </array> </array> <array> <array> <dict> <key>Amp</key> <dict> <key>MuteInputAmp</key> <false/> <key>PublishMute</key> <true/> <key>PublishVolume</key> <true/> <key>VolumeInputAmp</key> <false/> </dict> <key>NodeID</key> <integer>26</integer> </dict> <dict> <key>Amp</key> <dict> <key>MuteInputAmp</key> <true/> <key>PublishMute</key> <true/> <key>PublishVolume</key> <true/> <key>VolumeInputAmp</key> <false/> </dict> <key>NodeID</key> <integer>13</integer> </dict> <dict> <key>Amp</key> <dict> <key>Channels</key> <array> <dict> <key>Bind</key> <integer>1</integer> <key>Channel</key> <integer>1</integer> </dict> <dict> <key>Bind</key> <integer>2</integer> <key>Channel</key> <integer>2</integer> </dict> </array> <key>MuteInputAmp</key> <true/> <key>PublishMute</key> <true/> <key>PublishVolume</key> <true/> <key>VolumeInputAmp</key> <false/> </dict> <key>NodeID</key> <integer>3</integer> </dict> </array> </array> </array> </array> <key>PathMapID</key> <integer>269</integer> </dict> </array> </dict> ```
/content/code_sandbox/Resources/ALC269/Platforms100.xml
xml
2016-03-07T20:45:58
2024-08-14T08:57:03
AppleALC
acidanthera/AppleALC
3,420
1,752
```xml import spservice from '../../services/spservices'; import { IFile } from '../../webparts/myTasks/components/Attachments/IFile'; import { ITaskExternalReference } from '../../services/ITaskExternalReference'; export interface IUploadFromSharePointProps { spservice: spservice; onSelectedFile?: (file:IFile) => void; groupId:string; displayDialog: boolean; onDismiss: () => void; currentReferences: ITaskExternalReference; } ```
/content/code_sandbox/samples/react-mytasks/src/Controls/UploadFromSharePoint/IUploadFromSharePointProps.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
101
```xml import React from 'react'; if (!global.setImmediate) { global.setImmediate = function (fn) { return setTimeout(fn, 0); }; } if (process.env.NODE_ENV === 'development' && process.env.EXPO_OS === 'web') { // Stack traces are big with React Navigation require('./LogBox').default.install(); } export function withErrorOverlay(Comp: React.ComponentType<any>) { if (process.env.NODE_ENV === 'production') { return Comp; } const { default: ErrorToastContainer } = require('./toast/ErrorToastContainer') as typeof import('./toast/ErrorToastContainer'); return function ErrorOverlay(props: any) { return ( <ErrorToastContainer> <Comp {...props} /> </ErrorToastContainer> ); }; } ```
/content/code_sandbox/packages/@expo/metro-runtime/src/error-overlay/index.tsx
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
172
```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 Complex128 = require( '@stdlib/complex/float64/ctor' ); import conj = require( './index' ); // TESTS // // The function returns a complex number... { conj( new Complex128( 5.0, 3.0 ) ); // $ExpectType Complex128 } // The compiler throws an error if the function is provided an argument that is not a complex number... { conj( 'abc' ); // $ExpectError conj( 123 ); // $ExpectError conj( true ); // $ExpectError conj( false ); // $ExpectError conj( [] ); // $ExpectError conj( {} ); // $ExpectError conj( ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an unsupported number of arguments... { conj(); // $ExpectError conj( new Complex128( 5.0, 3.0 ), 123 ); // $ExpectError } ```
/content/code_sandbox/lib/node_modules/@stdlib/complex/float64/conj/docs/types/test.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
269
```xml import { describe, it, expect } from 'vitest' import { mount } from '@vue/test-utils' import { Radar } from '../src/index.js' import * as radarChartConfig from '../sandboxes/radar/src/chartConfig.js' describe('RadarChart', () => { it('should render a canvas', () => { const wrapper = mount(Radar, { props: radarChartConfig as any }) const canvas = wrapper.find('canvas') expect(canvas.exists()).toBe(true) expect(canvas.element.id).toBe('') }) it('should change id based on prop', () => { const wrapper = mount(Radar, { props: { id: 'radar-chart-id', ...radarChartConfig } as any }) const canvas = wrapper.find('canvas') expect(canvas.exists()).toBe(true) expect(canvas.element.id).toBe('radar-chart-id') }) it('should add inline plugins based on prop', () => { const testPlugin = { id: 'test' } const wrapper = mount(Radar, { props: { plugins: [testPlugin], ...radarChartConfig } as any }) expect(wrapper.props().plugins.length).toEqual(1) }) }) ```
/content/code_sandbox/test/Radar.spec.ts
xml
2016-06-26T13:25:12
2024-08-15T18:05:48
vue-chartjs
apertureless/vue-chartjs
5,514
276
```xml import type { Dependencies } from "@Core/Dependencies"; import type { DependencyRegistry } from "@Core/DependencyRegistry"; import { describe, expect, it, vi } from "vitest"; import { DuckDuckGoWebSearchEngine } from "./DuckDuckGoWebSearchEngine"; import { GoogleWebSearchEngine } from "./GoogleWebSearchEngine"; import { WebSearchExtension } from "./WebSearchExtension"; import { WebSearchExtensionModule } from "./WebSearchExtensionModule"; describe(WebSearchExtensionModule, () => { describe(WebSearchExtensionModule.prototype.bootstrap, () => { it("should return the web search extension", () => { const dependencyRegistry: DependencyRegistry<Dependencies> = { get: vi.fn(), register: vi.fn(), }; expect(new WebSearchExtensionModule().bootstrap(dependencyRegistry)).toEqual({ extension: new WebSearchExtension( dependencyRegistry.get("AssetPathResolver"), dependencyRegistry.get("SettingsManager"), [ new DuckDuckGoWebSearchEngine(dependencyRegistry.get("Net")), new GoogleWebSearchEngine(dependencyRegistry.get("Net")), ], ), }); }); }); }); ```
/content/code_sandbox/src/main/Extensions/WebSearch/WebSearchExtensionModule.test.ts
xml
2016-10-11T04:59:52
2024-08-16T11:53:31
ueli
oliverschwendener/ueli
3,543
243
```xml import { Commands } from "oni-api" import * as React from "react" import { Provider } from "react-redux" import { ISessionStore, Sessions } from "./" interface SessionPaneProps { commands: Commands.Api store: ISessionStore } /** * Class SessionsPane * * A Side bar pane for Oni's Session Management * */ export default class SessionsPane { private _store: ISessionStore private _commands: Commands.Api constructor({ store, commands }: SessionPaneProps) { this._commands = commands this._store = store this._setupCommands() } get id() { return "oni.sidebar.sessions" } public get title() { return "Sessions" } public enter() { this._store.dispatch({ type: "ENTER" }) } public leave() { this._store.dispatch({ type: "LEAVE" }) } public render() { return ( <Provider store={this._store}> <Sessions /> </Provider> ) } private _isActive = () => { const state = this._store.getState() return state.active && !state.creating } private _deleteSession = () => { this._store.dispatch({ type: "DELETE_SESSION" }) } private _setupCommands() { this._commands.registerCommand({ command: "oni.sessions.delete", name: "Sessions: Delete the current session", detail: "Delete the current or selected session", enabled: this._isActive, execute: this._deleteSession, }) } } ```
/content/code_sandbox/browser/src/Services/Sessions/SessionsPane.tsx
xml
2016-11-16T14:42:55
2024-08-14T11:48:05
oni
onivim/oni
11,355
347
```xml import * as React from 'react' import { Octicon } from '../octicons' import * as octicons from '../octicons/octicons.generated' import { Banner } from './banner' import { LinkButton } from '../lib/link-button' interface IConflictsFoundBannerProps { /** * Description of the operation to continue * Examples: * - rebasing <strong>target-branch-name</strong> * - cherry-picking onto <strong>target-branch-name</strong> * - squashing commits on <strong>target-branch-name</strong> */ readonly operationDescription: string | JSX.Element /** Callback to fire when the dialog should be reopened */ readonly onOpenConflictsDialog: () => void /** Callback to fire to dismiss the banner */ readonly onDismissed: () => void } export class ConflictsFoundBanner extends React.Component< IConflictsFoundBannerProps, {} > { private openDialog = async () => { this.props.onDismissed() this.props.onOpenConflictsDialog() } private onDismissed = () => { log.warn( `[ConflictsBanner] This cannot be dismissed by default unless the user clicks on the link` ) } public render() { return ( <Banner id="conflicts-found-banner" dismissable={false} onDismissed={this.onDismissed} > <Octicon className="alert-icon" symbol={octicons.alert} /> <div className="banner-message"> <span> Resolve conflicts to continue {this.props.operationDescription}. </span> <LinkButton onClick={this.openDialog}>View conflicts</LinkButton> </div> </Banner> ) } } ```
/content/code_sandbox/app/src/ui/banners/conflicts-found-banner.tsx
xml
2016-05-11T15:59:00
2024-08-16T17:00:41
desktop
desktop/desktop
19,544
379
```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> <artifactId>spring-cloud-function-deployer</artifactId> <packaging>jar</packaging> <name>spring-cloud-function-deployer</name> <description>Spring Cloud Function Deployer</description> <parent> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-function-parent</artifactId> <version>4.2.0-SNAPSHOT</version> </parent> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-loader-classic</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-loader</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-function-context</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-deployer-resource-maven</artifactId> <version>2.5.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>io.cloudevents</groupId> <artifactId>cloudevents-spring</artifactId> <version>2.2.0</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-invoker-plugin</artifactId> <version>3.0.1</version> <configuration> <localRepositoryPath>${project.build.directory}/local-repo </localRepositoryPath> </configuration> <executions> <execution> <id>prepare-test</id> <phase>test-compile</phase> <goals> <goal>run</goal> </goals> <configuration> <cloneProjectsTo>${project.build.directory}/it </cloneProjectsTo> <settingsFile>src/it/settings.xml</settingsFile> <addTestClassPath>true</addTestClassPath> <streamLogs>true</streamLogs> </configuration> </execution> </executions> </plugin> </plugins> <pluginManagement> <plugins> <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <pluginExecution> <pluginExecutionFilter> <groupId> org.apache.maven.plugins </groupId> <artifactId> maven-invoker-plugin </artifactId> <versionRange> [3.0.1,) </versionRange> <goals> <goal>run</goal> </goals> </pluginExecutionFilter> <action> <ignore></ignore> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin> </plugins> </pluginManagement> </build> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>path_to_url </repository> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>path_to_url <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>path_to_url </pluginRepository> <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>path_to_url <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> </project> ```
/content/code_sandbox/spring-cloud-function-deployer/pom.xml
xml
2016-09-22T02:34:34
2024-08-16T08:19:07
spring-cloud-function
spring-cloud/spring-cloud-function
1,032
1,245
```xml const commonParamsDef = ` $brandId: String!, $name: String!, $content: String, `; const commonParams = ` brandId: $brandId, name: $name, content: $content, `; const responseTemplatesAdd = ` mutation responseTemplatesAdd(${commonParamsDef}) { responseTemplatesAdd(${commonParams}) { _id } } `; const responseTemplatesEdit = ` mutation responseTemplatesEdit($_id: String!, ${commonParamsDef}) { responseTemplatesEdit(_id: $_id, ${commonParams}) { _id } } `; const responseTemplatesRemove = ` mutation responseTemplatesRemove($_id: String!) { responseTemplatesRemove(_id: $_id) } `; const responseTemplatesChangeStatus = ` mutation responseTemplatesChangeStatus($_id: String!, $status: String) { responseTemplatesChangeStatus(_id: $_id, status: $status) { _id } } `; export default { responseTemplatesAdd, responseTemplatesEdit, responseTemplatesRemove, responseTemplatesChangeStatus }; ```
/content/code_sandbox/packages/ui-inbox/src/settings/responseTemplates/graphql/mutations.ts
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
239
```xml import * as yargs from "yargs" import chalk from "chalk" import path from "path" import { PlatformTools } from "../platform/PlatformTools" import { CommandUtils } from "./CommandUtils" /** * Generates a new subscriber. */ export class SubscriberCreateCommand implements yargs.CommandModule { command = "subscriber:create <path>" describe = "Generates a new subscriber." builder(args: yargs.Argv) { return args.positional("path", { type: "string", describe: "Path of the subscriber file", demandOption: true, }) } async handler(args: yargs.Arguments) { try { const fullPath = (args.path as string).startsWith("/") ? (args.path as string) : path.resolve(process.cwd(), args.path as string) const filename = path.basename(fullPath) const fileContent = SubscriberCreateCommand.getTemplate(filename) const fileExists = await CommandUtils.fileExists(fullPath + ".ts") if (fileExists) { throw `File ${chalk.blue(fullPath + ".ts")} already exists` } await CommandUtils.createFile(fullPath + ".ts", fileContent) console.log( chalk.green( `Subscriber ${chalk.blue( fullPath, )} has been created successfully.`, ), ) } catch (err) { PlatformTools.logCmdErr("Error during subscriber creation:") process.exit(1) } } // your_sha256_hash--------- // Protected Static Methods // your_sha256_hash--------- /** * Gets contents of the entity file. */ protected static getTemplate(name: string): string { return `import { EventSubscriber, EntitySubscriberInterface } from "typeorm" @EventSubscriber() export class ${name} implements EntitySubscriberInterface { } ` } } ```
/content/code_sandbox/src/commands/SubscriberCreateCommand.ts
xml
2016-02-29T07:41:14
2024-08-16T18:28:52
typeorm
typeorm/typeorm
33,875
388
```xml import { isURLProtonInternal } from '@proton/components/helpers/url'; import { getAssistantModels } from '@proton/llm/lib/api'; import { ASSISTANT_CONTEXT_SIZE_LIMIT, GENERAL_STOP_STRINGS, STOP_STRINGS_WRITE_FULL_EMAIL, assistantAuthorizedApps, } from '@proton/llm/lib/constants'; import type { TransformCallback } from '@proton/llm/lib/formatPrompt'; import { formatPromptCustomRefine } from '@proton/llm/lib/formatPrompt'; import type { Action, AssistantModel, CustomRefineAction, IframeToParentMessage, OpenedAssistant, OpenedAssistantStatus, ParentToIframeMessage, } from '@proton/llm/lib/types'; import { isRefineActionType } from '@proton/llm/lib/types'; import { AssistantEvent } from '@proton/llm/lib/types'; import { GENERATION_TYPE, checkHardwareForAssistant } from '@proton/shared/lib/assistant'; import { isChromiumBased, isFirefox, isMobile } from '@proton/shared/lib/helpers/browser'; import { getApiSubdomainUrl } from '@proton/shared/lib/helpers/url'; import type { Api } from '@proton/shared/lib/interfaces'; import window from '@proton/shared/lib/window'; export const getAssistantHasCompatibleBrowser = () => { const isOnMobile = isMobile(); const isUsingCompatibleBrowser = isChromiumBased() || isFirefox(); return !isOnMobile && isUsingCompatibleBrowser; }; export const getAssistantHasCompatibleHardware = async () => { const compatibility = await checkHardwareForAssistant(); return compatibility; }; export const getGenerationType = (action: Action) => { switch (action.type) { case 'writeFullEmail': return GENERATION_TYPE.WRITE_FULL_EMAIL; case 'customRefine': return GENERATION_TYPE.CUSTOM_REFINE; case 'proofread': return GENERATION_TYPE.PROOFREAD; case 'shorten': return GENERATION_TYPE.SHORTEN; case 'formal': return GENERATION_TYPE.FORMALIZE; case 'friendly': return GENERATION_TYPE.FRIENDLY; case 'expand': return GENERATION_TYPE.EXPAND; default: return GENERATION_TYPE.WRITE_FULL_EMAIL; } }; export const getIsAssistantOpened = (openedAssistants: OpenedAssistant[], assistantID: string) => { return !!openedAssistants.find((assistant) => assistant.id === assistantID); }; export const getHasAssistantStatus = ( openedAssistants: OpenedAssistant[], assistantID: string, status: OpenedAssistantStatus ) => { return openedAssistants.find((assistant) => assistant.id === assistantID)?.status === status; }; export const checkHarmful = (inputText: string) => { /* The LLM starts generation of a text with a "yes" or "no" token that answers the question * "Harmful? (yes/no):". Therefore the LLM is telling us the prompt is harmful iff the text begins with "yes". */ return /^\s*yes/i.test(inputText); }; export function removeStopStrings(text: string, customStopStrings?: string[]) { customStopStrings ||= []; const stopStrings = [...GENERAL_STOP_STRINGS, ...customStopStrings]; const leftMostStopIdx: number | undefined = stopStrings .map((s) => text.indexOf(s)) .filter((idx) => idx >= 0) .reduce((minIdx, idx) => (minIdx === undefined ? idx : Math.min(minIdx, idx)), undefined as number | undefined); if (leftMostStopIdx !== undefined) { text = text.slice(0, leftMostStopIdx); } return text; } export function convertToDoubleNewlines(input: string): string { const lines = input.split('\n'); let paragraphs: string[][] = []; let paragraph: string[] = []; let inList = false; // we're currently in a list let listJustBegan = false; // marks that the next line will be a list for (let originalLine of lines) { const linePreserveStartSpace = originalLine.trimEnd(); const line = originalLine.trim(); if (!line) { paragraphs.push(paragraph); paragraph = []; continue; } const isListLine = /^(\d+[\.\)]|\-|\*|\|[a-zA-Z][\.\)]) /.test(line); inList = isListLine || listJustBegan; if (!inList) { paragraphs.push(paragraph); paragraph = []; } paragraph.push(inList ? linePreserveStartSpace : line); listJustBegan = line.endsWith(':'); } if (paragraph) { paragraphs.push(paragraph); } return paragraphs .map((lines) => lines.join('\n')) .join('\n\n') .replace(/\n{3,}/g, '\n\n'); } export function removePartialEndsWith(s: string, target: string): string { const n = target.length; if (n === 0) { return s; } for (let i = 1; i < n - 1; i++) { const subtarget = target.slice(0, i); if (s.endsWith(subtarget)) { s = s.slice(0, s.length - subtarget.length); break; } } return s; } export const makeTransformWriteFullEmail = (senderName?: string): TransformCallback => { return (inputText: string): string | undefined => { /* The LLM generates text that contains extraneous data, such as: * * - a token to tell if the prompt was harmful (yes/no) * - a subject (we drop it) * - a prefix "Body:" (we drop it) * - a signature "[Your Name]" (we replace it with the sender name) * * This method preprocesses the LLM generated text and return only the extracted email content without * the extraneous text. */ function isLast(i: number, lines: any[]) { return i + 1 === lines.length; } let text = inputText.trim(); // The LLM begins with an answer to the question: "Harmful? (yes/no):" // If the prompt is harmful, we do not let the text pass through. if (text.toLowerCase().startsWith('yes')) { return undefined; } // Remove stop strings and anything that come after. text = removeStopStrings(text, STOP_STRINGS_WRITE_FULL_EMAIL); // Split lines let lines = text.split('\n'); lines = lines.map((line) => line.trim()); // The LLM first line should be the reply to the harmful prompt ("no" or "No") // We drop this answer since it's not part of the actual email we want to generate. lines = lines.filter((_line, i) => i !== 0); // Drop the subject. // The LLM often wants to generate a subject line before the email content. We're not using it at // the moment, so we just get rid of this line altogether. lines = lines.filter((line) => !line.startsWith('Subject')); // Do not show a partially generated line, like "Subj" lines = lines.filter((line, i) => !isLast(i, lines) || !'Subject'.startsWith(line)); // Drop the "Body:" prefix, but keep the rest of the line. // Do not show a partially generated line, like "Bo" lines = lines.filter((line, i) => !isLast(i, lines) || !'Body:'.startsWith(line)); lines = lines.map((line) => line.replace(/^Body:\s*/, '')); // Drop spaces at the beginning of lines (not sure why it happens, but it does). lines = lines.map((line) => line.replace(/^ +/, '')); // Join back the lines into a string. We set newlines to 2 between paragraphs. let outputText = lines.join('\n').trim(); outputText = convertToDoubleNewlines(outputText); outputText = outputText.trim(); // Replace in-line instances of "[Your Name]" with the sender name. senderName = senderName?.trim(); if (senderName) { outputText = outputText.replaceAll('[Your Name]', senderName); // Hide a partial string like "[Your". outputText = removePartialEndsWith(outputText, '[Your Name]'); } return outputText; }; }; export const queryAssistantModels = async (api: Api) => { const models = await api(getAssistantModels()); return models.Models; }; export const isIncompleteModelURL = (url: string) => { try { new URL(url); return false; } catch { return true; } }; export const getModelURL = (url: string) => { // URL we get from the API can have different formats // 1- path_to_url // 2- /somePath/ndarray-cache.json // In the second case, we are trying to reach an internal url. We can add the window origin to it. const isIncompleteURL = isIncompleteModelURL(url); if (isIncompleteURL) { return new URL(url, window.location.origin); } return url; }; export const buildMLCConfig = (models: AssistantModel[]) => { // Get the model with the priority close to 0 const model = models.reduce((acc, model) => { return acc.Priority < model.Priority ? acc : model; }); if (model) { /** * The api return us the ModelURL which contains the url on which we will download the model => path_to_url * However, in we want to store files in the cache using the current url. * So we need to build the model_url in the assistant configuration with the same format path_to_url */ const modelURLDownloadURL = getModelURL(model.ModelURL).toString(); var modelLibURL = getModelURL(model.ModelLibURL).toString(); if (window.origin.includes('localhost')) { // The line below forces web-llm to grab the wasm from the cache (where we carefully placed it) // instead of fetching it itself. See: // path_to_url#L145 modelLibURL = modelLibURL.replace('localhost', 'LOCALHOST'); } // compute the model url with the needed format path_to_url const modelURL = `${window.origin}${new URL(modelURLDownloadURL).pathname}`; return { model_list: [ { model_url: `${window.origin}${new URL(modelURL).pathname}`, model_download_url: modelURLDownloadURL, model_id: model.ModelID, model_lib_url: modelLibURL, vram_required_MB: model.VRAMRequiredMB, low_resource_required: model.LowResourceRequired, required_features: model.RequiredFeatures, }, ], use_web_worker: true, }; } }; export class PromptRejectedError extends Error { constructor() { super(); this.name = 'PromptRejectedError'; if (Error.captureStackTrace) { Error.captureStackTrace(this, PromptRejectedError); } } } export const getAssistantIframeURL = () => { // If running the assistant iframe in localhost, use this instead: // return new URL('path_to_url // Else, forge the url on which the iframe html is available return getApiSubdomainUrl('/mail/v4/ai-assistant', window.location.origin).toString(); }; // Function used to validate events coming from the iframe. Are we actually receiving event from the assistant iframe? const isAuthorizedIframeAssistantURL = (url: string, hostname: string) => { try { const iframeURLString = getAssistantIframeURL(); const iframeURL = new URL(iframeURLString); const incomingURL = new URL(url); return isURLProtonInternal(url, hostname) && incomingURL.hostname === iframeURL.hostname; } catch { return false; } }; // Function used to validate events coming from iframe parent apps. Are we actually receiving event from authorized apps? const isAuthorizedAssistantAppURL = (url: string, hostname: string) => { try { const originURL = new URL(url); // Get subdomain of the url => e.g. mail, calendar, drive const appFromUrl = originURL.hostname.split('.')[0]; // In localhost, allow the app to send events to the iframe if (originURL.hostname === 'localhost') { return true; } // Else, check that // - The app url is internal // - The app sending an event is an authorized app return isURLProtonInternal(url, hostname) && assistantAuthorizedApps.includes(appFromUrl); } catch { return false; } }; // Function used to validate events assistant events export const isAssistantPostMessage = (event: MessageEvent, hostname = window.location.hostname) => { const origin = event.origin; if (!origin || origin === 'null') { return false; } const isIframeURL = isAuthorizedIframeAssistantURL(origin, hostname); const isAssistantAppURL = isAuthorizedAssistantAppURL(origin, hostname); const isValidURL = isIframeURL || isAssistantAppURL; // Check that the assistant event is a valid event based on // - The url of the event origin, is it an authorized url? // - Does the event contain a valid `ASSISTANT_EVENTS` return isValidURL && event.data && Object.values(AssistantEvent).includes(event.data.type); }; // Function used to post messages to the assistant iframe export const postMessageParentToIframe = (message: ParentToIframeMessage) => { const iframe = document.querySelector('[id^=assistant-iframe]') as HTMLIFrameElement | null; const assistantURL = getAssistantIframeURL(); iframe?.contentWindow?.postMessage(message, assistantURL); }; // Function used to post messages to the assistant iframe parent app export const postMessageIframeToParent = ( message: IframeToParentMessage, parentURL: string, arrayBuffers?: ArrayBuffer[] ) => { window.parent?.postMessage(message, parentURL, arrayBuffers || undefined); }; /* Model is not working well with more than ~10k chars. To avoid having users facing too many issues when sending * a prompt that is too big, we want to limit the prompt that we send to the model to 10k chars. * What we send to the model, the "full prompt" contains: * 1- The full message body, if any, when trying to refine a message * 2- The user prompt, if any * 3- The "system" instructions (where we say you're an assistant generating emails, etc...) * 4- In case of a selection refine, we have to trick the model. We are passing again the content that is before the selection, * so that he does not generate it again * * Because of all of this, we can compute the "full prompt" only when submitting a request. */ export const isPromptSizeValid = (action: Action) => { if (isRefineActionType(action.type)) { const modelPrompt = formatPromptCustomRefine(action as CustomRefineAction); return modelPrompt.length < ASSISTANT_CONTEXT_SIZE_LIMIT; } return true; }; ```
/content/code_sandbox/packages/llm/lib/helpers.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
3,365
```xml import * as path from "path"; import { CancellationToken, CodeLens, CodeLensProvider, commands, Event, EventEmitter, Range, TextDocument } from "vscode"; import { FlutterSdks, IAmDisposable, Logger } from "../../shared/interfaces"; import { disposeAll } from "../../shared/utils"; import { fsPath } from "../../shared/utils/fs"; import { LspClassOutlineVisitor } from "../../shared/utils/outline_lsp"; import { envUtils, lspToPosition, lspToRange } from "../../shared/vscode/utils"; import { LspAnalyzer } from "../analysis/analyzer_lsp"; const dartPadSamplePattern = new RegExp("\\{@tool\\s+dartpad"); export class LspFlutterDartPadSamplesCodeLensProvider implements CodeLensProvider, IAmDisposable { private disposables: IAmDisposable[] = []; private onDidChangeCodeLensesEmitter: EventEmitter<void> = new EventEmitter<void>(); public readonly onDidChangeCodeLenses: Event<void> = this.onDidChangeCodeLensesEmitter.event; private readonly flutterPackagesFolder: string; constructor(private readonly logger: Logger, private readonly analyzer: LspAnalyzer, private readonly sdks: FlutterSdks) { this.disposables.push(this.analyzer.fileTracker.onOutline(() => { this.onDidChangeCodeLensesEmitter.fire(); })); this.disposables.push(commands.registerCommand("_dart.openDartPadSample", async (sample: DartPadSampleInfo) => { // Link down to first code snippet. const fragment = `#${sample.libraryName}.${sample.className}.1`; const suffix = sample.elementKind === "MIXIN" ? "mixin" : sample.elementKind === "EXTENSION" ? "extension-type" : "class"; const url = `path_to_url{sample.libraryName}/${sample.className}-${suffix}.html${fragment}`; await envUtils.openInBrowser(url); })); this.flutterPackagesFolder = path.join(sdks.flutter, "packages/flutter/lib/src/").toLowerCase(); } public async provideCodeLenses(document: TextDocument, token: CancellationToken): Promise<CodeLens[] | undefined> { // Ensure this file is a Flutter package file. const filePath = fsPath(document.uri); if (!filePath.toLowerCase().startsWith(this.flutterPackagesFolder)) return; // Without version numbers, the best we have to tell if an outline is likely correct or stale is // if its length matches the document exactly. const expectedLength = document.getText().length; const outline = await this.analyzer.fileTracker.waitForOutlineWithLength(document, expectedLength, token); if (!outline || !outline.children || !outline.children.length) return; const libraryName = filePath.substr(this.flutterPackagesFolder.length).replace("\\", "/").split("/")[0]; const visitor = new LspClassOutlineVisitor(this.logger); visitor.visit(outline); // Filter classes to those with DartPad samples. const samples = visitor.classes.filter((cl) => { // HACK: DartDocs are between the main offset and codeOffset. const docs = document.getText(new Range(lspToPosition(cl.range.start), lspToPosition(cl.codeRange.start))); return dartPadSamplePattern.test(docs); }).map((cl) => ({ ...cl, libraryName })); return samples .filter((sample) => sample.codeRange) .map((sample) => new CodeLens( lspToRange(sample.codeRange), { arguments: [sample], command: "_dart.openDartPadSample", title: `Open online interactive samples for ${sample.className}`, }, )); } public dispose(): any { disposeAll(this.disposables); } } export interface DartPadSampleInfo { libraryName: string; className: string; elementKind: string; offset: number; length: number; } ```
/content/code_sandbox/src/extension/code_lens/flutter_dartpad_samples_lsp.ts
xml
2016-07-30T13:49:11
2024-08-10T16:23:15
Dart-Code
Dart-Code/Dart-Code
1,472
828
```xml <?xml version="1.0" encoding="UTF-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2"> <file source-language="de" target-language="de-CH" datatype="plaintext" original="messages.en.xlf"> <body> <trans-unit id="wCazS.X" resname="action.close"> <source>action.close</source> <target>Schliessen</target> </trans-unit> <trans-unit id="EO57yXg" resname="invoice.tax"> <source>invoice.tax</source> <target>Mehrwertsteuer</target> </trans-unit> <trans-unit id="UoOv6mx" resname="menu.homepage"> <source>menu.homepage</source> <target state="translated">Dashboard</target> </trans-unit> <trans-unit id="aq59Sk8" resname="api_token_repeat"> <source>api_token_repeat</source> <target>API-Passwort wiederholen</target> </trans-unit> <trans-unit id="T4nAM7X" resname="api_token"> <source>api_token</source> <target>API-Passwort</target> </trans-unit> <trans-unit id="WMJwy8r" resname="invoice_tax_number"> <source>invoice_tax_number</source> <target>Mehrwertsteuer-ID-Nr.:</target> </trans-unit> <trans-unit id="EJDS9HY" resname="vat_id"> <source>vat_id</source> <target>Mehrwertsteuer-ID</target> </trans-unit> <trans-unit id="fFErSLq" resname="vat"> <source>vat</source> <target>Mehrwertsteuer</target> </trans-unit> <trans-unit id="DYHuW58" resname="confirm.delete"> <source>confirm.delete</source> <target>Wollen Sie es wirklich lschen?</target> </trans-unit> <trans-unit id="XP5zkiN" resname="modal.dirty"> <source>modal.dirty</source> <target>Das Formular wurde gendert. Bitte klicken Sie Speichern, um die nderungen zu sichern oder Schliessen, um abzubrechen.</target> </trans-unit> <trans-unit id="9Wt8Pp_" resname="help.batch_meta_fields"> <source>help.batch_meta_fields</source> <target>Felder die aktualisiert werden sollen, mssen zunchst durch einen Klick auf die zugehrige Checkbox freigeschaltet werden.</target> </trans-unit> <trans-unit id="8BPmHPa" resname="batch_meta_fields"> <source>batch_meta_fields</source> <target>Zustzliche Felder</target> </trans-unit> <trans-unit id="NNsA8i2" resname="globalsOnly"> <source>globalsOnly</source> <target>Nur globale</target> </trans-unit> <trans-unit id="qtjPKUT" resname="export.mark_all"> <source>export.mark_all</source> <target>Alle angezeigten Eintrge als abgerechnet markieren?</target> </trans-unit> <trans-unit id="BhsaLxX" resname="export.clear_all"> <source>export.clear_all</source> <target>Alle angezeigten Eintrge als offen markieren?</target> </trans-unit> <trans-unit id="spHpd_I" resname="entryState.stopped"> <source>entryState.stopped</source> <target>Beendete</target> </trans-unit> <trans-unit id="xm7mqoK" resname="entryState.running"> <source>entryState.running</source> <target>Laufende</target> </trans-unit> <trans-unit id="XvXvA2S" resname="all"> <source>all</source> <target>Alle</target> </trans-unit> <trans-unit id="ccCiXyR" resname="entryState.not_exported"> <source>entryState.not_exported</source> <target>Offen</target> </trans-unit> <trans-unit id="_DDecAV" resname="entryState.exported"> <source>entryState.exported</source> <target>Abgerechnet</target> </trans-unit> <trans-unit id="Qn2ouiL" resname="exported"> <source>exported</source> <target>Exportiert</target> </trans-unit> <trans-unit id="cjgNYUB" resname="entryState"> <source>entryState</source> <target>Zeiten</target> </trans-unit> <trans-unit id="igCkqAP" resname="pageSize"> <source>pageSize</source> <target>Ergebnisse</target> </trans-unit> <trans-unit id="dTHY7Mw" resname="timesheet.start"> <source>timesheet.start</source> <target state="needs-translation">Neue Zeitmessung starten</target> </trans-unit> <trans-unit id="WVU_S.A" resname="recent.activities"> <source>recent.activities</source> <target state="translated">Eine Ihrer letzten Ttigkeiten neu starten</target> </trans-unit> <trans-unit id="OxdYMR3" resname="active.entries"> <source>active.entries</source> <target>Ihre aktiven Zeitmessungen</target> </trans-unit> <trans-unit id="vKY0tof" resname="export.date_copyright"> <source>export.date_copyright</source> <target>Erstellt %date% mit %kimai%</target> </trans-unit> <trans-unit id="ElDyzrx" resname="export.page_of"> <source>export.page_of</source> <target>Seite %page% von %pages%</target> </trans-unit> <trans-unit id="N778uJ6" resname="export.summary"> <source>export.summary</source> <target>Zusammenfassung</target> </trans-unit> <trans-unit id="d5wyWRD" resname="export.full_list"> <source>export.full_list</source> <target>Vollstndige Auflistung</target> </trans-unit> <trans-unit id="3CQ7A2m" resname="export.document_title"> <source>export.document_title</source> <target>Export von Zeiten</target> </trans-unit> <trans-unit id="vjmoQGo" resname="export.period"> <source>export.period</source> <target>Zeitraum</target> </trans-unit> <trans-unit id="iwWaUoa" resname="export.filter"> <source>export.filter</source> <target>Daten fr Export filtern</target> </trans-unit> <trans-unit id="1GruCMx" resname="export"> <source>export</source> <target>Export</target> </trans-unit> <trans-unit id="PHJwR4w" resname="status.paid"> <source>status.paid</source> <target>Bezahlt</target> </trans-unit> <trans-unit id="Uvo1CbP" resname="status.pending"> <source>status.pending</source> <target>Ausstehend</target> </trans-unit> <trans-unit id="X_NRsed" resname="status.new"> <source>status.new</source> <target>Neu</target> </trans-unit> <trans-unit id="BzwWNMS" resname="status"> <source>status</source> <target>Status</target> </trans-unit> <trans-unit id="lswYe8s" resname="invoice_bank_account"> <source>invoice_bank_account</source> <target>Bankverbindung</target> </trans-unit> <trans-unit id="tCNBGKG" resname="orderDate"> <source>orderDate</source> <target>Bestelldatum</target> </trans-unit> <trans-unit id="3tegKgk" resname="orderNumber"> <source>orderNumber</source> <target>Bestellnummer</target> </trans-unit> <trans-unit id="c3d6p33" resname="invoice.total_working_time"> <source>invoice.total_working_time</source> <target>Gesamtdauer</target> </trans-unit> <trans-unit id="Q9ykNhO" resname="invoice.signature_customer"> <source>invoice.signature_customer</source> <target>Leistungsbesttigung: Datum / Name Kunde / Unterschrift</target> </trans-unit> <trans-unit id="9p2KQag" resname="invoice.signature_user"> <source>invoice.signature_user</source> <target>Leistungsbesttigung: Datum / Name Berater / Unterschrift</target> </trans-unit> <trans-unit id="033t0aO" resname="payment_terms"> <source>payment_terms</source> <target>Zahlungsinformationen</target> </trans-unit> <trans-unit id="IoKfYkz" resname="unit_price"> <source>unit_price</source> <target>Einzelbetrag</target> </trans-unit> <trans-unit id="BAkWQqr" resname="total_rate"> <source>total_rate</source> <target>Gesamtpreis</target> </trans-unit> <trans-unit id="zzjZXJx" resname="amount"> <source>amount</source> <target>Anzahl</target> </trans-unit> <trans-unit id="TPzFWUs" resname="invoice.service_date"> <source>invoice.service_date</source> <target>Leistungsdatum</target> </trans-unit> <trans-unit id="N68vyvo" resname="invoice.total"> <source>invoice.total</source> <target>Rechnungsendbetrag</target> </trans-unit> <trans-unit id="86KyrKO" resname="invoice.subtotal"> <source>invoice.subtotal</source> <target>Rechnungsbetrag (netto)</target> </trans-unit> <trans-unit id="x_W5sV4" resname="invoice.number"> <source>invoice.number</source> <target>Rechnungsnummer</target> </trans-unit> <trans-unit id="hx7vsMA" resname="invoice.to"> <source>invoice.to</source> <target>An</target> </trans-unit> <trans-unit id="4XKFnWh" resname="invoice.from"> <source>invoice.from</source> <target>Von</target> </trans-unit> <trans-unit id="rAJrxSK" resname="invoice.due_days"> <source>invoice.due_days</source> <target>Zahlungsziel</target> </trans-unit> <trans-unit id="ohNu8DK" resname="due_days"> <source>due_days</source> <target>Zahlungsziel in Tagen</target> </trans-unit> <trans-unit id="XN4PEpj" resname="template"> <source>template</source> <target>Vorlage</target> </trans-unit> <trans-unit id="dicW36D" resname="mark_as_exported"> <source>mark_as_exported</source> <target>Als exportiert markieren</target> </trans-unit> <trans-unit id="zPcx3O_" resname="invoice_print"> <source>invoice_print</source> <target>Rechnung</target> </trans-unit> <trans-unit id="ulYFDIo" resname="button.ods"> <source>button.ods</source> <target>ODS</target> </trans-unit> <trans-unit id="aAa5uRR" resname="button.pdf"> <source>button.pdf</source> <target>PDF</target> </trans-unit> <trans-unit id="vC2IsaP" resname="button.xlsx"> <source>button.xlsx</source> <target>Excel</target> </trans-unit> <trans-unit id="W_TXvSi" resname="button.csv"> <source>button.csv</source> <target>CSV</target> </trans-unit> <trans-unit id="X70dwP8" resname="button.print"> <source>button.print</source> <target>Drucken</target> </trans-unit> <trans-unit id="WXXPG7p" resname="preview"> <source>preview</source> <target>Vorschau</target> </trans-unit> <trans-unit id="ov4OQOh" resname="invoice.filter"> <source>invoice.filter</source> <target>Rechnungsdaten filtern</target> </trans-unit> <trans-unit id="SR2r1Cs" resname="invoices"> <source>invoices</source> <target>Rechnungen</target> </trans-unit> <trans-unit id="Oq.KtC6" resname="admin_invoice_template.title"> <source>admin_invoice_template.title</source> <target>Vorlagen</target> </trans-unit> <trans-unit id="HkjvwLc" resname="stats.percentUsedLeft"> <source>stats.percentUsedLeft</source> <target>%percent%% verwendet (noch %left% offen)</target> </trans-unit> <trans-unit id="unC5MXv" resname="stats.percentUsed"> <source>stats.percentUsed</source> <target>%percent%% verwendet</target> </trans-unit> <trans-unit id="xN7MfSA" resname="stats.percentUsed_month"> <source>stats.percentUsed_month</source> <target>%percent%% verwendet diesen Monat</target> </trans-unit> <trans-unit id="vWJPpYU" resname="stats.percentUsedLeft_month"> <source>stats.percentUsedLeft_month</source> <target>%percent%% verwendet (noch %left% diesen Monat offen)</target> </trans-unit> <trans-unit id="tnD6aPj" resname="stats.customerTotal"> <source>stats.customerTotal</source> <target>Anzahl Kunden</target> </trans-unit> <trans-unit id="67uSaR3" resname="stats.projectTotal"> <source>stats.projectTotal</source> <target>Anzahl Projekte</target> </trans-unit> <trans-unit id="Bor.76M" resname="stats.activityTotal"> <source>stats.activityTotal</source> <target>Anzahl Ttigkeiten</target> </trans-unit> <trans-unit id="t5eIWp8" resname="stats.userTotal"> <source>stats.userTotal</source> <target>Anzahl Benutzer</target> </trans-unit> <trans-unit id="lEW82ex" resname="stats.activeRecordings"> <source>stats.activeRecordings</source> <target>Aktive Zeitmessungen</target> </trans-unit> <trans-unit id="8FFVmiv" resname="stats.activeUsersTotal"> <source>stats.activeUsersTotal</source> <target>Aktive Benutzer jemals</target> </trans-unit> <trans-unit id="lGuZo7g" resname="stats.activeUsersYear"> <source>stats.activeUsersYear</source> <target>Aktive Benutzer dieses Jahr</target> </trans-unit> <trans-unit id="40xQ.Qt" resname="stats.activeUsersMonth"> <source>stats.activeUsersMonth</source> <target>Aktive Benutzer diesen Monat</target> </trans-unit> <trans-unit id="7oP64Kh" resname="stats.activeUsersWeek"> <source>stats.activeUsersWeek</source> <target>Aktive Benutzer diese Woche</target> </trans-unit> <trans-unit id="HzICegM" resname="stats.activeUsersToday"> <source>stats.activeUsersToday</source> <target>Aktive Benutzer heute</target> </trans-unit> <trans-unit id="Z0fz23v" resname="stats.amountTotal"> <source>stats.amountTotal</source> <target>Umsatz total</target> </trans-unit> <trans-unit id="bQZyZaO" resname="stats.amountYear"> <source>stats.amountYear</source> <target>Umsatz dieses Jahr</target> </trans-unit> <trans-unit id="ulr3reE" resname="stats.amountMonth"> <source>stats.amountMonth</source> <target>Umsatz diesen Monat</target> </trans-unit> <trans-unit id="xnJvYAE" resname="stats.amountWeek"> <source>stats.amountWeek</source> <target>Umsatz diese Woche</target> </trans-unit> <trans-unit id="023M9Ta" resname="stats.amountToday"> <source>stats.amountToday</source> <target>Umsatz heute</target> </trans-unit> <trans-unit id="IFOLMgp" resname="stats.yourWorkingHours"> <source>stats.yourWorkingHours</source> <target>Meine Arbeitszeiten</target> </trans-unit> <trans-unit id="YtvPnl1" resname="stats.durationTotal"> <source>stats.durationTotal</source> <target>Arbeitszeit total</target> </trans-unit> <trans-unit id="WqF84KR" resname="stats.durationYear"> <source>stats.durationYear</source> <target>Arbeitszeit dieses Jahr</target> </trans-unit> <trans-unit id="uaOwf_P" resname="stats.durationMonth"> <source>stats.durationMonth</source> <target>Arbeitszeit diesen Monat</target> </trans-unit> <trans-unit id="XhKalZH" resname="stats.durationWeek"> <source>stats.durationWeek</source> <target>Arbeitszeit diese Woche</target> </trans-unit> <trans-unit id="TdBJBAl" resname="stats.durationToday"> <source>stats.durationToday</source> <target>Arbeitszeit heute</target> </trans-unit> <trans-unit id="JnUFsNi" resname="stats.workingTimeYear"> <source>stats.workingTimeYear</source> <target>Gesamtes Jahr %year%</target> </trans-unit> <trans-unit id="JIKNAYP" resname="stats.workingTimeMonth"> <source>stats.workingTimeMonth</source> <target>%month% %year%</target> </trans-unit> <trans-unit id="XdYs3I8" resname="stats.workingTimeWeek"> <source>stats.workingTimeWeek</source> <target>Kalenderwoche %week%</target> </trans-unit> <trans-unit id="lfSTZGe" resname="stats.workingTimeToday"> <source>stats.workingTimeToday</source> <target>Heute, %day%</target> </trans-unit> <trans-unit id="rvO5ZXf" resname="ROLE_USER"> <source>ROLE_USER</source> <target>Benutzer</target> </trans-unit> <trans-unit id="yttGLAB" resname="ROLE_TEAMLEAD"> <source>ROLE_TEAMLEAD</source> <target>Teamleiter</target> </trans-unit> <trans-unit id="718iPw6" resname="ROLE_ADMIN"> <source>ROLE_ADMIN</source> <target>Administrator</target> </trans-unit> <trans-unit id="WRuKTcz" resname="ROLE_SUPER_ADMIN"> <source>ROLE_SUPER_ADMIN</source> <target>System-Admin</target> </trans-unit> <trans-unit id="XKTzhQz" resname="version"> <source>version</source> <target>Version</target> </trans-unit> <trans-unit id="E7G60OF" resname="Allowed character: A-Z and _"> <source>Allowed character: A-Z and _</source> <target>Erlaubte Zeichen: A-Z und _</target> </trans-unit> <trans-unit id="G.GEdlk" resname="user_role.title"> <source>user_role.title</source> <target>Benutzer Rolle</target> </trans-unit> <trans-unit id="ZlZ20pG" resname="user_permissions.title"> <source>user_permissions.title</source> <target>Benutzer Berechtigungen</target> </trans-unit> <trans-unit id="Zs9VE7N" resname="roles"> <source>roles</source> <target>Rolle</target> </trans-unit> <trans-unit id="loeWEWU" resname="active"> <source>active</source> <target>Aktiv</target> </trans-unit> <trans-unit id="h7voece" resname="avatar"> <source>avatar</source> <target>Profilbild (URL)</target> </trans-unit> <trans-unit id="qvIyBkY" resname="title"> <source>title</source> <target>Titel</target> </trans-unit> <trans-unit id="GgpqNso" resname="alias"> <source>alias</source> <target>Name</target> </trans-unit> <trans-unit id="Rm5bnNV" resname="currency"> <source>currency</source> <target>Whrung</target> </trans-unit> <trans-unit id="OWLt7pw" resname="timezone"> <source>timezone</source> <target>Zeitzone</target> </trans-unit> <trans-unit id="pcWhXux" resname="homepage"> <source>homepage</source> <target>Homepage</target> </trans-unit> <trans-unit id="1STBoIE" resname="mobile"> <source>mobile</source> <target>Handy</target> </trans-unit> <trans-unit id="SvTiF8B" resname="fax"> <source>fax</source> <target>Fax</target> </trans-unit> <trans-unit id="RVadpX9" resname="phone"> <source>phone</source> <target>Telefon</target> </trans-unit> <trans-unit id="r.ZOT9U" resname="country"> <source>country</source> <target>Land</target> </trans-unit> <trans-unit id="2Ayb_RD" resname="address"> <source>address</source> <target>Adresse</target> </trans-unit> <trans-unit id="CT59X9u" resname="contact" approved="yes"> <source>Contact</source> <target state="final">Kontakt</target> </trans-unit> <trans-unit id="8WjM3ZF" resname="company"> <source>company</source> <target>Unternehmensbezeichnung</target> </trans-unit> <trans-unit id="EohvnQA" resname="number"> <source>number</source> <target>Kundennummer</target> </trans-unit> <trans-unit id="TBWoUYf" resname="project_end"> <source>project_end</source> <target>Projekt Ende</target> </trans-unit> <trans-unit id="Xyjr.V." resname="project_start"> <source>project_start</source> <target>Projekt Start</target> </trans-unit> <trans-unit id="UVJ5Die" resname="calendar"> <source>calendar</source> <target>Kalender</target> </trans-unit> <trans-unit id="7zptTeh" resname="update_browser_title"> <source>update_browser_title</source> <target>Browser Titel aktualisieren</target> </trans-unit> <trans-unit id="dherSTU" resname="export_decimal"> <source>export_decimal</source> <target>Dezimal Format fr Export nutzen</target> </trans-unit> <trans-unit id="r49TNAg" resname="daily_stats"> <source>daily_stats</source> <target>Tgliche Statistiken im Timesheet anzeigen</target> </trans-unit> <trans-unit id="Q0Zip02" resname="agendaDay"> <source>agendaDay</source> <target>Tag</target> </trans-unit> <trans-unit id="Irm6dfx" resname="agendaWeek"> <source>agendaWeek</source> <target>Woche</target> </trans-unit> <trans-unit id="pcfRcZ4" resname="month"> <source>month</source> <target>Monat</target> </trans-unit> <trans-unit id="gRIArHS" resname="lastLogin"> <source>lastLogin</source> <target>Letzte Anmeldung</target> </trans-unit> <trans-unit id="H.IqJTQ" resname="login_initial_view"> <source>login_initial_view</source> <target>Initiale Ansicht nach Anmeldung</target> </trans-unit> <trans-unit id="j4Kd9N1" resname="calendar_initial_view"> <source>calendar_initial_view</source> <target>Initiale Darstellung des Kalenders</target> </trans-unit> <trans-unit id="MQKiG33" resname="profile.preferences"> <source>profile.preferences</source> <target>Einstellungen</target> </trans-unit> <trans-unit id="ygtTz8." resname="profile.roles"> <source>profile.roles</source> <target>Rollen</target> </trans-unit> <trans-unit id="Z34ZpjK" resname="profile.api-token"> <source>profile.api-token</source> <target>API Zugang</target> </trans-unit> <trans-unit id="A6TLLQa" resname="profile.password"> <source>profile.password</source> <target>Passwort</target> </trans-unit> <trans-unit id="xEYQXPy" resname="profile.settings"> <source>profile.settings</source> <target>Profil</target> </trans-unit> <trans-unit id="1c0EQaz" resname="profile.registration_date"> <source>profile.registration_date</source> <target>Registriert am</target> </trans-unit> <trans-unit id="Fm.kwVn" resname="profile.first_entry"> <source>profile.first_entry</source> <target>Arbeitet seit</target> </trans-unit> <trans-unit id="HWKJZ0T" resname="profile.about_me"> <source>profile.about_me</source> <target>ber mich</target> </trans-unit> <trans-unit id="1_wnK76" resname="profile.title"> <source>profile.title</source> <target>Benutzerprofil</target> </trans-unit> <trans-unit id="rlJLVNm" resname="append"> <source>append</source> <target>Hinzufgen</target> </trans-unit> <trans-unit id="erN3h3b" resname="replace"> <source>replace</source> <target>Ersetzen</target> </trans-unit> <trans-unit id="dChNncv" resname="color"> <source>color</source> <target>Farbe</target> </trans-unit> <trans-unit id="b43sCwO" resname="help.fixedRate"> <source>help.fixedRate</source> <target>Jeder Eintrag bekommt den gleichen Preis, unabhngig von seiner Dauer</target> </trans-unit> <trans-unit id="_0tuMNE" resname="fixedRate"> <source>fixedRate</source> <target>Festpreis</target> </trans-unit> <trans-unit id="UbnqJLn" resname="modal.columns.title"> <source>modal.columns.title</source> <target>ndere Spalten-Sichtbarkeit</target> </trans-unit> <trans-unit id="iNOVZRh" resname="daterange"> <source>daterange</source> <target>Zeitraum</target> </trans-unit> <trans-unit id="Nh5I0DC" resname="end"> <source>end</source> <target>Bis</target> </trans-unit> <trans-unit id="5vB9Q7X" resname="begin"> <source>begin</source> <target>Von</target> </trans-unit> <trans-unit id="dwEVXUR" resname="timesheet.edit"> <source>timesheet.edit</source> <target>Eintrag bearbeiten</target> </trans-unit> <trans-unit id="VXj0Y3h" resname="timesheet.title"> <source>timesheet.title</source> <target>Meine Zeiten</target> </trans-unit> <trans-unit id="tfkKlua" resname="progress"> <source>progress</source> <target>Fortschritt</target> </trans-unit> <trans-unit id="Ia0kvPi" resname="my_team_projects"> <source>my_team_projects</source> <target>Meine Projekte</target> </trans-unit> <trans-unit id="L05Qw2x" resname="my_teams"> <source>my_teams</source> <target>Meine Teams</target> </trans-unit> <trans-unit id="muzkQpM" resname="toggle_dropdown"> <source>toggle_dropdown</source> <target>Men anzeigen</target> </trans-unit> <trans-unit id="3bqLM8Q" resname="dashboard.title"> <source>dashboard.title</source> <target>Dashboard</target> </trans-unit> <trans-unit id="tKZKI2Z" resname="action.reset"> <source>action.reset</source> <target>Zurcksetzen</target> </trans-unit> <trans-unit id="HLtdhYw" resname="action.save"> <source>action.save</source> <target>Speichern</target> </trans-unit> <trans-unit id="YZdZVQP" resname="delete"> <source>action.delete</source> <target>Lschen</target> </trans-unit> <trans-unit id="ovKkXwU" resname="action.edit"> <source>action.edit</source> <target>Bearbeiten</target> </trans-unit> <trans-unit id="Kw3N1AA" resname="actions"> <source>actions</source> <target>Aktionen</target> </trans-unit> <trans-unit id="aVwNQcX" resname="billable"> <source>billable</source> <target>Abrechenbar</target> </trans-unit> <trans-unit id="LIOnolg" resname="placeholder.type_message"> <source>placeholder.type_message</source> <target>Schreibe deine Nachricht</target> </trans-unit> <trans-unit id="evFI7nW" resname="teamlead"> <source>teamlead</source> <target>Teamleiter</target> </trans-unit> <trans-unit id="yosi0Nu" resname="team"> <source>team</source> <target>Team</target> </trans-unit> <trans-unit id="giREF.l" resname="email"> <source>email</source> <target>E-Mail</target> </trans-unit> <trans-unit id="tsRYY4d" resname="customer"> <source>customer</source> <target>Kunde</target> </trans-unit> <trans-unit id="pO8wS6Q" resname="language"> <source>language</source> <target>Sprache</target> </trans-unit> <trans-unit id="Qc5nsFn" resname="recalculate_rates"> <source>recalculate_rates</source> <target>Preise neu berechnen</target> </trans-unit> <trans-unit id="Cxv_0wG" resname="help.internalRate"> <source>help.internalRate</source> <target>Wenn dieser nicht angegeben ist, wird der normale Preis verwendet</target> </trans-unit> <trans-unit id="5ofAsOs" resname="internalRate"> <source>internalRate</source> <target>Interner Preis</target> </trans-unit> <trans-unit id="djL6LMC" resname="help.rate"> <source>help.rate</source> <target>Zu berechnender Preis pro Stunde bzw. pro Eintrag bei Festpreisen</target> </trans-unit> <trans-unit id="xUl3nXn" resname="rate"> <source>rate</source> <target>Preis</target> </trans-unit> <trans-unit id="QEMUsfS" resname="hours"> <source>hours</source> <target>Stunden</target> </trans-unit> <trans-unit id="HcWuW2g" resname="layout"> <source>layout</source> <target>Darstellung: Layout</target> </trans-unit> <trans-unit id="KgBw0BS" resname="skin"> <source>skin</source> <target>Design</target> </trans-unit> <trans-unit id="E_bHhGR" resname="hourlyRate"> <source>hourlyRate</source> <target>Preis pro Stunde</target> </trans-unit> <trans-unit id="l4wviUE" resname="tags"> <source>tags</source> <target>Schlagworte</target> </trans-unit> <trans-unit id="KhBzpuZ" resname="tag"> <source>tag</source> <target>Schlagworte</target> </trans-unit> <trans-unit id="JEIQ5IQ" resname="project"> <source>project</source> <target>Projekt</target> </trans-unit> <trans-unit id="BlGGO.X" resname="activity"> <source>activity</source> <target>Ttigkeit</target> </trans-unit> <trans-unit id="qbD0dHa" resname="timeBudget"> <source>timeBudget</source> <target>Zeit-Budget</target> </trans-unit> <trans-unit id="CvlqjtY" resname="budget"> <source>budget</source> <target>Budget</target> </trans-unit> <trans-unit id="1C7xSXk" resname="visible"> <source>visible</source> <target>Sichtbar</target> </trans-unit> <trans-unit id="pWFFJwz" resname="id"> <source>id</source> <target>ID</target> </trans-unit> <trans-unit id="xEuy.VF" resname="comment"> <source>comment</source> <target>Kommentar</target> </trans-unit> <trans-unit id="gqNTf.D" resname="name"> <source>name</source> <target>Name</target> </trans-unit> <trans-unit id="yQRveje" resname="description"> <source>Description</source> <target state="translated">Beschreibung</target> </trans-unit> <trans-unit id="FveKfWM" resname="username"> <source>username</source> <target>Benutzer</target> </trans-unit> <trans-unit id="BPiZbad" resname="user"> <source>user</source> <target>Benutzer</target> </trans-unit> <trans-unit id="yqea9Nt" resname="duration"> <source>duration</source> <target>Dauer</target> </trans-unit> <trans-unit id="eI_tMbq" resname="endtime"> <source>endtime</source> <target>Ende</target> </trans-unit> <trans-unit id="BHk4pZ3" resname="starttime"> <source>starttime</source> <target>Beginn</target> </trans-unit> <trans-unit id="DodjLNR" resname="date"> <source>date</source> <target>Datum</target> </trans-unit> <trans-unit id="hlu4iX5" resname="error.no_comments_found"> <source>error.no_comments_found</source> <target>Es wurden noch keine Kommentare abgegeben.</target> </trans-unit> <trans-unit id="Vz3Igj3" resname="error.no_entries_found"> <source>error.no_entries_found</source> <target>Anhand ihrer ausgewhlten Filter wurden keine Eintrge gefunden.</target> </trans-unit> <trans-unit id="JGaf9IK" resname="Doctor"> <source>Doctor</source> <target>Doktor</target> </trans-unit> <trans-unit id="IXtkHRw" resname="menu.system_configuration"> <source>menu.system_configuration</source> <target>Einstellungen</target> </trans-unit> <trans-unit id="hOZxcaK" resname="menu.plugin"> <source>menu.plugin</source> <target>Erweiterungen</target> </trans-unit> <trans-unit id="_t.2z4V" resname="teams"> <source>teams</source> <target>Teams</target> </trans-unit> <trans-unit id="fftM9nd" resname="users"> <source>users</source> <target>Benutzer</target> </trans-unit> <trans-unit id="YkyVVAY" resname="activities"> <source>activities</source> <target>Ttigkeiten</target> </trans-unit> <trans-unit id="JXfA9Ve" resname="projects"> <source>projects</source> <target>Projekte</target> </trans-unit> <trans-unit id="IeshU90" resname="customers"> <source>customers</source> <target>Kunden</target> </trans-unit> <trans-unit id="yxQop43" resname="all_times"> <source>all_times</source> <target>Zeiterfassung</target> </trans-unit> <trans-unit id="ypVQO7o" resname="menu.reporting"> <source>menu.reporting</source> <target>Berichte</target> </trans-unit> <trans-unit id="ebTjBb9" resname="my_times"> <source>my_times</source> <target>Meine Zeiten</target> </trans-unit> <trans-unit id="wBTFKFR" resname="menu.logout"> <source>menu.logout</source> <target>Abmelden</target> </trans-unit> <trans-unit id="6OKwCUB" resname="menu.system"> <source>menu.system</source> <target>System</target> </trans-unit> <trans-unit id="wvvYSw_" resname="menu.admin"> <source>menu.admin</source> <target>Administration</target> </trans-unit> <trans-unit id=".372.o7" resname="login_required"> <source>login_required</source> <target>Fehlende Berechtigung. Zur Anmeldung wechseln?</target> </trans-unit> <trans-unit id="_x2He8M" resname="user_profile"> <source>user_profile</source> <target>Mein Profil</target> </trans-unit> <trans-unit id="ACcM9j_" resname="logout"> <source>logout</source> <target>Abmelden</target> </trans-unit> <trans-unit id="hLEZkoC" resname="password_repeat"> <source>password_repeat</source> <target>Passwort wiederholen</target> </trans-unit> <trans-unit id="XohImNo" resname="password" approved="yes"> <source>Password</source> <target state="final">Passwort</target> </trans-unit> <trans-unit id="zFfl7jw" resname="sum.total"> <source>sum.total</source> <target>Gesamt</target> </trans-unit> <trans-unit id="mflwMcX" resname="rates.title"> <source>rates.title</source> <target>Preise</target> </trans-unit> <trans-unit id="0M_Gylq" resname="rates.empty"> <source>rates.empty</source> <target>Es wurden noch keine Preise hinterlegt.</target> </trans-unit> <trans-unit id="OTDmccn" resname="attachments"> <source>attachments</source> <target>Dateien</target> </trans-unit> <trans-unit id="J258iS6" resname="update_multiple"> <source>update_multiple</source> <target>%action% von %count% Eintrgen?</target> </trans-unit> <trans-unit id="hBNESu6" resname="my.profile"> <source>my.profile</source> <target>Mein Profil</target> </trans-unit> <trans-unit id="JBkykGe" resname="search"> <source>search</source> <target>Suchen</target> </trans-unit> <trans-unit id=".0CFrRV" resname="upload"> <source>upload</source> <target>Hochladen</target> </trans-unit> <trans-unit id="PyZ8KrQ" resname="confirm"> <source>confirm</source> <target>Besttigen</target> </trans-unit> <trans-unit id="I3TZF5S" resname="cancel"> <source>cancel</source> <target>Abbrechen</target> </trans-unit> <trans-unit id="COyxNde" resname="delete.not_in_use"> <source>delete.not_in_use</source> <target>Dieses Element kann sicher gelscht werden.</target> </trans-unit> <trans-unit id="vDd3alC" resname="admin_entity.delete_confirm"> <source>admin_entity.delete_confirm</source> <target>Diese Daten werden ebenfalls gelscht! Alternativ knnen Sie einen Eintrag auswhlen, auf den alle existierenden Daten umgebucht werden:</target> </trans-unit> <trans-unit id="_ohHsMM" resname="create"> <source>create</source> <target>Erstellen</target> </trans-unit> <trans-unit id="KLIuHvt" resname="This is a mandatory field"> <source>This is a mandatory field</source> <target>Pflichtfeld</target> </trans-unit> <trans-unit id=".3dyBTq" resname="both"> <source>both</source> <target>Beides</target> </trans-unit> <trans-unit id="k5Apjz_" resname="no"> <source>no</source> <target>Nein</target> </trans-unit> <trans-unit id="inmIkP6" resname="yes"> <source>yes</source> <target>Ja</target> </trans-unit> <trans-unit id="N7mikjJ" resname="time_tracking" xml:space="preserve"> <source>Time Tracking</source> <target state="translated">Zeiterfassung</target> </trans-unit> <trans-unit id="L0hRlcf" resname="includeNoBudget"> <source>includeNoBudget</source> <target>Eintrge ohne Budget anzeigen</target> </trans-unit> <trans-unit id="L27KvC9" resname="includeNoWork"> <source>includeNoWork</source> <target>Eintrge ohne Buchungen anzeigen</target> </trans-unit> <trans-unit id="qX_CKtU" resname="tax_rate"> <source>tax_rate</source> <target>Steuersatz</target> </trans-unit> <trans-unit id="O5w1jzb" resname="file"> <source>file</source> <target>Datei</target> </trans-unit> <trans-unit id="o0yOFHL" resname="not_invoiced"> <source>not_invoiced</source> <target>Nicht abgerechnet</target> </trans-unit> <trans-unit id="2dm.ZWM" resname="not_exported"> <source>not_exported</source> <target>Nicht exportiert</target> </trans-unit> <trans-unit id="crrlEUA" resname="preview.skipped_rows"> <source>preview.skipped_rows</source> <target>berspringe Vorschau von %rows% weiteren Zeilen </target> </trans-unit> <trans-unit id="Xij3oQl" resname="invoice.payment_date"> <source>invoice.payment_date</source> <target>Zahlungsdatum</target> </trans-unit> <trans-unit id="VSo_gmO" resname="orderBy"> <source>orderBy</source> <target>Sortieren nach</target> </trans-unit> <trans-unit id="l4ZOh4." resname="desc"> <source>desc</source> <target>Absteigend</target> </trans-unit> <trans-unit id="1o0.9vf" resname="asc"> <source>asc</source> <target>Aufsteigend</target> </trans-unit> <trans-unit id="CiA4s9E" resname="set_as_default"> <source>set_as_default</source> <target>Einstellung als Suchfavorit speichern</target> </trans-unit> <trans-unit id="8W_TZI0" resname="searchTerm"> <source>searchTerm</source> <target>Suchbegriff</target> </trans-unit> <trans-unit id="DUDrvjk" resname="remove_default"> <source>remove_default</source> <target>Suchfavorit lschen</target> </trans-unit> <trans-unit id="_YiKaOT" resname="last_record"> <source>last_record</source> <target>Letzter Eintrag</target> </trans-unit> <trans-unit id="vpqPF8v" resname="last_record_before"> <source>last_record_before</source> <target>Keine Zeitbuchung seit</target> </trans-unit> <trans-unit id="_Pym9RO" resname="stats.activeUsersFinancialYear"> <source>stats.activeUsersFinancialYear</source> <target>Aktive Benutzer dieses Geschftsjahr</target> </trans-unit> <trans-unit id="wuUWovn" resname="stats.amountFinancialYear"> <source>stats.amountFinancialYear</source> <target>Umsatz dieses Geschftsjahr</target> </trans-unit> <trans-unit id="xkugSAA" resname="stats.durationFinancialYear"> <source>stats.durationFinancialYear</source> <target>Arbeitszeit dieses Geschftsjahr</target> </trans-unit> <trans-unit id="HWB4OGJ" resname="stats.workingTimeFinancialYear"> <source>stats.workingTimeFinancialYear</source> <target>Geschftsjahr</target> </trans-unit> <trans-unit id=".ndupSK" resname="registration.check_email"> <source>registration.check_email</source> <target>Eine E-Mail wurde an %email% gesendet. Diese enthlt einen Link, den Sie anklicken mssen, um Ihr Benutzerkonto zu besttigen.</target> </trans-unit> <trans-unit id="_cY.wHP" resname="resetting.check_email" xml:space="preserve"> <source>An email has been sent with a link to reset your password. Note: You can only request a new password once every %tokenLifetime% hours. If you don't receive the email, please check your spam folder or try again.</source> <target state="needs-translation">Eine E-Mail wurde verschickt. Diese beinhaltet einen Link zum Zurcksetzen des Passwortes. Hinweis: Ein neues Passwort kann nur alle %tokenLifetime% Stunden beantragt werden. Eventuell wurde diese E-Mail als Spam markiert, wenn sie nicht angekommen ist.</target> </trans-unit> <trans-unit id="XQ2.pq2" resname="error.too_many_entries"> <source>error.too_many_entries</source> <target>Die Anfrage konnte nicht verarbeitet werden. Es wurden zu viele Ergebnisse gefunden.</target> </trans-unit> <trans-unit id="BXBFJP8" resname="stats.workingTime" xml:space="preserve"> <source>Working hours</source> <target>Arbeitszeit</target> </trans-unit> <trans-unit id="pX_3dNm" resname="stats.revenue"> <source>stats.revenue</source> <target>Einnahmen</target> </trans-unit> <trans-unit id="4Ndj7Xo" resname="budgetType"> <source>budgetType</source> <target>Budget-Typ</target> </trans-unit> <trans-unit id="wYqyL6A" resname="budgetType_month"> <source>budgetType_month</source> <target>Monatlich</target> </trans-unit> <trans-unit id="tvV0NhL" resname="delete_warning.short_stats"> <source>delete_warning.short_stats</source> <target>Momentan existieren insgesamt %records% Zeiteintrge, welche sich auf eine Gesamtdauer von %duration% belaufen.</target> </trans-unit> <trans-unit id="EwPAaws" resname="type"> <source>type</source> <target>Typ</target> </trans-unit> <trans-unit id="W92QGbY" resname="export.warn_result_amount"> <source>export.warn_result_amount</source> <target>Ihre Suche fhrt zu %count% Ergebnissen. Sollte der Export fehlschlagen, mssen Sie die Suche weiter eingrenzen.</target> </trans-unit> <trans-unit id="KH2hgil" resname="account_number"> <source>account_number</source> <target>Personalnummer</target> </trans-unit> <trans-unit id="Zif614Q" resname="add_user.label"> <source>add_user.label</source> <target>Benutzer hinzufgen</target> </trans-unit> <trans-unit id="tp.gIrE" resname="team.add_user.help"> <source>team.add_user.help</source> <target>Durch Auswahl wird dem Team ein neuer Benutzer hinzugefgt. Sie knnen im Anschluss festlegen, ob der Benutzer ein Teamleiter sein soll.</target> </trans-unit> <trans-unit id="yNWIi5U" resname="default_value_new"> <source>default_value_new</source> <target>Standard Wert fr neue Eintrge</target> </trans-unit> <trans-unit id="jdbtx6z" resname="action.add"> <source>action.add</source> <target>Hinzufgen</target> </trans-unit> <trans-unit id="f8oNzSP" resname="quick_entry.title"> <source>quick_entry.title</source> <target>Wochenstunden</target> </trans-unit> <trans-unit id="ViUuILv" resname="includeBudgetType_month"> <source>includeBudgetType_month</source> <target>Eintrge mit Monats-Budget anzeigen</target> </trans-unit> <trans-unit id="KukrzcT" resname="includeBudgetType_full"> <source>includeBudgetType_full</source> <target>Eintrge mit Lebenszyklus-Budget anzeigen</target> </trans-unit> <trans-unit id="dnQEYoJ" resname="budgetType_full"> <source>budgetType_full</source> <target>Lebenszyklus</target> </trans-unit> <trans-unit id="gT9W2pZ" resname="status.canceled"> <source>status.canceled</source> <target>Storniert</target> </trans-unit> <trans-unit id="GzWKgBk" resname="error.directory_missing"> <source>The directory %dir% does not exist and could not be created.</source> <target>Das Verzeichnis %dir% existiert nicht und konnte auch nicht erstellt werden.</target> </trans-unit> <trans-unit id="C2TGff0" resname="error.directory_protected"> <source>error.directory_protected</source> <target>Das Verzeichnis %dir% ist schreibgeschtzt.</target> </trans-unit> <trans-unit id="HPhRbtc" resname="stats.workingTimeWeekShort"> <source>stats.workingTimeWeekShort</source> <target state="translated">Woche %week%</target> </trans-unit> <trans-unit id="fVA3M2x" resname="choice_pattern"> <source>Display of entries in selection lists</source> <target state="translated">Darstellung der Eintrge in Auswahllisten</target> </trans-unit> <trans-unit id="nlwMf5w" resname="invoice_document.max_reached"> <source>invoice_document.max_reached</source> <target state="translated">Maximale Anzahl von %max% Rechnungsdokumenten erreicht. Um weitere hinzufgen mssen Sie zunchst eins lschen.</target> </trans-unit> <trans-unit id="IPHM4iP" resname="updated_at"> <source>Updated at</source> <target state="translated">Aktualisiert am</target> </trans-unit> <trans-unit id="U_D.NIy" resname="automatic"> <source>automatic</source> <target>Automatisch</target> </trans-unit> <trans-unit id="OJ.wI1U" resname="invoiceText"> <source>invoiceText</source> <target state="translated">Rechnungstext</target> </trans-unit> <trans-unit id="3Clo55j" resname="about.title"> <source>about.title</source> <target>ber Kimai</target> </trans-unit> <trans-unit id="1MfS6X5" resname="remove_filter"> <source>remove_filter</source> <target state="translated">Suchfilter zurcksetzen</target> </trans-unit> <trans-unit id="nqEYrfk" resname="security.unlock.intro"> <source>security.unlock.intro</source> <target state="translated">Bitte geben Sie, fr den vollen Zugriff, ihr Passwort ein</target> </trans-unit> <trans-unit id="fQ3Prt4" resname="security.unlock.title"> <source>security.unlock.title</source> <target state="translated">Benutzerkonto entsperren</target> </trans-unit> <trans-unit id="853W5Iu" resname="security.unlock.button"> <source>security.unlock.button</source> <target state="translated">Entsperren</target> </trans-unit> <trans-unit id="Eq2E_Rd" resname="menu.apps"> <source>Apps</source> <target state="translated">Anwendungen</target> </trans-unit> <trans-unit id="3rJ5QDP" resname="help.teams"> <source>help.teams</source> <target state="translated">Sichtbarkeit auf ausgewhlte Teams einschrnken.</target> </trans-unit> <trans-unit id="EGpYQvx" resname="help"> <source>help</source> <target state="translated">Dokumentation</target> </trans-unit> <trans-unit id="oYYDCG5" resname="support"> <source>Support</source> <target state="translated">Support</target> </trans-unit> <trans-unit id="mz4ieCN" resname="donate"> <source>donate</source> <target state="translated">Spenden</target> </trans-unit> <trans-unit id="cR5DD88" resname="invoice_number_generator.date"> <source>invoice_number_generator.date</source> <target state="translated">Datum</target> </trans-unit> <trans-unit id="Qh1X4Vu" resname="invoice_number_generator.default"> <source>invoice_number_generator.default</source> <target state="translated">Konfiguriertes Format</target> </trans-unit> <trans-unit id="UI6nPeP" resname="invoice_number_generator"> <source>invoice_number_generator</source> <target state="translated">Rechnungsnummern-Generator</target> </trans-unit> </body> </file> </xliff> ```
/content/code_sandbox/translations/messages.de_CH.xlf
xml
2016-10-20T17:06:34
2024-08-16T18:27:30
kimai
kimai/kimai
3,084
13,556
```xml import {RemoteGitHubV4Entity} from '../../Type/RemoteGitHubV4/RemoteGitHubV4Entity'; import {TimerUtil} from '../../Util/TimerUtil'; import {Logger} from '../../Infra/Logger'; export type PartialError = { message: string; type?: 'NOT_FOUND' | 'FORBIDDEN' | string; }; export class GitHubV4Client { private readonly options: RequestInit; private readonly apiEndPoint: string; protected readonly gheVersion: string; protected readonly isGitHubCom: boolean; constructor(accessToken: string, host: string, https: boolean, gheVersion: string) { if (!accessToken || !host) { console.error('invalid access token or host'); throw new Error('invalid access token or host'); } this.isGitHubCom = host === 'api.github.com'; const pathPrefix = this.isGitHubCom ? '' : 'api/'; this.gheVersion = this.isGitHubCom ? '' : gheVersion; this.apiEndPoint = `http${https ? 's' : ''}://${host}/${pathPrefix}graphql`; this.options = { method: 'POST', headers: { 'Authorization': `bearer ${accessToken}`, }, }; } protected async request<T extends RemoteGitHubV4Entity>(query: string): Promise<{error?: Error; data?: T; statusCode?: number; headers?: Headers; partialErrors?: PartialError[]}> { this.options.body = this.buildRequestBody(query); try { const res = await fetch(this.apiEndPoint, this.options); if (res.status !== 200) { const errorText = await res.text(); Logger.error(GitHubV4Client.name, `request error`, {error: new Error(errorText), statusCode: res.status}); return {error: new Error(errorText), statusCode: res.status} } const body = await res.json() as {data: T, errors?: PartialError[]}; if (body.errors) { Logger.error(GitHubV4Client.name, `response has errors`, { errors: body.errors.map(e => ({message: e.message, type: e.type})) }); const allNotFound = body.errors.every(error => error.type === 'NOT_FOUND' || error.type === 'FORBIDDEN'); if (allNotFound) { // partial success } else { return {error: new Error(body.errors[0]?.message), statusCode: res.status}; } } const data = body.data; await this.waitRateLimit(data); return {data, statusCode: res.status, headers: res.headers, partialErrors: body.errors ?? []}; } catch(e) { Logger.error(GitHubV4Client.name, `request error`, {error: e, errorMessage: e.message}); return {error: e}; } } private buildRequestBody(query: string): string { const graphqlQuery = QUERY_TEMPLATE.replace(`__QUERY__`, query); return JSON.stringify({query: graphqlQuery}); } private async waitRateLimit(data: RemoteGitHubV4Entity) { // GHErateLimit if (!data.rateLimit) return; if (data.rateLimit.remaining > 0) return; const resetAtMillSec = new Date(data.rateLimit.resetAt).getTime(); const waitMillSec = resetAtMillSec - Date.now(); Logger.warning(GitHubV4Client.name, 'rate limit', {resetSec: waitMillSec / 1000}); await TimerUtil.sleep(waitMillSec); } } const QUERY_TEMPLATE = ` query { __QUERY__ rateLimit { limit cost remaining resetAt } } `; ```
/content/code_sandbox/src/Renderer/Library/GitHub/V4/GitHubV4Client.ts
xml
2016-05-10T12:55:31
2024-08-11T04:32:50
jasper
jasperapp/jasper
1,318
795
```xml import { z, IntegrationDefinitionProps } from '@botpress/sdk' export { actions } from './actions' export { events } from './events' export { channels } from './channels' export const configuration = { schema: z.object({ owner: z.string().min(1), repo: z.string().min(1), token: z.string().min(1), }), } satisfies IntegrationDefinitionProps['configuration'] export const user = { tags: { id: {}, }, } satisfies IntegrationDefinitionProps['user'] export const states = { configuration: { type: 'integration', schema: z.object({ webhookSecret: z.string().optional(), webhookId: z.number().optional(), botUserId: z.number().optional(), }), }, } satisfies IntegrationDefinitionProps['states'] ```
/content/code_sandbox/integrations/github/src/definitions/index.ts
xml
2016-11-16T21:57:59
2024-08-16T18:45:35
botpress
botpress/botpress
12,401
173
```xml import React, { type FC, Fragment, useState } from 'react'; import { Button, Heading, Tab, TabList, TabPanel, Tabs, ToggleButton } from 'react-aria-components'; import { useParams, useRouteLoaderData } from 'react-router-dom'; import { useLocalStorage } from 'react-use'; import { getContentTypeFromHeaders } from '../../../common/constants'; import * as models from '../../../models'; import { queryAllWorkspaceUrls } from '../../../models/helpers/query-all-workspace-urls'; import { getCombinedPathParametersFromUrl, type RequestParameter } from '../../../models/request'; import type { Settings } from '../../../models/settings'; import { getAuthObjectOrNull } from '../../../network/authentication'; import { deconstructQueryStringToParams, extractQueryStringFromUrl } from '../../../utils/url/querystring'; import { useRequestPatcher, useSettingsPatcher } from '../../hooks/use-request'; import { useActiveRequestSyncVCSVersion, useGitVCSVersion } from '../../hooks/use-vcs-version'; import type { RequestLoaderData } from '../../routes/request'; import type { WorkspaceLoaderData } from '../../routes/workspace'; import { OneLineEditor } from '../codemirror/one-line-editor'; import { AuthWrapper } from '../editors/auth/auth-wrapper'; import { BodyEditor } from '../editors/body/body-editor'; import { readOnlyHttpPairs, RequestHeadersEditor } from '../editors/request-headers-editor'; import { RequestParametersEditor } from '../editors/request-parameters-editor'; import { RequestScriptEditor } from '../editors/request-script-editor'; import { ErrorBoundary } from '../error-boundary'; import { Icon } from '../icon'; import { MarkdownEditor } from '../markdown-editor'; import { RequestSettingsModal } from '../modals/request-settings-modal'; import { RenderedQueryString } from '../rendered-query-string'; import { RequestUrlBar } from '../request-url-bar'; import { Pane, PaneHeader } from './pane'; import { PlaceholderRequestPane } from './placeholder-request-pane'; interface Props { environmentId: string; settings: Settings; onPaste: (text: string) => void; } export const RequestPane: FC<Props> = ({ environmentId, settings, onPaste, }) => { const { activeRequest, activeRequestMeta } = useRouteLoaderData('request/:requestId') as RequestLoaderData; const { workspaceId, requestId } = useParams() as { workspaceId: string; requestId: string }; const patchSettings = useSettingsPatcher(); const [isRequestSettingsModalOpen, setIsRequestSettingsModalOpen] = useState(false); const patchRequest = useRequestPatcher(); const [dismissPathParameterTip, setDismissPathParameterTip] = useLocalStorage('dismissPathParameterTip', ''); const handleImportQueryFromUrl = () => { let query; try { query = extractQueryStringFromUrl(activeRequest.url); } catch (error) { console.warn('Failed to parse url to import querystring'); return; } // Remove the search string (?foo=bar&...) from the Url const url = activeRequest.url.replace(`?${query}`, ''); const parameters = [ ...activeRequest.parameters, ...deconstructQueryStringToParams(query), ]; // Only update if url changed if (url !== activeRequest.url) { patchRequest(requestId, { url, parameters }); } }; const gitVersion = useGitVCSVersion(); const activeRequestSyncVersion = useActiveRequestSyncVCSVersion(); const { activeEnvironment } = useRouteLoaderData( ':workspaceId', ) as WorkspaceLoaderData; // Force re-render when we switch requests, the environment gets modified, or the (Git|Sync)VCS version changes const uniqueKey = `${activeEnvironment?.modified}::${requestId}::${gitVersion}::${activeRequestSyncVersion}::${activeRequestMeta?.activeResponseId}`; if (!activeRequest) { return <PlaceholderRequestPane />; } const pathParameters = getCombinedPathParametersFromUrl(activeRequest.url, activeRequest.pathParameters || []); const onPathParameterChange = (pathParameters: RequestParameter[]) => { patchRequest(requestId, { pathParameters }); }; const parametersCount = pathParameters.length + activeRequest.parameters.filter(p => !p.disabled).length; const headersCount = activeRequest.headers.filter(h => !h.disabled).length + readOnlyHttpPairs.length; const urlHasQueryParameters = activeRequest.url.indexOf('?') >= 0; const contentType = getContentTypeFromHeaders(activeRequest.headers) || activeRequest.body.mimeType; const isBodyEmpty = Boolean(typeof activeRequest.body.mimeType !== 'string' && !activeRequest.body.text); const requestAuth = getAuthObjectOrNull(activeRequest.authentication); const isNoneOrInherited = requestAuth?.type === 'none' || requestAuth === null; return ( <Pane type="request"> <PaneHeader> <ErrorBoundary errorClassName="font-error pad text-center"> <RequestUrlBar key={requestId} uniquenessKey={uniqueKey} handleAutocompleteUrls={() => queryAllWorkspaceUrls(workspaceId, models.request.type, requestId)} nunjucksPowerUserMode={settings.nunjucksPowerUserMode} onPaste={onPaste} /> </ErrorBoundary> </PaneHeader> <Tabs aria-label='Request pane tabs' className="flex-1 w-full h-full flex flex-col"> <TabList className='w-full flex-shrink-0 overflow-x-auto border-solid scro border-b border-b-[--hl-md] bg-[--color-bg] flex items-center h-[--line-height-sm]' aria-label='Request pane tabs'> <Tab className='flex-shrink-0 h-full flex items-center justify-between cursor-pointer gap-2 outline-none select-none px-3 py-1 text-[--hl] aria-selected:text-[--color-font] hover:bg-[--hl-sm] hover:text-[--color-font] aria-selected:bg-[--hl-xs] aria-selected:focus:bg-[--hl-sm] aria-selected:hover:bg-[--hl-sm] focus:bg-[--hl-sm] transition-colors duration-300' id='params' > <span>Params</span> {parametersCount > 0 && ( <span className='p-1 min-w-6 h-6 flex items-center justify-center text-xs rounded-lg border border-solid border-[--hl]'> {parametersCount} </span> )} </Tab> <Tab className='flex-shrink-0 h-full flex items-center justify-between cursor-pointer gap-2 outline-none select-none px-3 py-1 text-[--hl] aria-selected:text-[--color-font] hover:bg-[--hl-sm] hover:text-[--color-font] aria-selected:bg-[--hl-xs] aria-selected:focus:bg-[--hl-sm] aria-selected:hover:bg-[--hl-sm] focus:bg-[--hl-sm] transition-colors duration-300' id='content-type' > <span>Body</span> {!isBodyEmpty && ( <span className='p-1 min-w-6 h-6 flex items-center justify-center text-xs rounded-lg border border-solid border-[--hl]'> <span className='w-2 h-2 bg-green-500 rounded-full' /> </span> )} </Tab> <Tab className='flex-shrink-0 h-full flex items-center justify-between cursor-pointer gap-2 outline-none select-none px-3 py-1 text-[--hl] aria-selected:text-[--color-font] hover:bg-[--hl-sm] hover:text-[--color-font] aria-selected:bg-[--hl-xs] aria-selected:focus:bg-[--hl-sm] aria-selected:hover:bg-[--hl-sm] focus:bg-[--hl-sm] transition-colors duration-300' id='auth' > <span>Auth</span> {!isNoneOrInherited && ( <span className='p-1 min-w-6 h-6 flex items-center justify-center text-xs rounded-lg border border-solid border-[--hl]'> <span className='w-2 h-2 bg-green-500 rounded-full' /> </span> )} </Tab> <Tab className='flex-shrink-0 h-full flex items-center justify-between cursor-pointer gap-2 outline-none select-none px-3 py-1 text-[--hl] aria-selected:text-[--color-font] hover:bg-[--hl-sm] hover:text-[--color-font] aria-selected:bg-[--hl-xs] aria-selected:focus:bg-[--hl-sm] aria-selected:hover:bg-[--hl-sm] focus:bg-[--hl-sm] transition-colors duration-300' id='headers' > <span>Headers</span> {headersCount > 0 && ( <span className='p-1 min-w-6 h-6 flex items-center justify-center text-xs rounded-lg border border-solid border-[--hl]'> {headersCount} </span> )} </Tab> <Tab className='flex-shrink-0 h-full flex items-center justify-between cursor-pointer gap-2 outline-none select-none px-3 py-1 text-[--hl] aria-selected:text-[--color-font] hover:bg-[--hl-sm] hover:text-[--color-font] aria-selected:bg-[--hl-xs] aria-selected:focus:bg-[--hl-sm] aria-selected:hover:bg-[--hl-sm] focus:bg-[--hl-sm] transition-colors duration-300' id='scripts' > <span>Scripts</span> {Boolean(activeRequest.preRequestScript || activeRequest.afterResponseScript) && ( <span className='p-1 min-w-6 h-6 flex items-center justify-center text-xs rounded-lg border border-solid border-[--hl]'> <span className='w-2 h-2 bg-green-500 rounded-full' /> </span> )} </Tab> <Tab className='flex-shrink-0 h-full flex items-center justify-between cursor-pointer gap-2 outline-none select-none px-3 py-1 text-[--hl] aria-selected:text-[--color-font] hover:bg-[--hl-sm] hover:text-[--color-font] aria-selected:bg-[--hl-xs] aria-selected:focus:bg-[--hl-sm] aria-selected:hover:bg-[--hl-sm] focus:bg-[--hl-sm] transition-colors duration-300' id='docs' > <span>Docs</span> {activeRequest.description && ( <span className='p-1 min-w-6 h-6 flex items-center justify-center text-xs rounded-lg border border-solid border-[--hl]'> <span className='w-2 h-2 bg-green-500 rounded-full' /> </span> )} </Tab> </TabList> <TabPanel className='w-full flex-1 flex flex-col h-full overflow-y-auto' id='params'> <div className="p-4 flex-shrink-0"> <div className="text-xs max-h-32 flex flex-col overflow-y-auto min-h-[2em] bg-[--hl-xs] px-2 py-1 border border-solid border-[--hl-sm]"> <label className="label--small no-pad-top">Url Preview</label> <ErrorBoundary key={uniqueKey} errorClassName="tall wide vertically-align font-error pad text-center" > <RenderedQueryString request={activeRequest} /> </ErrorBoundary> </div> </div> <div className="flex-shrink-0 grid flex-1 [grid-template-rows:minmax(auto,min-content)] [grid-template-columns:100%] overflow-hidden"> <div className="min-h-[2rem] max-h-full flex flex-col overflow-y-auto [&_.key-value-editor]:p-0 flex-1"> <div className='flex items-center w-full p-4 h-4 justify-between'> <Heading className='text-xs font-bold uppercase text-[--hl]'>Query parameters</Heading> <div className='flex items-center gap-2'> <Button isDisabled={!urlHasQueryParameters} onPress={handleImportQueryFromUrl} className="w-[14ch] flex flex-shrink-0 gap-2 items-center justify-start px-2 py-1 h-full asma-pressed:bg-[--hl-sm] aria-selected:bg-[--hl-xs] aria-selected:focus:bg-[--hl-sm] aria-selected:hover:bg-[--hl-sm] focus:bg-[--hl-sm] rounded-sm text-[--color-font] hover:bg-[--hl-xs] focus:ring-inset ring-1 ring-transparent focus:ring-[--hl-md] transition-colors text-sm" > Import from URL </Button> <ToggleButton onChange={isSelected => { patchSettings({ useBulkParametersEditor: isSelected, }); }} isSelected={settings.useBulkParametersEditor} className="w-[14ch] flex flex-shrink-0 gap-2 items-center justify-start px-2 py-1 h-full rounded-sm text-[--color-font] hover:bg-[--hl-xs] focus:ring-inset ring-1 ring-transparent focus:ring-[--hl-md] transition-colors text-sm" > {({ isSelected }) => ( <Fragment> <Icon icon={isSelected ? 'toggle-on' : 'toggle-off'} className={`${isSelected ? 'text-[--color-success]' : ''}`} /> <span>{ isSelected ? 'Regular Edit' : 'Bulk Edit' }</span> </Fragment> )} </ToggleButton> </div> </div> <ErrorBoundary key={uniqueKey} errorClassName="tall wide vertically-align font-error pad text-center" > <RequestParametersEditor key={contentType} bulk={settings.useBulkParametersEditor} /> </ErrorBoundary> </div> <div className='flex-1 flex flex-col gap-4 p-4 overflow-y-auto'> <Heading className='text-xs font-bold uppercase text-[--hl]'>Path parameters</Heading> {pathParameters.length > 0 && ( <div className="pr-[72.73px] w-full"> <div className='grid gap-x-[20.8px] grid-cols-2 flex-shrink-0 w-full rounded-sm overflow-hidden'> {pathParameters.map(pathParameter => ( <Fragment key={pathParameter.name}> <span className='p-2 select-none border-b border-solid border-[--hl-md] truncate flex items-center justify-end rounded-sm'> {pathParameter.name} </span> <div className='px-2 flex items-center h-full border-b border-solid border-[--hl-md]'> <OneLineEditor key={activeRequest._id} id={'key-value-editor__name' + pathParameter.name} placeholder="Parameter value" defaultValue={pathParameter.value || ''} onChange={name => { onPathParameterChange(pathParameters.map(p => p.name === pathParameter.name ? { ...p, value: name } : p)); }} /> </div> </Fragment> ))} </div> </div> )} {pathParameters.length === 0 && !dismissPathParameterTip && ( <div className='text-sm text-[--hl] rounded-sm border border-solid border-[--hl-md] p-2 flex items-center gap-2'> <Icon icon='info-circle' /> <span>Path parameters are url path segments that start with a colon ':' e.g. ':id' </span> <Button className="flex flex-shrink-0 items-center justify-center aspect-square h-6 aria-pressed:bg-[--hl-sm] rounded-sm text-[--color-font] hover:bg-[--hl-xs] ml-auto" onPress={() => setDismissPathParameterTip('true')} > <Icon icon='close' /> </Button> </div> )} </div> </div> </TabPanel> <TabPanel className='w-full flex-1 flex flex-col' id='content-type'> <BodyEditor key={uniqueKey} request={activeRequest} environmentId={environmentId} /> </TabPanel> <TabPanel className='w-full flex-1 flex flex-col overflow-hidden' id='auth'> <ErrorBoundary key={uniqueKey} errorClassName="font-error pad text-center" > <AuthWrapper authentication={activeRequest.authentication} /> </ErrorBoundary> </TabPanel> <TabPanel className='w-full flex-1 flex flex-col relative overflow-hidden' id='headers'> <ErrorBoundary key={uniqueKey} errorClassName="font-error pad text-center" > <div className='overflow-y-auto flex-1 flex-shrink-0'> <RequestHeadersEditor bulk={settings.useBulkHeaderEditor} headers={activeRequest.headers} requestType="Request" /> </div> </ErrorBoundary> <div className="flex flex-row border-solid border-t border-[var(--hl-md)] h-[var(--line-height-sm)] text-[var(--font-size-sm)] box-border"> <Button className="px-4 py-1 h-full flex items-center justify-center gap-2 aria-pressed:bg-[--hl-sm] text-[--color-font] text-xs hover:bg-[--hl-xs] focus:ring-inset ring-1 ring-transparent focus:ring-[--hl-md] transition-colors" onPress={() => patchSettings({ useBulkHeaderEditor: !settings.useBulkHeaderEditor, }) } > {settings.useBulkHeaderEditor ? 'Regular Edit' : 'Bulk Edit'} </Button> </div> </TabPanel> <TabPanel className='w-full flex-1' id='scripts'> <Tabs className="w-full h-full flex flex-col overflow-hidden"> <TabList className="w-full flex-shrink-0 overflow-x-auto border-solid border-b border-b-[--hl-md] px-2 bg-[--color-bg] flex items-center gap-2 h-[--line-height-sm]" aria-label="Request scripts tabs"> <Tab className="rounded-md flex-shrink-0 h-[--line-height-xxs] text-sm flex items-center justify-between cursor-pointer w-[10.5rem] outline-none select-none px-2 py-1 hover:bg-[rgba(var(--color-surprise-rgb),50%)] text-[--hl] aria-selected:text-[--color-font-surprise] hover:text-[--color-font-surprise] aria-selected:bg-[rgba(var(--color-surprise-rgb),40%)] transition-colors duration-300" id="pre-request" > <div className='flex flex-1 items-center gap-2'> <Icon icon="arrow-right-to-bracket" /> <span>Pre-request</span> </div> {Boolean(activeRequest.preRequestScript) && ( <span className="p-2 rounded-lg"> <span className="flex w-2 h-2 bg-green-500 rounded-full" /> </span> )} </Tab> <Tab className="rounded-md flex-shrink-0 h-[--line-height-xxs] text-sm flex items-center justify-between cursor-pointer w-[10.5rem] outline-none select-none px-2 py-1 hover:bg-[rgba(var(--color-surprise-rgb),50%)] text-[--hl] aria-selected:text-[--color-font-surprise] hover:text-[--color-font-surprise] aria-selected:bg-[rgba(var(--color-surprise-rgb),40%)] transition-colors duration-300" id="after-response" > <div className='flex flex-1 items-center gap-2'> <Icon icon="arrow-right-from-bracket" /> <span>After-response</span> </div> {Boolean(activeRequest.afterResponseScript) && ( <span className="p-2 rounded-lg"> <span className="flex w-2 h-2 bg-green-500 rounded-full" /> </span> )} </Tab> </TabList> <TabPanel className="w-full flex-1" id='pre-request'> <ErrorBoundary key={uniqueKey} errorClassName="tall wide vertically-align font-error pad text-center" > <RequestScriptEditor uniquenessKey={`${activeRequest._id}:pre-request-script`} defaultValue={activeRequest.preRequestScript || ''} onChange={preRequestScript => patchRequest(requestId, { preRequestScript })} settings={settings} /> </ErrorBoundary> </TabPanel> <TabPanel className="w-full flex-1" id="after-response"> <ErrorBoundary key={uniqueKey} errorClassName="tall wide vertically-align font-error pad text-center" > <RequestScriptEditor uniquenessKey={`${activeRequest._id}:after-response-script`} defaultValue={activeRequest.afterResponseScript || ''} onChange={afterResponseScript => patchRequest(requestId, { afterResponseScript })} settings={settings} /> </ErrorBoundary> </TabPanel> </Tabs> </TabPanel> <TabPanel className='w-full flex-1 overflow-y-auto' id='docs'> <MarkdownEditor key={uniqueKey} placeholder="Write a description" defaultValue={activeRequest.description} onChange={(description: string) => patchRequest(requestId, { description })} /> </TabPanel> </Tabs> {isRequestSettingsModalOpen && ( <RequestSettingsModal request={activeRequest} onHide={() => setIsRequestSettingsModalOpen(false)} /> )} </Pane> ); }; ```
/content/code_sandbox/packages/insomnia/src/ui/components/panes/request-pane.tsx
xml
2016-04-23T03:54:26
2024-08-16T16:50:44
insomnia
Kong/insomnia
34,054
4,670
```xml import * as React from 'react'; import { Provider } from 'jotai'; import { EnhancedThemeProvider, } from '@pnp/spfx-controls-react/lib/EnhancedThemeProvider'; import { FlightTrackerControl } from './FlightTrackerControl'; import { IFlightTrackerProps } from './IFlightTrackerProps'; export const FlightTracker: React.FunctionComponent<IFlightTrackerProps> = ( props: React.PropsWithChildren<IFlightTrackerProps> ) => { const { currentTheme } = props; return ( <EnhancedThemeProvider context={props.context} theme={currentTheme}> <section> <Provider> <FlightTrackerControl {...props} /> </Provider> </section> </EnhancedThemeProvider> ); }; ```
/content/code_sandbox/samples/react-flighttracker/src/components/FlightTracker/FlightTracker.tsx
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
160
```xml import React, { FunctionComponent } from "react"; const CoralMarkIcon: FunctionComponent = () => { return ( <svg xmlns="path_to_url" viewBox="0 0 110 114"> <rect width="110" height="114" fill="currentColor" /> <g id="Frame 385"> <rect width="314" height="279" transform="translate(-86 -99)" fill="background" /> <g id="Logo_stacked_color (1) 1" clipPath="url(#clip0_0_1)"> <path id="Vector" d="M107.497 74.2702C106.599 73.8896 105.586 73.882 104.682 74.2492C103.778 74.6163 103.057 75.3282 102.677 76.2281C99.1381 84.6311 93.3523 91.8919 85.957 97.2103C78.5617 102.529 69.844 105.698 60.7652 106.369V97.4888C60.9657 97.0084 61.1921 96.5394 61.4435 96.0837C63.7428 91.9452 68.0308 89.588 72.9972 86.87C78.6495 83.7604 85.0567 80.2361 88.9692 73.2567C89.4331 72.4055 89.5434 71.4054 89.2761 70.4732C89.0089 69.5411 88.3856 68.752 87.5415 68.2772C86.6974 67.8023 85.7005 67.6799 84.7669 67.9365C83.8334 68.1932 83.0384 68.8081 82.5544 69.648C79.6726 74.7885 74.7101 77.5181 69.4564 80.3973C66.4789 82.0366 63.4477 83.7104 60.7652 85.8603V80.5547C60.7652 72.9765 65.7738 68.6537 72.112 63.1907C79.8374 56.5261 88.5899 48.9863 88.5899 33.8335C88.559 32.8772 88.1581 31.9703 87.472 31.3047C86.7858 30.6391 85.8681 30.267 84.913 30.267C83.9579 30.267 83.0402 30.6391 82.354 31.3047C81.6678 31.9703 81.2669 32.8772 81.2361 33.8335C81.2361 41.335 78.4809 46.4218 74.6297 50.7253C70.8666 45.5234 68.2531 38.7936 68.2531 33.8335C68.2531 32.8561 67.8655 31.9187 67.1756 31.2275C66.4857 30.5363 65.55 30.148 64.5743 30.148C63.5986 30.148 62.6629 30.5363 61.973 31.2275C61.2831 31.9187 60.8955 32.8561 60.8955 33.8335C60.8955 40.6824 64.2448 49.3011 69.2878 55.8889L67.3066 57.6088C63.5703 60.8297 59.7689 64.1159 57.0865 68.2199C54.404 64.1159 50.5988 60.8297 46.8625 57.6088L44.8813 55.8889C49.9435 49.3011 53.2774 40.6939 53.2774 33.8335C53.2774 32.8561 52.8898 31.9187 52.1999 31.2275C51.51 30.5363 50.5743 30.148 49.5986 30.148C48.6229 30.148 47.6872 30.5363 46.9973 31.2275C46.3074 31.9187 45.9198 32.8561 45.9198 33.8335C45.9198 38.8013 43.3102 45.5273 39.5471 50.7253C35.692 46.4179 32.9406 41.3312 32.9406 33.8335C32.9406 32.8561 32.553 31.9187 31.8631 31.2275C31.1732 30.5363 30.2375 30.148 29.2618 30.148C28.2862 30.148 27.3505 30.5363 26.6606 31.2275C25.9707 31.9187 25.5831 32.8561 25.5831 33.8335C25.5831 48.9709 34.3393 56.5261 42.0609 63.1907C48.3992 68.6575 53.4038 72.9765 53.4038 80.5547V85.8603C50.7214 83.7066 47.6864 82.0213 44.7051 80.3935C39.4513 77.5027 34.4888 74.7731 31.6071 69.6442C31.3705 69.2225 31.0534 68.8515 30.6738 68.5526C30.2942 68.2536 29.8596 68.0325 29.3947 67.9019C28.9297 67.7712 28.4437 67.7336 27.9643 67.7911C27.4849 67.8486 27.0214 68.0002 26.6005 68.2372C26.1795 68.4741 25.8093 68.7918 25.5109 69.1721C25.2125 69.5524 24.9918 69.9879 24.8614 70.4536C24.7309 70.9194 24.6934 71.4063 24.7508 71.8866C24.8082 72.3669 24.9595 72.8312 25.196 73.2529C29.1086 80.2323 35.5119 83.7565 41.1642 86.8661C46.1459 89.5995 50.4225 91.9567 52.7179 96.0799C52.9726 96.5402 53.2016 97.0145 53.4038 97.5003V106.365C42.337 105.53 31.8715 100.992 23.6885 93.4812C15.5055 85.9704 10.0798 75.922 8.28311 64.9502C6.4864 53.9785 8.4229 42.7201 13.7815 32.9836C19.1402 23.2471 27.61 15.5976 37.8303 11.2638C49.9223 6.15915 63.542 6.06978 75.6997 11.0153C87.8574 15.9608 97.5596 25.537 102.677 37.6419C103.073 38.5166 103.794 39.2017 104.688 39.5512C105.581 39.9008 106.575 39.8872 107.458 39.5133C108.341 39.1394 109.044 38.4348 109.416 37.5496C109.789 36.6644 109.801 35.6685 109.452 34.7741C104.348 22.6888 95.2298 12.7431 83.6431 6.62283C72.0564 0.502553 58.7137 -1.41585 45.8765 1.19278C33.0394 3.80141 21.4974 10.7766 13.2068 20.9361C4.9163 31.0956 0.387207 43.8144 0.387207 56.9369C0.387207 70.0594 4.9163 82.7783 13.2068 92.9378C21.4974 103.097 33.0394 110.072 45.8765 112.681C58.7137 115.29 72.0564 113.371 83.6431 107.251C95.2298 101.131 104.348 91.1851 109.452 79.0997C109.64 78.6541 109.739 78.1756 109.743 77.6916C109.747 77.2076 109.656 76.7275 109.474 76.279C109.293 75.8304 109.025 75.4221 108.685 75.0774C108.346 74.7327 107.942 74.4584 107.497 74.2702Z" fill="currentColor" /> </g> </g> <defs> <clipPath id="clip0_0_1"> <rect width="110" height="114" fill="background" /> </clipPath> </defs> </svg> ); }; export default CoralMarkIcon; ```
/content/code_sandbox/client/src/core/client/ui/components/icons/CoralMarkIcon.tsx
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
2,455
```xml import { BigNumber } from '@ethersproject/bignumber'; import { parse as parseTransaction } from '@ethersproject/transactions'; import { donationAddressMap, ETHUUID } from '@config'; import { fAccounts, fAssets, fERC20NonWeb3TxConfigJSON as fERC20NonWeb3TxConfig, fERC20NonWeb3TxReceipt, fERC20NonWeb3TxResponse, fERC20Web3TxConfigJSON as fERC20Web3TxConfig, fERC20Web3TxReceipt, fERC20Web3TxResponse, fETHNonWeb3TxConfigJSON as fETHNonWeb3TxConfig, fETHNonWeb3TxReceipt, fETHNonWeb3TxResponse, fETHWeb3TxConfigJSON as fETHWeb3TxConfig, fETHWeb3TxReceipt, fETHWeb3TxResponse, fFinishedERC20NonWeb3TxReceipt, fFinishedERC20Web3TxReceipt, fNetwork, fNetworks, fRopDAI, fSignedTx, fSignedTxEIP1559, fTxConfigEIP1559, fTxReceiptEIP1559 } from '@fixtures'; import { ITxData, ITxGasLimit, ITxGasPrice, ITxHash, ITxStatus, ITxToAddress, ITxType, ITxValue, TAddress, TUuid } from '@types'; import { appendGasLimit, appendGasPrice, appendNonce, appendSender, deriveTxFields, deriveTxRecipientsAndAmount, ERCType, guessERC20Type, makeFinishedTxReceipt, makePendingTxReceipt, makeTxConfigFromSignedTx, makeTxConfigFromTx, makeUnknownTxReceipt, toTxReceipt, verifyTransaction } from './transaction'; jest.mock('@services/ApiService/Gas', () => ({ ...jest.requireActual('@services/ApiService/Gas'), fetchGasPriceEstimates: () => Promise.resolve({ fast: 20 }), getGasEstimate: () => Promise.resolve(21000) })); jest.mock('@services/EthService/nonce', () => ({ getNonce: () => Promise.resolve(1) })); const senderAddr = donationAddressMap.ETH as TAddress; describe('toTxReceipt', () => { it('creates tx receipt for non-web3 eth tx', () => { const txReceipt = toTxReceipt(fETHNonWeb3TxResponse.hash as ITxHash, ITxStatus.PENDING)( ITxType.STANDARD, fETHNonWeb3TxConfig ); expect(txReceipt).toStrictEqual(fETHNonWeb3TxReceipt); }); it('creates tx receipt for web3 eth tx', () => { const txReceipt = toTxReceipt(fETHWeb3TxResponse.hash as ITxHash, ITxStatus.PENDING)( ITxType.STANDARD, fETHWeb3TxConfig ); expect(txReceipt).toStrictEqual(fETHWeb3TxReceipt); }); it('creates tx receipt for non-web3 erc20 tx', () => { const txReceipt = toTxReceipt(fERC20NonWeb3TxResponse.hash as ITxHash, ITxStatus.PENDING)( ITxType.STANDARD, fERC20NonWeb3TxConfig ); expect(txReceipt).toStrictEqual(fERC20NonWeb3TxReceipt); }); it('creates tx receipt for web3 erc20 tx', () => { const txReceipt = toTxReceipt(fERC20Web3TxResponse.hash as ITxHash, ITxStatus.PENDING)( ITxType.STANDARD, fERC20Web3TxConfig ); expect(txReceipt).toStrictEqual(fERC20Web3TxReceipt); }); it('adds metadata if present', () => { const metadata = { receivingAsset: ETHUUID as TUuid }; const txReceipt = toTxReceipt(fERC20Web3TxResponse.hash as ITxHash, ITxStatus.PENDING)( ITxType.STANDARD, fERC20Web3TxConfig, metadata ); expect(txReceipt).toStrictEqual({ ...fERC20Web3TxReceipt, metadata }); }); it('supports EIP 1559 gas', () => { const txReceipt = toTxReceipt(fERC20Web3TxResponse.hash as ITxHash, ITxStatus.PENDING)( ITxType.STANDARD, fTxConfigEIP1559 ); expect(txReceipt).toStrictEqual(fTxReceiptEIP1559); }); }); describe('makePendingTxReceipt', () => { it('creates pending tx receipt for non-web3 eth tx', () => { const txReceipt = makePendingTxReceipt(fETHNonWeb3TxResponse.hash as ITxHash)( ITxType.STANDARD, fETHNonWeb3TxConfig ); expect(txReceipt).toStrictEqual(fETHNonWeb3TxReceipt); }); it('creates pending tx receipt for web3 eth tx', () => { const txReceipt = makePendingTxReceipt(fETHWeb3TxResponse.hash as ITxHash)( ITxType.STANDARD, fETHWeb3TxConfig ); expect(txReceipt).toStrictEqual(fETHWeb3TxReceipt); }); it('creates pending tx receipt for non-web3 erc20 tx', () => { const txReceipt = makePendingTxReceipt(fERC20NonWeb3TxResponse.hash as ITxHash)( ITxType.STANDARD, fERC20NonWeb3TxConfig ); expect(txReceipt).toStrictEqual(fERC20NonWeb3TxReceipt); }); it('creates pending tx receipt for web3 erc20 tx', () => { const txReceipt = makePendingTxReceipt(fERC20Web3TxResponse.hash as ITxHash)( ITxType.STANDARD, fERC20Web3TxConfig ); expect(txReceipt).toStrictEqual(fERC20Web3TxReceipt); }); it('adds metadata if present', () => { const metadata = { receivingAsset: ETHUUID as TUuid }; const txReceipt = makePendingTxReceipt(fERC20Web3TxResponse.hash as ITxHash)( ITxType.STANDARD, fERC20Web3TxConfig, metadata ); expect(txReceipt).toStrictEqual({ ...fERC20Web3TxReceipt, metadata }); }); }); describe('makeUnknownTxReceipt', () => { it('creates pending tx receipt for non-web3 eth tx', () => { const txReceipt = makeUnknownTxReceipt(fETHNonWeb3TxResponse.hash as ITxHash)( ITxType.STANDARD, fETHNonWeb3TxConfig ); expect(txReceipt).toStrictEqual({ ...fETHNonWeb3TxReceipt, status: ITxStatus.UNKNOWN }); }); it('creates pending tx receipt for web3 eth tx', () => { const txReceipt = makeUnknownTxReceipt(fETHWeb3TxResponse.hash as ITxHash)( ITxType.STANDARD, fETHWeb3TxConfig ); expect(txReceipt).toStrictEqual({ ...fETHWeb3TxReceipt, status: ITxStatus.UNKNOWN }); }); it('creates pending tx receipt for non-web3 erc20 tx', () => { const txReceipt = makeUnknownTxReceipt(fERC20NonWeb3TxResponse.hash as ITxHash)( ITxType.STANDARD, fERC20NonWeb3TxConfig ); expect(txReceipt).toStrictEqual({ ...fERC20NonWeb3TxReceipt, status: ITxStatus.UNKNOWN }); }); it('creates pending tx receipt for web3 erc20 tx', () => { const txReceipt = makeUnknownTxReceipt(fERC20Web3TxResponse.hash as ITxHash)( ITxType.STANDARD, fERC20Web3TxConfig ); expect(txReceipt).toStrictEqual({ ...fERC20Web3TxReceipt, status: ITxStatus.UNKNOWN }); }); it('adds metadata if present', () => { const metadata = { receivingAsset: ETHUUID as TUuid }; const txReceipt = makeUnknownTxReceipt(fERC20Web3TxResponse.hash as ITxHash)( ITxType.STANDARD, fERC20Web3TxConfig, metadata ); expect(txReceipt).toStrictEqual({ ...fERC20Web3TxReceipt, status: ITxStatus.UNKNOWN, metadata }); }); }); describe('makeFinishedTxReceipt', () => { it('updates pending erc20 web3 tx to finished', () => { const finishedTimestamp = 1590735286; const finishedBlock = 7991049; const finishedGasUsed = fERC20Web3TxReceipt.gasLimit; const confirmations = 1; const finishedTxReceipt = makeFinishedTxReceipt( fERC20Web3TxReceipt, ITxStatus.SUCCESS, finishedTimestamp, finishedBlock, finishedGasUsed, confirmations ); expect(finishedTxReceipt).toStrictEqual(fFinishedERC20Web3TxReceipt); }); it('updates pending erc20 non-web3 tx to finished', () => { const finishedTimestamp = 1590734231; const finishedBlock = 7990974; const finishedGasUsed = fERC20NonWeb3TxReceipt.gasLimit; const confirmations = 1; const finishedTxReceipt = makeFinishedTxReceipt( fERC20NonWeb3TxReceipt, ITxStatus.SUCCESS, finishedTimestamp, finishedBlock, finishedGasUsed, confirmations ); expect(finishedTxReceipt).toStrictEqual(fFinishedERC20NonWeb3TxReceipt); }); }); describe('guessERC20Type', () => { it('interprets an erc20 transfer data field to be an erc20 transfer', () => { const erc20DataField = your_sha256_hashyour_sha256_hash29913de8a2'; const ercType = guessERC20Type(erc20DataField); expect(ercType).toBe(ERCType.TRANSFER); }); it('interprets an eth tx data field to not be an erc20 transfer', () => { const ethTxDataField = '0x0'; const ercType = guessERC20Type(ethTxDataField); expect(ercType).toBe(ERCType.NONE); }); it('interprets an swap tx data field to not be an erc20 transfer', () => { const swapTxDataField = your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashb495dd19fe'; const ercType = guessERC20Type(swapTxDataField); expect(ercType).toBe(ERCType.NONE); }); }); describe('deriveTxRecipientsAndAmount', () => { it("interprets an erc20 transfer's recipients and amounts correctly", () => { const erc20DataField = your_sha256_hashyour_sha256_hash29913de8a2'; const toAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; const value = '0x0'; const { to, amount, receiverAddress } = deriveTxRecipientsAndAmount( ERCType.TRANSFER, erc20DataField as ITxData, toAddress as ITxToAddress, value as ITxValue ); expect({ to, amount, receiverAddress }).toStrictEqual({ to: toAddress, receiverAddress: '0x5dd6e754D37baBaBEb95F34639568812900feC79', amount: '4813942855992010991778' }); }); it("interprets an eth tx's recipients and amounts correctly", () => { const ethTxDataField = '0x0'; const toAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; const value = '0x104f6e0a229913de8a2'; const { to, amount, receiverAddress } = deriveTxRecipientsAndAmount( ERCType.NONE, ethTxDataField as ITxData, toAddress as ITxToAddress, value as ITxValue ); expect({ to, amount, receiverAddress }).toStrictEqual({ to: toAddress, receiverAddress: toAddress, amount: '0x104f6e0a229913de8a2' }); }); }); describe('deriveTxFields', () => { it("interprets an erc20 transfer's fields correctly", () => { const erc20DataField = your_sha256_hashyour_sha256_hash29913de8a2'; const toAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; const value = '0x0'; const result = deriveTxFields( ERCType.TRANSFER, erc20DataField as ITxData, toAddress as ITxToAddress, value as ITxValue, fAssets[1], fRopDAI ); expect(result).toStrictEqual({ to: toAddress, receiverAddress: '0x5dd6e754D37baBaBEb95F34639568812900feC79', amount: '4813.942855992010991778', asset: fRopDAI }); }); it("interprets an erc20 approve's fields correctly", () => { const erc20DataField = your_sha256_hashyour_sha256_hashffffffffff'; const toAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; const value = '0x0'; const result = deriveTxFields( ERCType.APPROVAL, erc20DataField as ITxData, toAddress as ITxToAddress, value as ITxValue, fAssets[1], fRopDAI ); expect(result).toStrictEqual({ to: toAddress, receiverAddress: toAddress, amount: '0', asset: fRopDAI }); }); it("interprets an eth tx's fields correctly", () => { const erc20DataField = '0x'; const toAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; const value = '0x54ab1b2ceea88000'; const result = deriveTxFields( ERCType.NONE, erc20DataField as ITxData, toAddress as ITxToAddress, value as ITxValue, fAssets[1], fRopDAI ); expect(result).toStrictEqual({ to: toAddress, receiverAddress: toAddress, amount: '6.101', asset: fAssets[1] }); }); }); describe('makeTxConfigFromTx', () => { it('interprets an web3 tx response correctly', () => { const toAddress = '0x5197B5b062288Bbf29008C92B08010a92Dd677CD'; const result = makeTxConfigFromTx(fETHWeb3TxResponse, fAssets, fNetwork, fAccounts); expect(result).toStrictEqual( expect.objectContaining({ from: toAddress, receiverAddress: toAddress, amount: '0.01', asset: fAssets[1] }) ); }); }); describe('appendSender', () => { it('appends sender to transaction input', () => { const input = { to: senderAddr, value: '0x0' as ITxValue, data: '0x0' as ITxData, chainId: 1 }; const actual = appendSender(senderAddr)(input); const expected = { to: senderAddr, value: '0x0', data: '0x0', chainId: 1, from: senderAddr }; expect(actual).toStrictEqual(expected); }); }); describe('appendGasLimit', () => { it('appends gas limit to transaction input', async () => { const input = { to: senderAddr, value: '0x0' as ITxValue, data: '0x0' as ITxData, chainId: 1, gasPrice: '0x4a817c800' as ITxGasPrice }; const actual = await appendGasLimit(fNetworks[0])(input); const expected = { to: senderAddr, value: '0x0', data: '0x0', chainId: 1, gasLimit: '0x5208', gasPrice: '0x4a817c800' }; expect(actual).toStrictEqual(expected); }); it('respects gas limit if present', async () => { const input = { to: senderAddr, value: '0x0' as ITxValue, data: '0x0' as ITxData, chainId: 1, gasPrice: '0x4a817c800' as ITxGasPrice, gasLimit: '0x5208' as ITxGasLimit }; const actual = await appendGasLimit(fNetworks[0])(input); const expected = { to: senderAddr, value: '0x0', data: '0x0', chainId: 1, gasLimit: '0x5208', gasPrice: '0x4a817c800' }; expect(actual).toStrictEqual(expected); }); }); describe('appendGasPrice', () => { it('appends gas price to transaction input', async () => { const input = { to: senderAddr, value: '0x0' as ITxValue, data: '0x0' as ITxData, chainId: 1 }; const actual = await appendGasPrice(fNetworks[0])(input); const expected = { to: senderAddr, value: '0x0', data: '0x0', chainId: 1, gasPrice: '0x4a817c800' }; expect(actual).toStrictEqual(expected); }); it('respects gas price if present', async () => { const input = { to: senderAddr, value: '0x0' as ITxValue, data: '0x0' as ITxData, gasPrice: '0x2540be400' as ITxGasPrice, chainId: 1 }; const actual = await appendGasPrice(fNetworks[0])(input); const expected = { to: senderAddr, value: '0x0', data: '0x0', chainId: 1, gasPrice: '0x2540be400' }; expect(actual).toStrictEqual(expected); }); }); describe('appendNonce', () => { it('appends nonce to transaction input', async () => { const input = { to: senderAddr, value: '0x0' as ITxValue, data: '0x0' as ITxData, chainId: 1, gasPrice: '0x4a817c800' as ITxGasPrice, gasLimit: '0x5208' as ITxGasLimit, from: senderAddr }; const actual = await appendNonce(fNetworks[0], senderAddr)(input); const expected = { to: senderAddr, value: '0x0' as ITxValue, data: '0x0' as ITxData, chainId: 1, gasPrice: '0x4a817c800' as ITxGasPrice, gasLimit: '0x5208' as ITxGasLimit, from: senderAddr, nonce: '0x1' }; expect(actual).toStrictEqual(expected); }); }); describe('verifyTransaction', () => { it('verifies a signed transaction', () => { expect( verifyTransaction({ to: '0x4bbeEB066eD09B7AEd07bF39EEe0460DFa261520', value: BigNumber.from('0x0'), data: '0x', chainId: 1, gasLimit: BigNumber.from('0x5208'), gasPrice: BigNumber.from('0x1'), nonce: 1, r: your_sha256_hash3f', s: your_sha256_hash95', v: 37 }) ).toBe(true); }); it('verifies a parsed signed transaction', () => { expect(verifyTransaction(parseTransaction(fSignedTx))).toBe(true); }); it('returns false for transactions with an invalid s value', () => { expect( verifyTransaction({ to: '0x4bbeEB066eD09B7AEd07bF39EEe0460DFa261520', value: BigNumber.from('0x0'), data: '0x', chainId: 1, gasLimit: BigNumber.from('0x5208'), gasPrice: BigNumber.from('0x1'), nonce: 1, r: your_sha256_hash3f', s: your_sha256_hasha1', v: 37 }) ).toBe(false); }); it('returns false for transactions with an invalid v value', () => { expect( verifyTransaction({ to: '0x4bbeEB066eD09B7AEd07bF39EEe0460DFa261520', value: BigNumber.from('0x0'), data: '0x', chainId: 1, gasLimit: BigNumber.from('0x5208'), gasPrice: BigNumber.from('0x1'), nonce: 1, r: your_sha256_hash3f', s: your_sha256_hasha1', v: 12345 }) ).toBe(false); }); it('returns false for transactions with an invalid signature', () => { expect( verifyTransaction({ to: '0x4bbeEB066eD09B7AEd07bF39EEe0460DFa261520', value: BigNumber.from('0x0'), data: '0x', chainId: 1, gasLimit: BigNumber.from('0x5208'), gasPrice: BigNumber.from('0x1'), nonce: 1, r: '0x12345', s: '0x12345', v: 37 }) ).toBe(false); }); it('returns false for transactions without a signature', () => { expect( verifyTransaction({ to: '0x4bbeEB066eD09B7AEd07bF39EEe0460DFa261520', value: BigNumber.from('0x0'), data: '0x', chainId: 1, gasLimit: BigNumber.from('0x5208'), gasPrice: BigNumber.from('0x1'), nonce: 1 }) ).toBe(false); }); }); describe('makeTxConfigFromSignedTx', () => { it('creates a basic tx config from a signed tx', () => { const address = '0x0961Ca10D49B9B8e371aA0Bcf77fE5730b18f2E4' as TAddress; const account = { ...fAccounts[1], address }; const result = makeTxConfigFromSignedTx(fSignedTx, fAssets, fNetworks, [account]); expect(result).toStrictEqual({ amount: '0.01', asset: fAssets[1], baseAsset: fAssets[1], from: address, networkId: 'Ropsten', rawTransaction: { chainId: 3, data: '0x', from: address, gasLimit: '0x5208', gasPrice: '0x012a05f200', nonce: '0x06', to: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', type: null, value: '0x2386f26fc10000' }, receiverAddress: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', senderAccount: account }); }); it('creates a basic tx config from a signed EIP 1559 tx', () => { const address = '0x0961Ca10D49B9B8e371aA0Bcf77fE5730b18f2E4' as TAddress; const account = { ...fAccounts[1], address }; const result = makeTxConfigFromSignedTx(fSignedTxEIP1559, fAssets, fNetworks, [account]); expect(result).toStrictEqual({ amount: '0.01', asset: fAssets[1], baseAsset: fAssets[1], from: address, networkId: 'Ropsten', rawTransaction: { chainId: 3, data: '0x', from: address, gasLimit: '0x5208', maxFeePerGas: '0x04a817c800', maxPriorityFeePerGas: '0x3b9aca00', nonce: '0x06', to: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', type: 2, value: '0x2386f26fc10000' }, receiverAddress: '0xB2BB2b958aFA2e96dAb3F3Ce7162B87dAea39017', senderAccount: account }); }); }); ```
/content/code_sandbox/src/helpers/transaction.spec.ts
xml
2016-12-04T01:35:27
2024-08-14T21:41:58
MyCrypto
MyCryptoHQ/MyCrypto
1,347
5,861
```xml import * as DateGrid from '../../../../../src/utils/date-time-utilities/dateFormatting/formatYear'; enum Months { Jan = 0, Feb = 1, Mar = 2, Apr = 3, May = 4, Jun = 5, Jul = 6, Aug = 7, Sep = 8, Oct = 9, Nov = 10, Dec = 11, } describe('formatYear', () => { const date = new Date(2016, Months.Apr, 1); it('returns default format', () => { const result = DateGrid.formatYear(date); expect(result).toBe('2016'); }); }); ```
/content/code_sandbox/packages/fluentui/react-northstar/test/specs/utils/date-time-utils/dateFormatting/formatYear-test.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
152
```xml /* * @license Apache-2.0 * * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ // TypeScript Version: 4.1 /// <reference types="@stdlib/types"/> import { Complex128 } from '@stdlib/types/complex'; /** * Evaluates the signum function of a double-precision complex floating-point number. * * @param z - input value * @returns result * * @example * var Complex128 = require( '@stdlib/complex/float64/ctor' ); * var real = require( '@stdlib/complex/float64/real' ); * var imag = require( '@stdlib/complex/float64/imag' ); * * var v = cceil( new Complex128( -4.2, 5.5 ) ); * // returns <Complex128> * * var re = real( v ); * // returns -0.6069136033622302 * * var im = imag( v ); * // returns 0.79476781392673 */ declare function csignum( z: Complex128 ): Complex128; // EXPORTS // export = csignum; ```
/content/code_sandbox/lib/node_modules/@stdlib/math/base/special/csignum/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
266
```xml // export const revalidate = '1' export default function Root({ children }: { children: React.ReactNode }) { return ( <html> <body>{children}</body> </html> ) } ```
/content/code_sandbox/test/e2e/app-dir/app-invalid-revalidate/app/layout.tsx
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
46
```xml /*your_sha256_hash----------------------------- *your_sha256_hash----------------------------*/ import { testTokenization } from '../test/testRunner'; testTokenization('vb', [ // Comments - single line [ { line: "'", tokens: [{ startIndex: 0, type: 'comment.vb' }] } ], [ { line: " ' a comment", tokens: [ { startIndex: 0, type: '' }, { startIndex: 4, type: 'comment.vb' } ] } ], [ { line: "' a comment", tokens: [{ startIndex: 0, type: 'comment.vb' }] } ], [ { line: "'sticky comment", tokens: [{ startIndex: 0, type: 'comment.vb' }] } ], [ { line: "1 ' 2; ' comment", tokens: [ { startIndex: 0, type: 'number.vb' }, { startIndex: 1, type: '' }, { startIndex: 2, type: 'comment.vb' } ] } ], [ { line: "Dim x = 1; ' my comment '' is a nice one", tokens: [ { startIndex: 0, type: 'keyword.dim.vb' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'identifier.vb' }, { startIndex: 5, type: '' }, { startIndex: 6, type: 'delimiter.vb' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'number.vb' }, { startIndex: 9, type: 'delimiter.vb' }, { startIndex: 10, type: '' }, { startIndex: 11, type: 'comment.vb' } ] } ], [ { line: 'REM this is a comment', tokens: [{ startIndex: 0, type: 'comment.vb' }] } ], [ { line: '2 + 5 REM comment starts', tokens: [ { startIndex: 0, type: 'number.vb' }, { startIndex: 1, type: '' }, { startIndex: 2, type: 'delimiter.vb' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'number.vb' }, { startIndex: 5, type: '' }, { startIndex: 6, type: 'comment.vb' } ] } ], // Numbers [ { line: '0', tokens: [{ startIndex: 0, type: 'number.vb' }] } ], [ { line: '0.0', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '&h123', tokens: [{ startIndex: 0, type: 'number.hex.vb' }] } ], [ { line: '23.5', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '23.5e3', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '23.5E3', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '23.5r', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '23.5f', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '1.72E3r', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '1.72E3r', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '1.72e3f', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '1.72e3r', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '23.5R', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '23.5r', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '1.72E3#', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '1.72E3F', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '1.72e3!', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '1.72e3f', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '1.72e-3', tokens: [{ startIndex: 0, type: 'number.float.vb' }] } ], [ { line: '0+0', tokens: [ { startIndex: 0, type: 'number.vb' }, { startIndex: 1, type: 'delimiter.vb' }, { startIndex: 2, type: 'number.vb' } ] } ], [ { line: '100+10', tokens: [ { startIndex: 0, type: 'number.vb' }, { startIndex: 3, type: 'delimiter.vb' }, { startIndex: 4, type: 'number.vb' } ] } ], [ { line: '0 + 0', tokens: [ { startIndex: 0, type: 'number.vb' }, { startIndex: 1, type: '' }, { startIndex: 2, type: 'delimiter.vb' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'number.vb' } ] } ], // Keywords [ { line: 'Imports Microsoft.VisualBasic', tokens: [ { startIndex: 0, type: 'keyword.imports.vb' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'identifier.vb' }, { startIndex: 17, type: 'delimiter.vb' }, { startIndex: 18, type: 'identifier.vb' } ] } ], [ { line: 'Private Sub Foo(ByVal sender As String)', tokens: [ { startIndex: 0, type: 'keyword.private.vb' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'keyword.tag-sub.vb' }, { startIndex: 11, type: '' }, { startIndex: 12, type: 'identifier.vb' }, { startIndex: 15, type: 'delimiter.parenthesis.vb' }, { startIndex: 16, type: 'keyword.byval.vb' }, { startIndex: 21, type: '' }, { startIndex: 22, type: 'identifier.vb' }, { startIndex: 28, type: '' }, { startIndex: 29, type: 'keyword.as.vb' }, { startIndex: 31, type: '' }, { startIndex: 32, type: 'keyword.string.vb' }, { startIndex: 38, type: 'delimiter.parenthesis.vb' } ] } ], // Strings [ { line: 'String s = "string"', tokens: [ { startIndex: 0, type: 'keyword.string.vb' }, { startIndex: 6, type: '' }, { startIndex: 7, type: 'identifier.vb' }, { startIndex: 8, type: '' }, { startIndex: 9, type: 'delimiter.vb' }, { startIndex: 10, type: '' }, { startIndex: 11, type: 'string.quote.vb' }, { startIndex: 12, type: 'string.vb' }, { startIndex: 18, type: 'string.quote.vb' } ] } ], [ { line: '"use strict";', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 11, type: 'string.quote.vb' }, { startIndex: 12, type: 'delimiter.vb' } ] } ], [ { line: '"a""b"', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 2, type: 'string.escape.vb' }, { startIndex: 4, type: 'string.vb' }, { startIndex: 5, type: 'string.quote.vb' } ] }, { line: '"ab"', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 2, type: 'string.escape.vb' }, { startIndex: 4, type: 'string.vb' }, { startIndex: 5, type: 'string.quote.vb' } ] }, { line: '"ab"', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 2, type: 'string.escape.vb' }, { startIndex: 4, type: 'string.vb' }, { startIndex: 5, type: 'string.quote.vb' } ] } ], [ { line: '"mixed quotes 1', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 15, type: 'string.quote.vb' } ] }, { line: '"mixed quotes 2', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 15, type: 'string.quote.vb' } ] }, { line: 'mixed quotes 3"', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 15, type: 'string.quote.vb' } ] }, { line: 'mixed quotes 4', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 15, type: 'string.quote.vb' } ] }, { line: 'mixed quotes 5"', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 15, type: 'string.quote.vb' } ] }, { line: 'mixed quotes 6', tokens: [ { startIndex: 0, type: 'string.quote.vb' }, { startIndex: 1, type: 'string.vb' }, { startIndex: 15, type: 'string.quote.vb' } ] } ], // Tags [ { line: 'Public Sub ToString()', tokens: [ { startIndex: 0, type: 'keyword.public.vb' }, { startIndex: 6, type: '' }, { startIndex: 7, type: 'keyword.tag-sub.vb' }, { startIndex: 10, type: '' }, { startIndex: 11, type: 'identifier.vb' }, { startIndex: 19, type: 'delimiter.parenthesis.vb' } ] } ], [ { line: 'public sub ToString()', tokens: [ { startIndex: 0, type: 'keyword.public.vb' }, { startIndex: 6, type: '' }, { startIndex: 7, type: 'keyword.tag-sub.vb' }, { startIndex: 10, type: '' }, { startIndex: 11, type: 'identifier.vb' }, { startIndex: 19, type: 'delimiter.parenthesis.vb' } ] } ], [ { line: 'While Do Continue While End While', tokens: [ { startIndex: 0, type: 'keyword.tag-while.vb' }, { startIndex: 5, type: '' }, { startIndex: 6, type: 'keyword.tag-do.vb' }, { startIndex: 8, type: '' }, { startIndex: 9, type: 'keyword.tag-continue.vb' }, { startIndex: 17, type: '' }, { startIndex: 18, type: 'keyword.tag-while.vb' }, { startIndex: 23, type: '' }, { startIndex: 24, type: 'keyword.tag-while.vb' } ] } ], [ { line: 'While while WHILE WHile whiLe', tokens: [ { startIndex: 0, type: 'keyword.tag-while.vb' }, { startIndex: 5, type: '' }, { startIndex: 6, type: 'keyword.tag-while.vb' }, { startIndex: 11, type: '' }, { startIndex: 12, type: 'keyword.tag-while.vb' }, { startIndex: 17, type: '' }, { startIndex: 18, type: 'keyword.tag-while.vb' }, { startIndex: 23, type: '' }, { startIndex: 24, type: 'keyword.tag-while.vb' } ] } ], [ { line: 'If b(i) = col Then', tokens: [ { startIndex: 0, type: 'keyword.tag-if.vb' }, { startIndex: 2, type: '' }, { startIndex: 3, type: 'identifier.vb' }, { startIndex: 4, type: 'delimiter.parenthesis.vb' }, { startIndex: 5, type: 'identifier.vb' }, { startIndex: 6, type: 'delimiter.parenthesis.vb' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'delimiter.vb' }, { startIndex: 9, type: '' }, { startIndex: 10, type: 'identifier.vb' }, { startIndex: 13, type: '' }, { startIndex: 14, type: 'keyword.then.vb' } ] } ], [ { line: 'Do stuff While True Loop', tokens: [ { startIndex: 0, type: 'keyword.tag-do.vb' }, { startIndex: 2, type: '' }, { startIndex: 3, type: 'identifier.vb' }, { startIndex: 8, type: '' }, { startIndex: 9, type: 'keyword.tag-while.vb' }, { startIndex: 14, type: '' }, { startIndex: 15, type: 'keyword.true.vb' }, { startIndex: 19, type: '' }, { startIndex: 20, type: 'keyword.tag-do.vb' } ] } ], [ { line: 'For i = 0 To 10 DoStuff Next', tokens: [ { startIndex: 0, type: 'keyword.tag-for.vb' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'identifier.vb' }, { startIndex: 5, type: '' }, { startIndex: 6, type: 'delimiter.vb' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'number.vb' }, { startIndex: 9, type: '' }, { startIndex: 10, type: 'keyword.to.vb' }, { startIndex: 12, type: '' }, { startIndex: 13, type: 'number.vb' }, { startIndex: 15, type: '' }, { startIndex: 16, type: 'identifier.vb' }, { startIndex: 23, type: '' }, { startIndex: 24, type: 'keyword.tag-for.vb' } ] } ], [ { line: 'For stuff End For', tokens: [ { startIndex: 0, type: 'keyword.tag-for.vb' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'identifier.vb' }, { startIndex: 9, type: '' }, { startIndex: 10, type: 'keyword.end.vb' }, { startIndex: 13, type: '' }, { startIndex: 14, type: 'keyword.tag-for.vb' } ] } ], [ { line: 'For stuff end for', tokens: [ { startIndex: 0, type: 'keyword.tag-for.vb' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'identifier.vb' }, { startIndex: 9, type: '' }, { startIndex: 10, type: 'keyword.end.vb' }, { startIndex: 13, type: '' }, { startIndex: 14, type: 'keyword.tag-for.vb' } ] } ], [ { line: 'Dim x = "hello', tokens: [ { startIndex: 0, type: 'keyword.dim.vb' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'identifier.vb' }, { startIndex: 5, type: '' }, { startIndex: 6, type: 'delimiter.vb' }, { startIndex: 7, type: '' }, { startIndex: 8, type: 'string.quote.vb' }, { startIndex: 9, type: 'string.vb' } ] }, { line: 'world"', tokens: [ { startIndex: 0, type: 'string.vb' }, { startIndex: 5, type: 'string.quote.vb' } ] } ], [ { line: `End qweqweqweqweqwe'here always becomes highlighted Loop `, tokens: [ { startIndex: 0, type: 'keyword.end.vb' }, { startIndex: 3, type: '' }, { startIndex: 4, type: 'identifier.vb' }, { startIndex: 19, type: 'comment.vb' } ] } ] ]); ```
/content/code_sandbox/src/basic-languages/vb/vb.test.ts
xml
2016-06-07T16:56:31
2024-08-16T17:17:05
monaco-editor
microsoft/monaco-editor
39,508
4,764
```xml import { Component, ViewChild } from '@angular/core'; import { IonicPage, Slides, NavController } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-slider-with-arrows', templateUrl: 'slider-with-arrows.html' }) export class SliderWithArrowsPage { @ViewChild('slider') slider: Slides; slides = [ { title: 'Dream\'s Adventure', imageUrl: 'assets/img/lists/wishlist-1.jpg', songs: 2, private: false }, { title: 'For the Weekend', imageUrl: 'assets/img/lists/wishlist-2.jpg', songs: 4, private: false }, { title: 'Family Time', imageUrl: 'assets/img/lists/wishlist-3.jpg', songs: 5, private: true }, { title: 'My Trip', imageUrl: 'assets/img/lists/wishlist-4.jpg', songs: 12, private: true } ]; constructor(public navCtrl: NavController) { } currentIndex = 0; nextSlide() { this.slider.slideNext(); } previousSlide() { this.slider.slidePrev(); } onSlideChanged() { this.currentIndex = this.slider.getActiveIndex(); console.log('Slide changed! Current index is', this.currentIndex); } } ```
/content/code_sandbox/src/pages/slide/slider-with-arrows/slider-with-arrows.ts
xml
2016-11-04T05:48:23
2024-08-03T05:22:54
ionic3-components
yannbf/ionic3-components
1,679
294
```xml <ResourceDictionary xmlns="path_to_url" xmlns:x="path_to_url" xmlns:local="using:Telegram.Controls.Messages.Content" xmlns:controls="using:Telegram.Controls" xmlns:icons="using:Telegram.Assets.Icons" xmlns:muxc="using:Microsoft.UI.Xaml.Controls" xmlns:d="path_to_url" xmlns:mc="path_to_url" mc:Ignorable="d"> <Style x:Key="RecognizeButtonStyle" TargetType="controls:AnimatedIconToggleButton"> <Setter Property="Background" Value="{ThemeResource ToggleButtonBackgroundChecked}" /> <Setter Property="BackgroundSizing" Value="OuterBorderEdge" /> <Setter Property="BorderBrush" Value="{ThemeResource ToggleButtonBorderBrushChecked}" /> <Setter Property="Padding" Value="0,0,0,0" /> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="FontFamily" Value="{ThemeResource SymbolThemeFontFamily}" /> <Setter Property="FontWeight" Value="Normal" /> <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}" /> <Setter Property="UseSystemFocusVisuals" Value="{StaticResource UseSystemFocusVisuals}" /> <Setter Property="FocusVisualMargin" Value="-3" /> <Setter Property="CornerRadius" Value="8" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="controls:AnimatedIconToggleButton"> <Grid CornerRadius="{TemplateBinding CornerRadius}" Margin="{TemplateBinding Padding}" AutomationProperties.AccessibilityView="Raw"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="PointerOver"> <Storyboard> <DoubleAnimation Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Opacity" Duration="0" To="0.4" /> </Storyboard> <VisualState.Setters> <Setter Target="Icon.(muxc:AnimatedIcon.State)" Value="Normal" /> </VisualState.Setters> </VisualState> <VisualState x:Name="Pressed"> <Storyboard> <DoubleAnimation Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Opacity" Duration="0" To="0.6" /> </Storyboard> <VisualState.Setters> <Setter Target="Icon.(muxc:AnimatedIcon.State)" Value="Normal" /> </VisualState.Setters> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ToggleButtonBackgroundDisabled}" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Checked"> <VisualState.Setters> <Setter Target="Icon.(muxc:AnimatedIcon.State)" Value="Checked" /> </VisualState.Setters> </VisualState> <VisualState x:Name="CheckedPointerOver"> <Storyboard> <DoubleAnimation Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Opacity" Duration="0" To="0.4" /> </Storyboard> <VisualState.Setters> <Setter Target="Icon.(muxc:AnimatedIcon.State)" Value="Checked" /> </VisualState.Setters> </VisualState> <VisualState x:Name="CheckedPressed"> <Storyboard> <DoubleAnimation Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Opacity" Duration="0" To="0.6" /> </Storyboard> <VisualState.Setters> <Setter Target="Icon.(muxc:AnimatedIcon.State)" Value="Checked" /> </VisualState.Setters> </VisualState> <VisualState x:Name="CheckedDisabled"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background"> <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ToggleButtonBackgroundCheckedDisabled}" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border x:Name="ContentPresenter" Background="{TemplateBinding Foreground}" Opacity="0.2" /> <TextBlock x:Name="ContentPresenter1" Margin="{TemplateBinding Padding}" HorizontalAlignment="Center" VerticalAlignment="Center" AutomationProperties.AccessibilityView="Raw" FontSize="30" /> <TextBlock x:Name="ContentPresenter2" Margin="{TemplateBinding Padding}" HorizontalAlignment="Center" VerticalAlignment="Center" AutomationProperties.AccessibilityView="Raw" FontSize="30" /> <muxc:AnimatedIcon x:Name="Icon" Source="{TemplateBinding Source}" muxc:AnimatedIcon.State="Normal" HorizontalAlignment="Center" VerticalAlignment="Center" AutomationProperties.AccessibilityView="Raw" Width="30" Height="30" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="controls:ProgressVoice"> <Setter Property="Foreground" Value="{ThemeResource MessageMediaBackgroundBrush}" /> <Setter Property="Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" /> <Setter Property="BorderThickness" Value="{ThemeResource ProgressBarBorderThemeThickness}" /> <Setter Property="BorderBrush" Value="{ThemeResource SystemControlHighlightTransparentBrush}" /> <Setter Property="Maximum" Value="100" /> <Setter Property="MinHeight" Value="{ThemeResource ProgressBarThemeMinHeight}" /> <Setter Property="IsTabStop" Value="False" /> <Setter Property="VerticalAlignment" Value="Stretch" /> <Setter Property="MinWidth" Value="0" /> <Setter Property="Height" Value="20" /> <Setter Property="Margin" Value="0,0,0,2" /> <Setter Property="IsTabStop" Value="False" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="controls:ProgressVoice"> <Grid> <Path x:Name="HorizontalTrackRect" Margin="{TemplateBinding Padding}" Fill="{TemplateBinding Foreground}" StrokeStartLineCap="Round" StrokeEndLineCap="Round" HorizontalAlignment="Stretch" Opacity="0.4" /> <Path x:Name="ProgressBarIndicator" Margin="{TemplateBinding Padding}" Fill="{TemplateBinding Foreground}" StrokeStartLineCap="Round" StrokeEndLineCap="Round" HorizontalAlignment="Left" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="local:VoiceNoteContent"> <Setter Property="IsTabStop" Value="False" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="local:VoiceNoteContent"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Border Width="48" Height="48" CornerRadius="24" Background="{ThemeResource MessageMediaBackgroundBrush}" VerticalAlignment="Top"> <controls:FileButton x:Name="Button" Style="{StaticResource InlineFileButtonStyle}" /> </Border> <Border x:Name="ViewOnce" Width="24" Height="24" CornerRadius="12" Margin="0,0,-6,-4" BorderThickness="2" BorderBrush="{ThemeResource MessageBackgroundBrush}" Background="{ThemeResource MessageMediaBackgroundBrush}" HorizontalAlignment="Right" VerticalAlignment="Bottom" UseLayoutRounding="False" IsHitTestVisible="False"> <TextBlock Text="&#xE918;" Foreground="#FFFFFF" FontSize="20" FontFamily="{StaticResource SymbolThemeFontFamily}" /> </Border> <StackPanel Margin="8,0,0,2" VerticalAlignment="Center" Grid.Column="1"> <!--<TextBlock x:Name="Title" Foreground="{ThemeResource MessageForegroundBrush}" TextWrapping="NoWrap" TextTrimming="CharacterEllipsis" Style="{StaticResource BaseTextBlockStyle}"/>--> <controls:ProgressVoice x:Name="Progress" AutomationProperties.AccessibilityView="Raw" HorizontalAlignment="Left" /> <TextBlock x:Name="Subtitle" Style="{StaticResource DisabledCaptionTextBlockStyle}" Typography.NumeralAlignment="Tabular" /> </StackPanel> <controls:AnimatedIconToggleButton x:Name="Recognize" AutomationProperties.Name="{CustomResource AccActionOpenTranscription}" Style="{StaticResource RecognizeButtonStyle}" Foreground="{ThemeResource MessageMediaBackgroundBrush}" CheckedGlyph="&#xE90B;" Glyph="&#xE913;" VerticalAlignment="Top" Margin="8,0,0,0" Width="28" Height="28" IsOneWay="True" Grid.Column="2"> <controls:AnimatedIconToggleButton.Source> <icons:VoiceRecognition /> </controls:AnimatedIconToggleButton.Source> </controls:AnimatedIconToggleButton> <RichTextBlock x:Name="RecognizedText" x:Load="False" Grid.ColumnSpan="3" Grid.Row="1"> <Paragraph> <Run x:Name="RecognizedSpan" /> <InlineUIContainer> <Border x:Name="RecognizedIcon" Width="12.8" Height="16" Margin="-4,2,0,-4" /> </InlineUIContainer> </Paragraph> </RichTextBlock> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> ```
/content/code_sandbox/Telegram/Controls/Messages/Content/VoiceNoteContent.xaml
xml
2016-05-23T09:03:33
2024-08-16T16:17:48
Unigram
UnigramDev/Unigram
3,744
2,267
```xml import { useMutation, useQueryClient } from '@tanstack/react-query'; import { EnvironmentId } from '@/react/portainer/environments/types'; import axios, { parseAxiosError } from '@/portainer/services/axios'; import { withError } from '@/react-tools/react-query'; import { EdgeStack } from '../../types'; import { logsStatusQueryKey } from './useLogsStatus'; export function useCollectLogsMutation() { const queryClient = useQueryClient(); return useMutation(collectLogs, { onSuccess(data, variables) { return queryClient.invalidateQueries( logsStatusQueryKey(variables.edgeStackId, variables.environmentId) ); }, ...withError('Unable to retrieve logs'), }); } interface CollectLogs { edgeStackId: EdgeStack['Id']; environmentId: EnvironmentId; } async function collectLogs({ edgeStackId, environmentId }: CollectLogs) { try { await axios.put(`/edge_stacks/${edgeStackId}/logs/${environmentId}`); } catch (error) { throw parseAxiosError(error as Error, 'Unable to start logs collection'); } } ```
/content/code_sandbox/app/react/edge/edge-stacks/ItemView/EnvironmentsDatatable/useCollectLogsMutation.ts
xml
2016-05-19T20:15:28
2024-08-16T19:15:14
portainer
portainer/portainer
30,083
240
```xml import { GET_LIST, GET_MANY, GET_MANY_REFERENCE, DELETE, DELETE_MANY, UPDATE_MANY, } from 'ra-core'; import { QUERY_TYPES, IntrospectionResult, IntrospectedResource, } from 'ra-data-graphql'; import { ArgumentNode, IntrospectionField, IntrospectionNamedTypeRef, IntrospectionObjectType, IntrospectionUnionType, TypeKind, VariableDefinitionNode, } from 'graphql'; import * as gqlTypes from 'graphql-ast-types-browser'; import getFinalType from './getFinalType'; import { getGqlType } from './getGqlType'; type SparseField = string | { [k: string]: SparseField[] }; type ExpandedSparseField = { linkedType?: string; fields: SparseField[] }; type ProcessedFields = { resourceFields: IntrospectionField[]; linkedSparseFields: ExpandedSparseField[]; }; function processSparseFields( resourceFields: readonly IntrospectionField[], sparseFields: SparseField[] ): ProcessedFields & { resourceFields: readonly IntrospectionField[] } { if (!sparseFields || sparseFields.length === 0) throw new Error( "Empty sparse fields. Specify at least one field or remove the 'sparseFields' param" ); const permittedSparseFields: ProcessedFields = sparseFields.reduce( (permitted: ProcessedFields, sparseField: SparseField) => { let expandedSparseField: ExpandedSparseField; if (typeof sparseField == 'string') expandedSparseField = { fields: [sparseField] }; else { const [linkedType, linkedSparseFields] = Object.entries(sparseField)[0]; expandedSparseField = { linkedType, fields: linkedSparseFields, }; } const availableField = resourceFields.find( resourceField => resourceField.name === (expandedSparseField.linkedType || expandedSparseField.fields[0]) ); if (availableField && expandedSparseField.linkedType) { permitted.linkedSparseFields.push(expandedSparseField); permitted.resourceFields.push(availableField); } else if (availableField) permitted.resourceFields.push(availableField); return permitted; }, { resourceFields: [], linkedSparseFields: [] } ); // ensure the requested fields are available if ( permittedSparseFields.resourceFields.length === 0 && permittedSparseFields.linkedSparseFields.length === 0 ) throw new Error( "Requested sparse fields not found. Ensure sparse fields are available in the resource's type" ); return permittedSparseFields; } export default (introspectionResults: IntrospectionResult) => ( resource: IntrospectedResource, raFetchMethod: string, queryType: IntrospectionField, variables: any ) => { let { sortField, sortOrder, ...metaVariables } = variables; const apolloArgs = buildApolloArgs(queryType, variables); const args = buildArgs(queryType, variables); const sparseFields = metaVariables.meta?.sparseFields; if (sparseFields) delete metaVariables.meta.sparseFields; const metaArgs = buildArgs(queryType, metaVariables); const fields = buildFields(introspectionResults)( resource.type.fields, sparseFields ); if ( raFetchMethod === GET_LIST || raFetchMethod === GET_MANY || raFetchMethod === GET_MANY_REFERENCE ) { return gqlTypes.document([ gqlTypes.operationDefinition( 'query', gqlTypes.selectionSet([ gqlTypes.field( gqlTypes.name(queryType.name), gqlTypes.name('items'), args, null, gqlTypes.selectionSet(fields) ), gqlTypes.field( gqlTypes.name(`_${queryType.name}Meta`), gqlTypes.name('total'), metaArgs, null, gqlTypes.selectionSet([ gqlTypes.field(gqlTypes.name('count')), ]) ), ]), gqlTypes.name(queryType.name), apolloArgs ), ]); } if (raFetchMethod === DELETE) { return gqlTypes.document([ gqlTypes.operationDefinition( 'mutation', gqlTypes.selectionSet([ gqlTypes.field( gqlTypes.name(queryType.name), gqlTypes.name('data'), args, null, gqlTypes.selectionSet(fields) ), ]), gqlTypes.name(queryType.name), apolloArgs ), ]); } if (raFetchMethod === DELETE_MANY || raFetchMethod === UPDATE_MANY) { return gqlTypes.document([ gqlTypes.operationDefinition( 'mutation', gqlTypes.selectionSet([ gqlTypes.field( gqlTypes.name(queryType.name), gqlTypes.name('data'), args, null, gqlTypes.selectionSet([ gqlTypes.field(gqlTypes.name('ids')), ]) ), ]), gqlTypes.name(queryType.name), apolloArgs ), ]); } return gqlTypes.document([ gqlTypes.operationDefinition( QUERY_TYPES.includes(raFetchMethod) ? 'query' : 'mutation', gqlTypes.selectionSet([ gqlTypes.field( gqlTypes.name(queryType.name), gqlTypes.name('data'), args, null, gqlTypes.selectionSet(fields) ), ]), gqlTypes.name(queryType.name), apolloArgs ), ]); }; export const buildFields = (introspectionResults: IntrospectionResult, paths = []) => (fields: readonly IntrospectionField[], sparseFields?: SparseField[]) => { const { resourceFields, linkedSparseFields } = sparseFields ? processSparseFields(fields, sparseFields) : { resourceFields: fields, linkedSparseFields: [] }; return resourceFields.reduce((acc, field) => { const type = getFinalType(field.type); if (type.name.startsWith('_')) { return acc; } if ( type.kind !== TypeKind.OBJECT && type.kind !== TypeKind.INTERFACE ) { return [...acc, gqlTypes.field(gqlTypes.name(field.name))]; } const linkedResource = introspectionResults.resources.find( r => r.type.name === type.name ); if (linkedResource) { const linkedResourceSparseFields = linkedSparseFields.find( lSP => lSP.linkedType === field.name )?.fields || ['id']; // default to id if no sparse fields specified for linked resource const linkedResourceFields = buildFields(introspectionResults)( linkedResource.type.fields, linkedResourceSparseFields ); return [ ...acc, gqlTypes.field( gqlTypes.name(field.name), null, null, null, gqlTypes.selectionSet(linkedResourceFields) ), ]; } const linkedType = introspectionResults.types.find( t => t.name === type.name ); if (linkedType && !paths.includes(linkedType.name)) { const possibleTypes = (linkedType as IntrospectionUnionType).possibleTypes || []; return [ ...acc, gqlTypes.field( gqlTypes.name(field.name), null, null, null, gqlTypes.selectionSet([ ...buildFragments(introspectionResults)( possibleTypes ), ...buildFields(introspectionResults, [ ...paths, linkedType.name, ])( (linkedType as IntrospectionObjectType).fields, linkedSparseFields.find( lSP => lSP.linkedType === field.name )?.fields ), ]) ), ]; } // NOTE: We might have to handle linked types which are not resources but will have to be careful about // ending with endless circular dependencies return acc; }, []); }; export const buildFragments = (introspectionResults: IntrospectionResult) => ( possibleTypes: readonly IntrospectionNamedTypeRef<IntrospectionObjectType>[] ) => possibleTypes.reduce((acc, possibleType) => { const type = getFinalType(possibleType); const linkedType = introspectionResults.types.find( t => t.name === type.name ); return [ ...acc, gqlTypes.inlineFragment( gqlTypes.selectionSet( buildFields(introspectionResults)( (linkedType as IntrospectionObjectType).fields ) ), gqlTypes.namedType(gqlTypes.name(type.name)) ), ]; }, []); export const buildArgs = ( query: IntrospectionField, variables: any ): ArgumentNode[] => { if (query.args.length === 0) { return []; } const validVariables = Object.keys(variables).filter( k => typeof variables[k] !== 'undefined' ); let args = query.args .filter(a => validVariables.includes(a.name)) .reduce( (acc, arg) => [ ...acc, gqlTypes.argument( gqlTypes.name(arg.name), gqlTypes.variable(gqlTypes.name(arg.name)) ), ], [] ); return args; }; export const buildApolloArgs = ( query: IntrospectionField, variables: any ): VariableDefinitionNode[] => { if (query.args.length === 0) { return []; } const validVariables = Object.keys(variables).filter( k => typeof variables[k] !== 'undefined' ); let args = query.args .filter(a => validVariables.includes(a.name)) .reduce((acc, arg) => { return [ ...acc, gqlTypes.variableDefinition( gqlTypes.variable(gqlTypes.name(arg.name)), getGqlType(arg.type) ), ]; }, []); return args; }; ```
/content/code_sandbox/packages/ra-data-graphql-simple/src/buildGqlQuery.ts
xml
2016-07-13T07:58:54
2024-08-16T18:32:27
react-admin
marmelab/react-admin
24,624
2,102
```xml /** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../../..' export const input = ( <editor> <block> one<inline>two</inline>three </block> </editor> ) export const test = editor => { return Editor.string(editor, [0, 1]) } export const output = `two` ```
/content/code_sandbox/packages/slate/test/interfaces/Editor/string/inline.tsx
xml
2016-06-18T01:52:42
2024-08-16T18:43:42
slate
ianstormtaylor/slate
29,492
84
```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>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>10.1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>$(CURRENT_PROJECT_VERSION)</string> <key>NSPrincipalClass</key> <string></string> </dict> </plist> ```
/content/code_sandbox/Sources/Info.plist
xml
2016-06-15T20:15:11
2024-08-13T17:55:49
LayoutKit
LinkedInAttic/LayoutKit
3,161
248
```xml const maxDelay = 50; export const getStaticProps = async () => { const delay = Math.floor(Math.random() * maxDelay); return new Promise(resolve => { setTimeout(resolve, delay); }).then(() => { return { props: { message: "demo3 this is static props", // this actually won't execute even if we didn't escape the <script> tags // because this sample enables CSP nonce xss: "</script><script>alert('oops, xss')</script>", delay } }; }); }; ```
/content/code_sandbox/samples/subapp2-poc/src/demo3-static-props.ts
xml
2016-09-06T19:02:39
2024-08-11T11:43:11
electrode
electrode-io/electrode
2,103
123
```xml <RelativeLayout xmlns:android="path_to_url" xmlns:app="path_to_url" xmlns:tools="path_to_url" android:id="@+id/file_explorer_grid_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="@drawable/background_item_grid" android:descendantFocusability="blocksDescendants" android:padding="1dp"> <RelativeLayout android:id="@+id/file_explorer_grid_folder_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone"> <RelativeLayout android:id="@+id/file_explorer_grid_folder_thumbnail_layout" android:layout_width="match_parent" android:layout_height="56dp"> <ImageView android:id="@+id/file_explorer_grid_folder_icon" android:layout_width="24dp" android:layout_height="24dp" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:background="@null" android:scaleType="fitCenter"/> <TextView android:id="@+id/file_explorer_grid_folder_filename" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginEnd="8dp" android:layout_toEndOf="@+id/file_explorer_grid_folder_icon" android:layout_toStartOf="@+id/file_grid_taken_down" android:ellipsize="middle" android:singleLine="true" android:textSize="14sp"/> <ImageView android:id="@+id/file_grid_taken_down" style="@style/taken_down_icon" android:layout_alignParentEnd="true" android:layout_marginTop="15dp" android:layout_marginEnd="6dp" android:src="@drawable/ic_alert_triangle_medium_regular_outline" app:tint="@color/color_button_brand" tools:ignore="ContentDescription" /> </RelativeLayout> </RelativeLayout> <RelativeLayout android:id="@+id/file_explorer_grid_file_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone"> <RelativeLayout android:id="@+id/file_explorer_grid_file_thumbnail_layout" android:layout_width="match_parent" android:layout_height="172dp"> <ImageView android:id="@+id/file_explorer_grid_file_thumbnail" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:scaleType="fitXY" android:paddingTop="1dp" android:paddingRight="1dp" android:paddingLeft="1dp" android:visibility="gone"/> <ImageView android:id="@+id/file_explorer_grid_file_selected" android:layout_width="23dp" android:layout_height="23dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="7dp" android:layout_marginTop="7dp"/> <ImageView android:id="@+id/file_explorer_grid_file_icon" android:layout_width="88dp" android:layout_height="88dp" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@null" android:scaleType="fitCenter"/> <RelativeLayout android:id="@+id/file_explorer_grid_file_videoinfo_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@drawable/gradient_cam_uploads" android:visibility="gone"> <TextView android:id="@+id/file_explorer_grid_file_title_video_duration" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_centerVertical="true" android:layout_marginStart="33dp" android:textAppearance="@style/TextAppearance.Mega.Body2.Variant" android:visibility="gone"/> <ImageView android:id="@+id/file_explorer_grid_file_video_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:background="@null" android:src="@drawable/ic_play_arrow_white_24dp"/> </RelativeLayout> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/grey_012_white_012" android:layout_below="@+id/file_explorer_grid_file_thumbnail_layout"/> <RelativeLayout android:layout_width="wrap_content" android:layout_height="47dp" android:layout_below="@+id/file_explorer_grid_file_thumbnail_layout"> <TextView android:id="@+id/file_grid_filename_for_file" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_toStartOf="@+id/file_grid_taken_down_for_file" android:layout_centerVertical="true" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:ellipsize="middle" android:singleLine="true" android:textColor="?android:attr/textColorPrimary" android:textSize="14sp"/> <ImageView android:id="@+id/file_grid_taken_down_for_file" style="@style/taken_down_icon" android:layout_marginStart="6dp" android:layout_marginTop="15dp" android:layout_marginEnd="6dp" android:layout_alignParentEnd="true" android:src="@drawable/ic_alert_triangle_medium_regular_outline" app:tint="@color/color_button_brand" tools:ignore="ContentDescription" /> </RelativeLayout> </RelativeLayout> </RelativeLayout> ```
/content/code_sandbox/app/src/main/res/layout/item_file_explorer_grid.xml
xml
2016-05-04T11:46:20
2024-08-15T16:29:10
android
meganz/android
1,537
1,337
```xml import * as React from "react"; import { WebPartContext } from "@microsoft/sp-webpart-base"; // Used to retrieve SharePoint items import { sp } from '@pnp/sp'; import '@pnp/sp/webs'; import '@pnp/sp/lists'; import "@pnp/sp/views"; import { ICardServiceState, cardServiceReducer } from "../CardService/CardServiceReducer"; export const useSPListDataService = (spContext: WebPartContext) => { const initialState: ICardServiceState = { type: 'status', isLoading: false, isError: false }; const [listServiceState, dispatch] = React.useReducer(cardServiceReducer, initialState); const fetchData = async (listId: string, viewId: string) => { sp.setup({ spfxContext: spContext }); // Get the list const list = await sp.web.lists.getById(listId); const view:any = await list.getView(viewId); const _viewSchema = view.HtmlSchemaXml; // Get the data as returned by the view const { Row: data } = await list.renderListDataAsStream({ ViewXml: _viewSchema }); dispatch({ type: 'success_data', results: { data: JSON.stringify(data) } }); }; const getListItems = async (listId: string, viewId: string) => { dispatch({ type: 'request_data' }); await fetchData(listId, viewId); return () => { // clean up (equivalent to finally/dispose) }; }; // return the items that consumers need return { listServiceState, getListItems }; }; ```
/content/code_sandbox/samples/react-adaptivecards-hooks/src/services/SPListDataService/SPListDataService.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
350
```xml export type Browser = "Arc" | "Brave Browser" | "Firefox" | "Google Chrome" | "Microsoft Edge" | "Yandex Browser"; ```
/content/code_sandbox/src/common/Extensions/BrowserBookmarks/Browser.ts
xml
2016-10-11T04:59:52
2024-08-16T11:53:31
ueli
oliverschwendener/ueli
3,543
34
```xml import * as consts from '../src/consts' const noBuild = false const secrets = [] satisfies string[] const sourceMap = false const verbose = false const confirm = true const json = false const entryPoint = consts.defaultEntrypoint const outDir = consts.defaultOutputFolder const allowDeprecated = false const isPublic = false export default { noBuild, secrets, sourceMap, verbose, confirm, json, entryPoint, outDir, allowDeprecated, public: isPublic, } ```
/content/code_sandbox/packages/cli/e2e/defaults.ts
xml
2016-11-16T21:57:59
2024-08-16T18:45:35
botpress
botpress/botpress
12,401
118
```xml <vector xmlns:android="path_to_url" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> <path android:pathData="M13,5C13,4.448 12.552,4 12,4C11.448,4 11,4.448 11,5L11,16.586L5.707,11.293C5.317,10.902 4.683,10.902 4.293,11.293C3.902,11.683 3.902,12.317 4.293,12.707L11.293,19.707C11.683,20.098 12.317,20.098 12.707,19.707L19.707,12.707C20.098,12.317 20.098,11.683 19.707,11.293C19.317,10.902 18.683,10.902 18.293,11.293L13,16.586L13,5Z" android:fillColor="#FAFAFA"/> </vector> ```
/content/code_sandbox/shared/original-core-ui/src/main/res/drawable/ic_arrow_down.xml
xml
2016-05-04T11:46:20
2024-08-15T16:29:10
android
meganz/android
1,537
262
```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. --> <project xmlns:xsi="path_to_url" xmlns="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.intuit.wasabi</groupId> <artifactId>wasabi</artifactId> <version>1.0.20190619090227-SNAPSHOT</version> <relativePath>../../pom.xml</relativePath> </parent> <artifactId>wasabi-user-directory</artifactId> <packaging>jar</packaging> <name>${project.artifactId}</name> <dependencies> <dependency> <groupId>${project.groupId}</groupId> <artifactId>wasabi-authentication-objects</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>wasabi-exceptions</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>com.intuit.autumn</groupId> <artifactId>autumn-utils</artifactId> <version>1.0.20160714060618</version> </dependency> <dependency> <groupId>com.intuit.autumn</groupId> <artifactId>autumn-client</artifactId> <version>1.0.20160714060618</version> </dependency> </dependencies> </project> ```
/content/code_sandbox/modules/user-directory/pom.xml
xml
2016-06-21T21:21:06
2024-08-06T13:29:36
wasabi
intuit/wasabi
1,133
369
```xml <Documentation> <Docs DocId="T:Foundation.NSNumber"> <summary>Binding to Objective-C API to box numbers (value types).</summary> <remarks> <para> NSNumber provides explicit operator conversions that allow you to cast an NSNumber into any of the core .NET types (float, double, int, uint, short, ushort, byte, sbyte and bool). </para> <para> NSNumber also provides implicit operator conversions that allow you to create NSNumber instances from the core .NET types (float, double, int, uint, short, ushort, byte, sbyte and bool). </para> <example> <code lang="csharp lang-csharp"><![CDATA[ // Creates an NSNumber that contains the integer value 4. NSNumber d = 4; // Obtains a float from an NSNumber using explicit casts: float asFloat = (float) d; // Passes a float to a method taking an NSNumber implicitly: void RunForSeconds (NSNumber seconds) { ... } [...] RunForSeconds (4); ]]></code> </example> </remarks> <related type="externalDocumentation" href="path_to_url">Apple documentation for <c>NSNumber</c></related> </Docs> </Documentation> ```
/content/code_sandbox/docs/api/Foundation/NSNumber.xml
xml
2016-04-20T18:24:26
2024-08-16T13:29:19
xamarin-macios
xamarin/xamarin-macios
2,436
277
```xml import { Widget } from '@lumino/widgets'; import { ITableOfContentsTracker, TableOfContents } from './tokens'; /** * Table of contents tracker */ export class TableOfContentsTracker implements ITableOfContentsTracker { /** * Constructor */ constructor() { this.modelMapping = new WeakMap<Widget, TableOfContents.Model>(); } /** * Track a given model. * * @param widget Widget * @param model Table of contents model */ add(widget: Widget, model: TableOfContents.Model): void { this.modelMapping.set(widget, model); } /** * Get the table of contents model associated with a given widget. * * @param widget Widget * @returns The table of contents model */ get(widget: Widget): TableOfContents.Model | null { const model = this.modelMapping.get(widget); return !model || model.isDisposed ? null : model; } protected modelMapping: WeakMap<Widget, TableOfContents.Model>; } ```
/content/code_sandbox/packages/toc/src/tracker.ts
xml
2016-06-03T20:09:17
2024-08-16T19:12:44
jupyterlab
jupyterlab/jupyterlab
14,019
226
```xml import '@interactjs/types' import interact from '@interactjs/interactjs/index' export default interact ```
/content/code_sandbox/Myrtille.Web/node_modules/interactjs/index.d.ts
xml
2016-03-10T11:30:37
2024-08-16T11:10:12
myrtille
cedrozor/myrtille
1,778
25
```xml import {Component, NgModule} from '@angular/core'; import {MatListModule} from '@angular/material/list'; /** * Basic component using `MatNavList` and `MatListItem`. Other parts of the list * module such as `MatList`, `MatSelectionList` or `MatListOption` are not used * and should be tree-shaken away. */ @Component({ template: ` <mat-nav-list> <mat-list-item> hello </mat-list-item> </mat-nav-list> `, }) export class TestComponent {} @NgModule({ imports: [MatListModule], declarations: [TestComponent], bootstrap: [TestComponent], }) export class AppModule {} ```
/content/code_sandbox/integration/size-test/material/list/nav-list.ts
xml
2016-01-04T18:50:02
2024-08-16T11:21:13
components
angular/components
24,263
148
```xml import deburr from "lodash/deburr"; import difference from "lodash/difference"; import sortBy from "lodash/sortBy"; import { observer } from "mobx-react"; import { DOMParser as ProsemirrorDOMParser } from "prosemirror-model"; import { TextSelection } from "prosemirror-state"; import * as React from "react"; import { mergeRefs } from "react-merge-refs"; import { Optional } from "utility-types"; import insertFiles from "@shared/editor/commands/insertFiles"; import { AttachmentPreset } from "@shared/types"; import { Heading } from "@shared/utils/ProsemirrorHelper"; import { dateLocale, dateToRelative } from "@shared/utils/date"; import { getDataTransferFiles } from "@shared/utils/files"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; import { isInternalUrl } from "@shared/utils/urls"; import { AttachmentValidation } from "@shared/validations"; import ClickablePadding from "~/components/ClickablePadding"; import ErrorBoundary from "~/components/ErrorBoundary"; import type { Props as EditorProps, Editor as SharedEditor } from "~/editor"; import useCurrentUser from "~/hooks/useCurrentUser"; import useDictionary from "~/hooks/useDictionary"; import useEditorClickHandlers from "~/hooks/useEditorClickHandlers"; import useEmbeds from "~/hooks/useEmbeds"; import useStores from "~/hooks/useStores"; import useUserLocale from "~/hooks/useUserLocale"; import { NotFoundError } from "~/utils/errors"; import { uploadFile } from "~/utils/files"; import lazyWithRetry from "~/utils/lazyWithRetry"; import DocumentBreadcrumb from "./DocumentBreadcrumb"; import Icon from "./Icon"; const LazyLoadedEditor = lazyWithRetry(() => import("~/editor")); export type Props = Optional< EditorProps, | "placeholder" | "defaultValue" | "onClickLink" | "embeds" | "dictionary" | "extensions" > & { shareId?: string | undefined; embedsDisabled?: boolean; onHeadingsChange?: (headings: Heading[]) => void; onSynced?: () => Promise<void>; onPublish?: (event: React.MouseEvent) => void; editorStyle?: React.CSSProperties; }; function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) { const { id, shareId, onChange, onHeadingsChange, onCreateCommentMark, onDeleteCommentMark, } = props; const userLocale = useUserLocale(); const locale = dateLocale(userLocale); const { comments, documents } = useStores(); const dictionary = useDictionary(); const embeds = useEmbeds(!shareId); const localRef = React.useRef<SharedEditor>(); const preferences = useCurrentUser({ rejectOnEmpty: false })?.preferences; const previousHeadings = React.useRef<Heading[] | null>(null); const previousCommentIds = React.useRef<string[]>(); const handleSearchLink = React.useCallback( async (term: string) => { if (isInternalUrl(term)) { // search for exact internal document const slug = parseDocumentSlug(term); if (!slug) { return []; } try { const document = await documents.fetch(slug); const time = dateToRelative(Date.parse(document.updatedAt), { addSuffix: true, shorten: true, locale, }); return [ { title: document.title, subtitle: `Updated ${time}`, url: document.url, icon: document.icon ? ( <Icon value={document.icon} color={document.color ?? undefined} /> ) : undefined, }, ]; } catch (error) { // NotFoundError could not find document for slug if (!(error instanceof NotFoundError)) { throw error; } } } // default search for anything that doesn't look like a URL const results = await documents.searchTitles(term); return sortBy( results.map(({ document }) => ({ title: document.title, subtitle: <DocumentBreadcrumb document={document} onlyText />, url: document.url, icon: document.icon ? ( <Icon value={document.icon} color={document.color ?? undefined} /> ) : undefined, })), (document) => deburr(document.title) .toLowerCase() .startsWith(deburr(term).toLowerCase()) ? -1 : 1 ); }, [locale, documents] ); const handleUploadFile = React.useCallback( async (file: File) => { const result = await uploadFile(file, { documentId: id, preset: AttachmentPreset.DocumentAttachment, }); return result.url; }, [id] ); const { handleClickLink } = useEditorClickHandlers({ shareId }); const focusAtEnd = React.useCallback(() => { localRef?.current?.focusAtEnd(); }, [localRef]); const handleDrop = React.useCallback( (event: React.DragEvent<HTMLDivElement>) => { event.preventDefault(); event.stopPropagation(); const files = getDataTransferFiles(event); const view = localRef?.current?.view; if (!view) { return; } // Find a valid position at the end of the document to insert our content const pos = TextSelection.near( view.state.doc.resolve(view.state.doc.nodeSize - 2) ).from; // If there are no files in the drop event attempt to parse the html // as a fragment and insert it at the end of the document if (files.length === 0) { const text = event.dataTransfer.getData("text/html") || event.dataTransfer.getData("text/plain"); const dom = new DOMParser().parseFromString(text, "text/html"); view.dispatch( view.state.tr.insert( pos, ProsemirrorDOMParser.fromSchema(view.state.schema).parse(dom) ) ); return; } // Insert all files as attachments if any of the files are not images. const isAttachment = files.some( (file) => !AttachmentValidation.imageContentTypes.includes(file.type) ); return insertFiles(view, event, pos, files, { uploadFile: handleUploadFile, onFileUploadStart: props.onFileUploadStart, onFileUploadStop: props.onFileUploadStop, dictionary, isAttachment, }); }, [ localRef, props.onFileUploadStart, props.onFileUploadStop, dictionary, handleUploadFile, ] ); // see: path_to_url const handleDragOver = React.useCallback( (event: React.DragEvent<HTMLDivElement>) => { event.stopPropagation(); event.preventDefault(); }, [] ); // Calculate if headings have changed and trigger callback if so const updateHeadings = React.useCallback(() => { if (onHeadingsChange) { const headings = localRef?.current?.getHeadings(); if ( headings && headings.map((h) => h.level + h.title).join("") !== previousHeadings.current?.map((h) => h.level + h.title).join("") ) { previousHeadings.current = headings; onHeadingsChange(headings); } } }, [localRef, onHeadingsChange]); const updateComments = React.useCallback(() => { if (onCreateCommentMark && onDeleteCommentMark && localRef.current) { const commentMarks = localRef.current.getComments(); const commentIds = comments.orderedData.map((c) => c.id); const commentMarkIds = commentMarks?.map((c) => c.id); const newCommentIds = difference( commentMarkIds, previousCommentIds.current ?? [], commentIds ); newCommentIds.forEach((commentId) => { const mark = commentMarks.find((c) => c.id === commentId); if (mark) { onCreateCommentMark(mark.id, mark.userId); } }); const removedCommentIds = difference( previousCommentIds.current ?? [], commentMarkIds ?? [] ); removedCommentIds.forEach((commentId) => { onDeleteCommentMark(commentId); }); previousCommentIds.current = commentMarkIds; } }, [onCreateCommentMark, onDeleteCommentMark, comments.orderedData]); const handleChange = React.useCallback( (event) => { onChange?.(event); updateHeadings(); updateComments(); }, [onChange, updateComments, updateHeadings] ); const handleRefChanged = React.useCallback( (node: SharedEditor | null) => { if (node) { updateHeadings(); updateComments(); } }, [updateComments, updateHeadings] ); return ( <ErrorBoundary component="div" reloadOnChunkMissing> <> <LazyLoadedEditor ref={mergeRefs([ref, localRef, handleRefChanged])} uploadFile={handleUploadFile} embeds={embeds} userPreferences={preferences} dictionary={dictionary} {...props} onClickLink={handleClickLink} onSearchLink={handleSearchLink} onChange={handleChange} placeholder={props.placeholder || ""} defaultValue={props.defaultValue || ""} /> {props.editorStyle?.paddingBottom && !props.readOnly && ( <ClickablePadding onClick={focusAtEnd} onDrop={handleDrop} onDragOver={handleDragOver} minHeight={props.editorStyle.paddingBottom} /> )} </> </ErrorBoundary> ); } export default observer(React.forwardRef(Editor)); ```
/content/code_sandbox/app/components/Editor.tsx
xml
2016-05-22T21:31:47
2024-08-16T19:57:22
outline
outline/outline
26,751
2,077
```xml import { debug } from "../debug" import * as node_fetch from "node-fetch" import HttpProxyAgent from "http-proxy-agent" import HttpsProxyAgent from "https-proxy-agent" import AsyncRetry from "async-retry" const d = debug("networking") declare const global: any const isJest = typeof jest !== "undefined" const warn = isJest ? () => "" : console.warn const shouldRetryRequest = (res: node_fetch.Response) => { // Don't retry 4xx errors other than 401. All 4xx errors can probably be ignored once // the Github API issue causing path_to_url is fixed return res.status === 401 || (res.status >= 500 && res.status <= 599) } /** * Adds retry handling to fetch requests * * @param {(string | fetch.Request)} url the request * @param {fetch.RequestInit} [init] the usual options * @returns {Promise<fetch.Response>} network-y promise */ export async function retryableFetch( url: string | node_fetch.Request, init: node_fetch.RequestInit ): Promise<node_fetch.Response> { const retries = isJest ? 1 : 3 return AsyncRetry( async (_, attempt) => { const originalFetch = node_fetch.default const res = await originalFetch(url, init) // Throwing an error will trigger a retry if (attempt <= retries && shouldRetryRequest(res)) { throw new Error(`Request failed [${res.status}]: ${res.url}. Attempting retry.`) } return res }, { retries: retries, onRetry: (error, attempt) => { warn(error.message) warn(`Retry ${attempt} of ${retries}.`) }, } ) } /** * Adds logging to every fetch request if a global var for `verbose` is set to true * * @param {(string | fetch.Request)} url the request * @param {fetch.RequestInit} [init] the usual options * @returns {Promise<fetch.Response>} network-y promise */ export function api( url: string | node_fetch.Request, init: node_fetch.RequestInit, suppressErrorReporting?: boolean, processEnv: NodeJS.ProcessEnv = process.env ): Promise<node_fetch.Response> { const isTests = typeof jest !== "undefined" if (isTests && !url.toString().includes("localhost")) { const message = `No API calls in tests please: ${url}` debugger throw new Error(message) } if (global.verbose && global.verbose === true) { const output = ["curl", "-i"] if (init.method) { output.push(`-X ${init.method}`) } const showToken = processEnv["DANGER_VERBOSE_SHOW_TOKEN"] const token = processEnv["DANGER_GITHUB_API_TOKEN"] || processEnv["GITHUB_TOKEN"] if (init.headers) { for (const prop in init.headers) { if (init.headers.hasOwnProperty(prop)) { // Don't show the token for normal verbose usage if (init.headers[prop].includes(token) && !showToken) { output.push("-H", `"${prop}: [API TOKEN]"`) continue } output.push("-H", `"${prop}: ${init.headers[prop]}"`) } } } if (init.method === "POST") { // const body:string = init.body // output.concat([init.body]) } if (typeof url === "string") { output.push(url) } d(output.join(" ")) } let agent = init.agent const proxy = processEnv["HTTPS_PROXY"] || processEnv["https_proxy"] || processEnv["HTTP_PROXY"] || processEnv["http_proxy"] if (!agent && proxy) { let secure = url.toString().startsWith("https") init.agent = secure ? HttpsProxyAgent(proxy) : HttpProxyAgent(proxy) } return retryableFetch(url, init).then(async (response: node_fetch.Response) => { // Handle failing errors if (!suppressErrorReporting && !response.ok) { // we should not modify the response when an error occur to allow body stream to be read again if needed let clonedResponse = response.clone() warn(`Request failed [${clonedResponse.status}]: ${clonedResponse.url}`) let responseBody = await clonedResponse.text() try { // tries to pretty print the JSON response when possible const responseJSON = await JSON.parse(responseBody.toString()) warn(`Response: ${JSON.stringify(responseJSON, null, " ")}`) } catch (e) { warn(`Response: ${responseBody}`) } } return response }) } ```
/content/code_sandbox/source/api/fetch.ts
xml
2016-08-20T12:57:06
2024-08-13T14:00:02
danger-js
danger/danger-js
5,229
1,026
```xml import { hooks } from 'botframework-webchat-api'; import classNames from 'classnames'; import PropTypes from 'prop-types'; import React, { useCallback, useRef, type FC, type FormEventHandler, type MouseEventHandler } from 'react'; import { useRefFrom } from 'use-ref-from'; import IconButton from '../SendBox/IconButton'; import useMakeThumbnail from '../hooks/useMakeThumbnail'; import useStyleToEmotionObject from '../hooks/internal/useStyleToEmotionObject'; import useFocus from '../hooks/useFocus'; import useStyleSet from '../hooks/useStyleSet'; import useSubmit from '../providers/internal/SendBox/useSubmit'; import AttachmentIcon from './Assets/AttachmentIcon'; const { useDisabled, useSendBoxAttachments, useLocalizer, useStyleOptions } = hooks; const ROOT_STYLE = { '&.webchat__upload-button': { display: 'flex', overflow: 'hidden', position: 'relative', '& .webchat__upload-button--file-input': { height: 0, width: 0, opacity: 0, position: 'absolute', left: 0, top: 0 } } }; const PREVENT_DEFAULT_HANDLER = event => event.preventDefault(); type UploadButtonProps = { className?: string; }; const UploadButton: FC<UploadButtonProps> = ({ className }) => { const [{ sendAttachmentOn, uploadAccept, uploadMultiple }] = useStyleOptions(); const [{ uploadButton: uploadButtonStyleSet }] = useStyleSet(); const [disabled] = useDisabled(); const [sendBoxAttachments, setSendBoxAttachments] = useSendBoxAttachments(); const focus = useFocus(); const inputRef = useRef<HTMLInputElement>(null); const localize = useLocalizer(); const makeThumbnail = useMakeThumbnail(); const rootClassName = useStyleToEmotionObject()(ROOT_STYLE) + ''; const submit = useSubmit(); const sendAttachmentOnRef = useRefFrom(sendAttachmentOn); const uploadFileString = localize('TEXT_INPUT_UPLOAD_BUTTON_ALT'); const handleClick = useCallback<MouseEventHandler<HTMLButtonElement>>(() => inputRef.current?.click(), [inputRef]); const handleFileChange = useCallback<FormEventHandler<HTMLInputElement>>( ({ currentTarget }) => { // We should change the focus synchronously for accessibility reason. focus('sendBox'); // TODO: [P2] We should disable send button while we are creating thumbnails. // Otherwise, if the user click the send button too quickly, it will not attach any files. (async function () { setSendBoxAttachments( Object.freeze( await Promise.all( [...currentTarget.files].map(blob => makeThumbnail(blob).then(thumbnailURL => ({ blob, thumbnailURL }))) ) ) ); sendAttachmentOnRef.current === 'attach' && submit(); })(); }, [focus, makeThumbnail, sendAttachmentOnRef, setSendBoxAttachments, submit] ); return ( <div className={classNames(rootClassName, 'webchat__upload-button', uploadButtonStyleSet + '', className)}> <input accept={uploadAccept} aria-disabled={disabled} aria-hidden="true" className="webchat__upload-button--file-input" multiple={uploadMultiple} onChange={disabled ? undefined : handleFileChange} onClick={disabled ? PREVENT_DEFAULT_HANDLER : undefined} readOnly={disabled} ref={inputRef} role="button" tabIndex={-1} type="file" /> <IconButton alt={uploadFileString} aria-label={uploadFileString} disabled={disabled} onClick={handleClick}> <AttachmentIcon checked={!!sendBoxAttachments.length} /> </IconButton> </div> ); }; UploadButton.defaultProps = { className: undefined }; UploadButton.propTypes = { className: PropTypes.string }; export default UploadButton; ```
/content/code_sandbox/packages/component/src/SendBoxToolbar/UploadButton.tsx
xml
2016-07-07T23:16:57
2024-08-16T00:12:37
BotFramework-WebChat
microsoft/BotFramework-WebChat
1,567
822
```xml <!-- Description: entry source contributor - email --> <feed xmlns="path_to_url"> <entry> <source> <contributor> <email>email@example.org</email> </contributor> </source> </entry> </feed> ```
/content/code_sandbox/testdata/parser/atom/atom10_feed_entry_source_contributor_email.xml
xml
2016-01-23T02:44:34
2024-08-16T15:16:03
gofeed
mmcdole/gofeed
2,547
64
```xml // PnP import { sp, RenderListDataOptions } from "@pnp/sp"; import { WebPartContext } from "@microsoft/sp-webpart-base"; import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http'; import { IGetListDataAsStreamResult, IRow } from './IGetListDataAsStreamResult'; import { GetAbsoluteDomainUrl } from "../../CommonUtils"; export class OneDriveServices { private _oneDriveUrl: string = undefined; private _oneDriveFullUrl: string = undefined; private _context: WebPartContext = undefined; private _absoluteUrl: string = undefined; private _serverRelativeFolderUrl: string = undefined; private _accepts: string = undefined; /** * */ constructor(context: WebPartContext, accepts: string) { this._context = context; this._accepts = accepts; this._absoluteUrl = this._context.pageContext.web.absoluteUrl; sp.setup({ sp: { baseUrl: this._absoluteUrl } }); } private _getOneDriveRootFolder = (): Promise<string> => { return sp.profiles.userProfile.then((currentUser) => { // Get the current user's personal site URL this._oneDriveUrl = currentUser.FollowPersonalSiteUrl; // Get the list of ... uh.. lists on the user's personal site // BaseTemplate 700 and BaseType 1 means document library const apiUrl: string = `${this._absoluteUrl}/_api/SP.RemoteWeb(@a1)/Web/Lists?$filter=BaseTemplate eq 700 and BaseType eq 1&@a1='${encodeURIComponent(this._oneDriveUrl)}'`; return this._context.spHttpClient.get(apiUrl, SPHttpClient.configurations.v1) .then((response: SPHttpClientResponse) => { return response.json().then((responseJSON: any) => { // Get the first library const myDocumentsLibrary = responseJSON.value[0]; // Get the parent url const parentWebUrl: string = myDocumentsLibrary.ParentWebUrl; // Get the first root folder. Assumed it is the same name as the library. Could be wrong. const serverRelativeRootFolder: string = `${myDocumentsLibrary.ParentWebUrl}/${myDocumentsLibrary.Title}`; // Build an absolute URL so that we can refer to it this._oneDriveFullUrl = this._buildOneDriveAbsoluteUrl(serverRelativeRootFolder); return serverRelativeRootFolder; }); }); }); } public GetListDataAsStream(rootFolder?: string) { // If we don't know what the root OneDrive folder is if (this._serverRelativeFolderUrl === undefined) { // Get the user's OneDrive root folder return this._getOneDriveRootFolder().then((oneDriveRootFolder: string) => { // Call the OneDrive root folder or whatever we passed in as root folder return this._getListDataAsStream(rootFolder ? rootFolder : oneDriveRootFolder); }); } else { return this._getListDataAsStream(rootFolder ? rootFolder : this._serverRelativeFolderUrl); } } private _getListDataAsStream = (rootFolder: string): Promise<IGetListDataAsStreamResult> => { const listFullUrl: string = this._oneDriveFullUrl; const encodedFullUrl: string = encodeURIComponent(`'${listFullUrl}'`); const encodedRootFolder: string = encodeURIComponent(rootFolder); const listItemUrl: string = `${this._absoluteUrl}/_api/SP.List.GetListDataAsStream?listFullUrl=${encodedFullUrl}&View=&RootFolder=${encodedRootFolder}`; const fileFilter: string = OneDriveServices.GetFileTypeFilter(this._accepts); const data: string = JSON.stringify({ parameters: { RenderOptions: RenderListDataOptions.ContextInfo | RenderListDataOptions.ListData | RenderListDataOptions.ListSchema | RenderListDataOptions.ViewMetadata | RenderListDataOptions.EnableMediaTAUrls | RenderListDataOptions.ParentInfo,//4231, //4103, //4231, //192, //64 AllowMultipleValueFilterForTaxonomyFields: true, ViewXml: `<View> <Query> <Where> <Or> <And> <Eq> <FieldRef Name="FSObjType" /> <Value Type="Text">1</Value> </Eq> <Eq> <FieldRef Name="SortBehavior" /> <Value Type="Text">1</Value> </Eq> </And> <In> <FieldRef Name="File_x0020_Type" /> ${fileFilter} </In> </Or> </Where> </Query> <ViewFields> <FieldRef Name="DocIcon"/> <FieldRef Name="LinkFilename"/> <FieldRef Name="Modified"/> <FieldRef Name="Editor"/> <FieldRef Name="FileSizeDisplay"/> <FieldRef Name="SharedWith"/> <FieldRef Name="MediaServiceFastMetadata"/> <FieldRef Name="MediaServiceOCR"/> <FieldRef Name="_ip_UnifiedCompliancePolicyUIAction"/> <FieldRef Name="ItemChildCount"/> <FieldRef Name="FolderChildCount"/> <FieldRef Name="SMTotalFileCount"/> <FieldRef Name="SMTotalSize"/> </ViewFields> <RowLimit Paged="TRUE">100</RowLimit> </View>` } }); const spOpts: ISPHttpClientOptions = { method: "POST", body: data }; return this._context.spHttpClient.fetch(listItemUrl, SPHttpClient.configurations.v1, spOpts) .then((listResponse: SPHttpClientResponse) => listResponse.json().then((listResponseJSON: IGetListDataAsStreamResult) => listResponseJSON)); } /** * Creates an absolute URL */ private _buildOneDriveAbsoluteUrl = (relativeUrl: string) => { const siteUrl: string = GetAbsoluteDomainUrl(this._oneDriveUrl); return siteUrl + relativeUrl; } /** * Builds a file filter */ public static GetFileTypeFilter(accepts: string) { let fileFilter: string = undefined; fileFilter = "<Values>"; accepts.split(",").forEach((fileType: string, index: number) => { fileType = fileType.replace(".", ""); if (index > 0) { fileFilter = fileFilter + `<Value Type="Text">${fileType}</Value>`; } }); fileFilter = fileFilter + "</Values>"; return fileFilter; } } ```
/content/code_sandbox/samples/react-comparer/src/services/OneDriveServices/OneDriveServices.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
1,432
```xml <?xml version="1.0" encoding="UTF-8"?> <nodes> <node> <text>this branch</text> <id>root/number_8</id> <cls>folder</cls> <leaf></leaf> <expanded></expanded> <value>number_8</value> <children> <node> <text><![CDATA[<i class="icon-shopping-cart"></i> Purchase Metronic Today]]></text> <id>root/number_8/wow</id> <href>path_to_url <leaf>1</leaf> <value>2</value> </node> </children> </node> <node> <text>Check this Out!</text> <id>root/number_9</id> <cls>folder</cls> <leaf></leaf> <expanded>true</expanded> <value>number_9</value> <children> <node> <text><![CDATA[<i class="icon-shopping-cart"></i> Purchase Metronic Today]]></text> <id>root/number_9/metronic</id> <href>path_to_url <leaf>1</leaf> <value>But Metronic Today</value> </node> </children> </node> </nodes> ```
/content/code_sandbox/Git.Storage.Web/Theme/plugins/bootstrap-tree/xmlexample.xml
xml
2016-05-19T00:34:01
2024-07-23T18:45:11
gitwms
hechenqingyuan/gitwms
1,000
297
```xml import { API_CODES } from '@proton/shared/lib/constants'; import type { SyncMultipleApiResponse, SyncMultipleApiResponses, UpdateEventPartApiResponse, } from '@proton/shared/lib/interfaces/calendar'; import type { OpenedMailEvent } from '../../../../hooks/useGetOpenedMailEvents'; import type { AttendeeDeleteSingleEditOperation, UpdatePartstatOperation, UpdatePersonalPartOperation, } from '../../../../interfaces/Invite'; import type { SyncEventActionOperations } from '../../getSyncMultipleEventsPayload'; import { getIsDeleteSyncOperation } from '../../getSyncMultipleEventsPayload'; import type { CalendarsEventsCache } from '../interface'; import removeCalendarEventStoreRecord from './removeCalendarEventStoreRecord'; import upsertCalendarApiEvent from './upsertCalendarApiEvent'; const getResponse = (responses: SyncMultipleApiResponses[], index: number) => { return responses.find((x) => x.Index === index); }; export const upsertSyncMultiActionsResponses = ( multiActions: SyncEventActionOperations[], multiResponses: SyncMultipleApiResponse[], calendarsEventsCache: CalendarsEventsCache, getOpenedMailEvents: () => OpenedMailEvent[] ) => { for (let i = 0; i < multiResponses.length; ++i) { const actions = multiActions[i]; const responses = multiResponses[i]; const responsesArray = responses?.Responses; const calendarEventsCache = calendarsEventsCache.calendars[actions.calendarID]; if (!Array.isArray(responsesArray) || !calendarEventsCache) { continue; } for (let j = 0; j < actions.operations.length; ++j) { const operation = actions.operations[j]; const matchingResponse = getResponse(responsesArray, j); if (getIsDeleteSyncOperation(operation)) { if (!matchingResponse || matchingResponse.Response.Code === API_CODES.SINGLE_SUCCESS) { removeCalendarEventStoreRecord( operation.data.calendarEvent.ID, calendarEventsCache, getOpenedMailEvents ); } continue; } if (matchingResponse) { const matchingEvent = matchingResponse.Response.Event; if (matchingEvent && matchingResponse.Response.Code === API_CODES.SINGLE_SUCCESS) { upsertCalendarApiEvent(matchingEvent, calendarEventsCache, getOpenedMailEvents); } } } } }; export const upsertUpdateEventPartResponses = ( operations: (UpdatePartstatOperation | UpdatePersonalPartOperation | AttendeeDeleteSingleEditOperation)[], responses: UpdateEventPartApiResponse[], calendarsEventsCache: CalendarsEventsCache, getOpenedMailEvents: () => OpenedMailEvent[] ) => { responses.forEach(({ Code, Event }, index) => { const { data: { calendarID }, } = operations[index]; const calendarEventsCache = calendarsEventsCache.calendars[calendarID]; if (!calendarEventsCache) { return; } if (Code === API_CODES.SINGLE_SUCCESS) { upsertCalendarApiEvent(Event, calendarEventsCache, getOpenedMailEvents); } }); }; export const upsertAttendeeDeleteSingleEditResponses = ( operations: (UpdatePartstatOperation | UpdatePersonalPartOperation | AttendeeDeleteSingleEditOperation)[], responses: UpdateEventPartApiResponse[], calendarsEventsCache: CalendarsEventsCache, getOpenedMailEvents: () => OpenedMailEvent[] ) => { responses.forEach(({ Code, Event }, index) => { const { data: { calendarID, eventID }, } = operations[index]; const calendarEventsCache = calendarsEventsCache.calendars[calendarID]; if (!calendarEventsCache) { return; } if (Code === API_CODES.SINGLE_SUCCESS) { upsertCalendarApiEvent(Event, calendarEventsCache, getOpenedMailEvents); removeCalendarEventStoreRecord(eventID, calendarEventsCache, getOpenedMailEvents); } }); }; ```
/content/code_sandbox/applications/calendar/src/app/containers/calendar/eventStore/cache/upsertResponsesArray.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
830
```xml import * as React from 'react'; import { TextField, Button, ButtonType } from 'office-ui-fabric-react'; import styles from './ConfigurationView.module.scss'; import IConfigurationViewState from './IConfigurationViewState'; import IConfigurationViewProps from './IConfigurationViewProps'; export default class ConfigurationView extends React.Component<IConfigurationViewProps, IConfigurationViewState>{ private _placeHolderText: string = 'Enter your todo'; constructor(props: IConfigurationViewProps) { super(props); this.state = { inputValue: '' }; this._handleConfigureButtonClick = this._handleConfigureButtonClick.bind(this); } public render(): JSX.Element { return ( <div className="Placeholder"> <div className="Placeholder-container ms-Grid"> <div className="Placeholder-head ms-Grid-row"> <div className="ms-Grid-col ms-u-hiddenSm ms-u-md3"></div> <div className="Placeholder-headContainer ms-Grid-col ms-u-sm12 ms-u-md6"> <i className={"Placeholder-icon ms-fontSize-su ms-Icon " + (this.props.icon)}></i><span className="Placeholder-text ms-fontWeight-light ms-fontSize-xxl">{this.props.iconText}</span></div> <div className="ms-Grid-col ms-u-hiddenSm ms-u-md3"></div> </div> <div className="Placeholder-description ms-Grid-row"><span className="Placeholder-descriptionText">{this.props.description}</span></div> <div className="Placeholder-description ms-Grid-row"> <Button className={ styles.configureButton } buttonType={ ButtonType.primary } ariaLabel={ this.props.buttonLabel } onClick={this._handleConfigureButtonClick}> {this.props.buttonLabel} </Button> </div> </div> </div> ); } private _handleConfigureButtonClick(event?: React.MouseEvent<HTMLButtonElement>) { this.props.onConfigure(); } } ```
/content/code_sandbox/samples/react-todo-basic/src/webparts/todo/components/ConfigurationView/ConfigurationView.tsx
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
413
```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 realarray = require( './index' ); // TESTS // // The function returns a typed array.. { realarray(); // $ExpectType TypedArray realarray( 'float32' ); // $ExpectType TypedArray realarray( 10, 'float32' ); // $ExpectType TypedArray realarray( [ 1, 2, 3 ], 'int32' ); // $ExpectType TypedArray } // The compiler throws an error if the function is provided a first argument which is not a data type, number, array-like object, or typed array... { realarray( true ); // $ExpectError realarray( false ); // $ExpectError realarray( {} ); // $ExpectError realarray( null ); // $ExpectError realarray( ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an unsupported number of arguments... { const buf = new ArrayBuffer( 32 ); realarray( buf, 8, 2, 'int32', {} ); // $ExpectError } ```
/content/code_sandbox/lib/node_modules/@stdlib/array/typed-real/docs/types/test.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
282
```xml export { default as IconRow } from './IconRow'; export { default as MemoizedIconRow } from './MemoizedIconRow'; ```
/content/code_sandbox/packages/components/components/iconRow/index.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
29
```xml import * as React from 'react'; import ComponentExample from '../../../../components/ComponentDoc/ComponentExample'; import ExampleSection from '../../../../components/ComponentDoc/ExampleSection'; const Types = () => ( <ExampleSection title="Types"> <ComponentExample title="Default" description="A default form." examplePath="components/Form/Types/FormExampleBase" /> <ComponentExample title="Inline" description="The form controls can appear next to the label instead of below it." examplePath="components/Form/Types/FormExampleInline" /> </ExampleSection> ); export default Types; ```
/content/code_sandbox/packages/fluentui/docs/src/examples/components/Form/Types/index.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
131
```xml import { inject, injectable } from 'inversify'; import * as path from 'path'; import { IServiceContainer } from '../../../ioc/types'; import '../../extensions'; import { TerminalShellType } from '../types'; import { ActivationScripts, VenvBaseActivationCommandProvider } from './baseActivationProvider'; // For a given shell the scripts are in order of precedence. const SCRIPTS: ActivationScripts = { // Group 1 [TerminalShellType.commandPrompt]: ['activate.bat', 'Activate.ps1'], // Group 2 [TerminalShellType.powershell]: ['Activate.ps1', 'activate.bat'], [TerminalShellType.powershellCore]: ['Activate.ps1', 'activate.bat'], }; export function getAllScripts(pathJoin: (...p: string[]) => string): string[] { const scripts: string[] = []; for (const names of Object.values(SCRIPTS)) { for (const name of names) { if (!scripts.includes(name)) { scripts.push( name, // We also add scripts in subdirs. pathJoin('Scripts', name), pathJoin('scripts', name), ); } } } return scripts; } @injectable() export class CommandPromptAndPowerShell extends VenvBaseActivationCommandProvider { protected readonly scripts: ActivationScripts; constructor(@inject(IServiceContainer) serviceContainer: IServiceContainer) { super(serviceContainer); this.scripts = {}; for (const [key, names] of Object.entries(SCRIPTS)) { const shell = key as TerminalShellType; const scripts: string[] = []; for (const name of names) { scripts.push( name, // We also add scripts in subdirs. path.join('Scripts', name), path.join('scripts', name), ); } this.scripts[shell] = scripts; } } public async getActivationCommandsForInterpreter( pythonPath: string, targetShell: TerminalShellType, ): Promise<string[] | undefined> { const scriptFile = await this.findScriptFile(pythonPath, targetShell); if (!scriptFile) { return undefined; } if (targetShell === TerminalShellType.commandPrompt && scriptFile.endsWith('activate.bat')) { return [scriptFile.fileToCommandArgumentForPythonExt()]; } if ( (targetShell === TerminalShellType.powershell || targetShell === TerminalShellType.powershellCore) && scriptFile.endsWith('Activate.ps1') ) { return [`& ${scriptFile.fileToCommandArgumentForPythonExt()}`]; } if (targetShell === TerminalShellType.commandPrompt && scriptFile.endsWith('Activate.ps1')) { // lets not try to run the powershell file from command prompt (user may not have powershell) return []; } return undefined; } } ```
/content/code_sandbox/src/client/common/terminal/environmentActivationProviders/commandPrompt.ts
xml
2016-01-19T10:50:01
2024-08-12T21:05:24
pythonVSCode
DonJayamanne/pythonVSCode
2,078
612
```xml /* * @license Apache-2.0 * * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ // TypeScript Version: 4.1 /** * Tests if two arguments are strictly equal. * * ## Notes * * - The function differs from the `===` operator in that the function treats `-0` and `+0` as distinct. * * @param a - first input value * @param b - second input value * @returns boolean indicating whether two arguments are strictly equal * * @example * var bool = isStrictEqual( true, true ); * // returns true * * @example * var bool = isStrictEqual( 3.14, 3.14 ); * // returns true * * @example * var bool = isStrictEqual( {}, {} ); * // returns false * * @example * var bool = isStrictEqual( -0.0, -0.0 ); * // returns true * * @example * var bool = isStrictEqual( -0.0, 0.0 ); * // returns false * * @example * var bool = isStrictEqual( NaN, NaN ); * // returns false * * @example * var bool = isStrictEqual( [], [] ); * // returns false */ declare function isStrictEqual( a: any, b: any ): boolean; // EXPORTS // export = isStrictEqual; ```
/content/code_sandbox/lib/node_modules/@stdlib/assert/is-strict-equal/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
322
```xml import { getPackageJson } from '@expo/config'; import { getBareExtensions } from '@expo/config/paths'; import * as runtimeEnv from '@expo/env'; import JsonFile from '@expo/json-file'; import chalk from 'chalk'; import { MixedOutput, Module, ReadOnlyGraph, Reporter } from 'metro'; import { stableHash } from 'metro-cache'; import { ConfigT as MetroConfig, InputConfigT } from 'metro-config'; import os from 'os'; import path from 'path'; import resolveFrom from 'resolve-from'; import { getDefaultCustomizeFrame, INTERNAL_CALLSITES_REGEX } from './customizeFrame'; import { env } from './env'; import { FileStore } from './file-store'; import { getModulesPaths, getServerRoot } from './getModulesPaths'; import { getWatchFolders } from './getWatchFolders'; import { getRewriteRequestUrl } from './rewriteRequestUrl'; import { JSModule } from './serializer/getCssDeps'; import { isVirtualModule } from './serializer/sideEffects'; import { withExpoSerializers } from './serializer/withExpoSerializers'; import { getPostcssConfigHash } from './transform-worker/postcss'; import { importMetroConfig } from './traveling/metro-config'; const debug = require('debug')('expo:metro:config') as typeof console.log; export interface LoadOptions { config?: string; maxWorkers?: number; port?: number; reporter?: Reporter; resetCache?: boolean; } export interface DefaultConfigOptions { /** @deprecated */ mode?: 'exotic'; /** * **Experimental:** Enable CSS support for Metro web, and shim on native. * * This is an experimental feature and may change in the future. The underlying implementation * is subject to change, and native support for CSS Modules may be added in the future during a non-major SDK release. */ isCSSEnabled?: boolean; /** * **Experimental:** Modify premodules before a code asset is serialized * * This is an experimental feature and may change in the future. The underlying implementation * is subject to change. */ unstable_beforeAssetSerializationPlugins?: ((serializationInput: { graph: ReadOnlyGraph<MixedOutput>; premodules: Module[]; debugId?: string; }) => Module[])[]; } function getAssetPlugins(projectRoot: string): string[] { const hashAssetFilesPath = resolveFrom.silent(projectRoot, 'expo-asset/tools/hashAssetFiles'); if (!hashAssetFilesPath) { throw new Error(`The required package \`expo-asset\` cannot be found`); } return [hashAssetFilesPath]; } let hasWarnedAboutExotic = false; // Patch Metro's graph to support always parsing certain modules. This enables // things like Tailwind CSS which update based on their own heuristics. function patchMetroGraphToSupportUncachedModules() { const { Graph } = require('metro/src/DeltaBundler/Graph'); const original_traverseDependencies = Graph.prototype.traverseDependencies; if (!original_traverseDependencies.__patched) { original_traverseDependencies.__patched = true; Graph.prototype.traverseDependencies = function (paths: string[], options: unknown) { this.dependencies.forEach((dependency: JSModule) => { // Find any dependencies that have been marked as `skipCache` and ensure they are invalidated. // `skipCache` is set when a CSS module is found by PostCSS. if ( dependency.output.find((file) => file.data.css?.skipCache) && !paths.includes(dependency.path) ) { // Ensure we invalidate the `unstable_transformResultKey` (input hash) so the module isn't removed in // the Graph._processModule method. dependency.unstable_transformResultKey = dependency.unstable_transformResultKey + '.'; // Add the path to the list of modified paths so it gets run through the transformer again, // this will ensure it is passed to PostCSS -> Tailwind. paths.push(dependency.path); } }); // Invoke the original method with the new paths to ensure the standard behavior is preserved. return original_traverseDependencies.call(this, paths, options); }; // Ensure we don't patch the method twice. Graph.prototype.traverseDependencies.__patched = true; } } function createNumericModuleIdFactory(): (path: string) => number { const fileToIdMap = new Map(); let nextId = 0; return (modulePath: string) => { let id = fileToIdMap.get(modulePath); if (typeof id !== 'number') { id = nextId++; fileToIdMap.set(modulePath, id); } return id; }; } function createStableModuleIdFactory(root: string): (path: string) => number { const fileToIdMap = new Map<string, string>(); // This is an absolute file path. return (modulePath: string): number => { // TODO: We may want a hashed version for production builds in the future. let id = fileToIdMap.get(modulePath); if (id == null) { // NOTE: Metro allows this but it can lead to confusing errors when dynamic requires cannot be resolved, e.g. `module 456 cannot be found`. if (modulePath == null) { id = 'MODULE_NOT_FOUND'; } else if (isVirtualModule(modulePath)) { // Virtual modules should be stable. id = modulePath; } else if (path.isAbsolute(modulePath)) { id = path.relative(root, modulePath); } else { id = modulePath; } fileToIdMap.set(modulePath, id); } // @ts-expect-error: we patch this to support being a string. return id; }; } export function getDefaultConfig( projectRoot: string, { mode, isCSSEnabled = true, unstable_beforeAssetSerializationPlugins }: DefaultConfigOptions = {} ): InputConfigT { const { getDefaultConfig: getDefaultMetroConfig, mergeConfig } = importMetroConfig(projectRoot); if (isCSSEnabled) { patchMetroGraphToSupportUncachedModules(); } const isExotic = mode === 'exotic' || env.EXPO_USE_EXOTIC; if (isExotic && !hasWarnedAboutExotic) { hasWarnedAboutExotic = true; console.log( chalk.gray( `\u203A Feature ${chalk.bold`EXPO_USE_EXOTIC`} has been removed in favor of the default transformer.` ) ); } const reactNativePath = path.dirname(resolveFrom(projectRoot, 'react-native/package.json')); const sourceExtsConfig = { isTS: true, isReact: true, isModern: true }; const sourceExts = getBareExtensions([], sourceExtsConfig); // Add support for cjs (without platform extensions). sourceExts.push('cjs'); const reanimatedVersion = getPkgVersion(projectRoot, 'react-native-reanimated'); let sassVersion: string | null = null; if (isCSSEnabled) { sassVersion = getPkgVersion(projectRoot, 'sass'); // Enable SCSS by default so we can provide a better error message // when sass isn't installed. sourceExts.push('scss', 'sass', 'css'); } const envFiles = runtimeEnv.getFiles(process.env.NODE_ENV, { silent: true }); const pkg = getPackageJson(projectRoot); const watchFolders = getWatchFolders(projectRoot); const nodeModulesPaths = getModulesPaths(projectRoot); if (env.EXPO_DEBUG) { console.log(); console.log(`Expo Metro config:`); try { console.log(`- Version: ${require('../package.json').version}`); } catch {} console.log(`- Extensions: ${sourceExts.join(', ')}`); console.log(`- React Native: ${reactNativePath}`); console.log(`- Watch Folders: ${watchFolders.join(', ')}`); console.log(`- Node Module Paths: ${nodeModulesPaths.join(', ')}`); console.log(`- Env Files: ${envFiles}`); console.log(`- Sass: ${sassVersion}`); console.log(`- Reanimated: ${reanimatedVersion}`); console.log(); } const { // Remove the default reporter which metro always resolves to be the react-native-community/cli reporter. // This prints a giant React logo which is less accessible to users on smaller terminals. reporter, ...metroDefaultValues } = getDefaultMetroConfig.getDefaultValues(projectRoot); const cacheStore = new FileStore<any>({ root: path.join(os.tmpdir(), 'metro-cache'), }); const serverRoot = getServerRoot(projectRoot); // Merge in the default config from Metro here, even though loadConfig uses it as defaults. // This is a convenience for getDefaultConfig use in metro.config.js, e.g. to modify assetExts. const metroConfig: Partial<MetroConfig> = mergeConfig(metroDefaultValues, { watchFolders, resolver: { unstable_conditionsByPlatform: { ios: ['react-native'], android: ['react-native'], // This is removed for server platforms. web: ['browser'], }, unstable_conditionNames: ['require', 'import'], resolverMainFields: ['react-native', 'browser', 'main'], platforms: ['ios', 'android'], assetExts: metroDefaultValues.resolver.assetExts .concat( // Add default support for `expo-image` file types. ['heic', 'avif'], // Add default support for `expo-sqlite` file types. ['db'] ) .filter((assetExt) => !sourceExts.includes(assetExt)), sourceExts, nodeModulesPaths, }, cacheStores: [cacheStore], watcher: { // strip starting dot from env files additionalExts: envFiles.map((file: string) => file.replace(/^\./, '')), }, serializer: { isThirdPartyModule(module) { // Block virtual modules from appearing in the source maps. if (isVirtualModule(module.path)) return true; // Generally block node modules if (/(?:^|[/\\])node_modules[/\\]/.test(module.path)) { // Allow the expo-router/entry and expo/AppEntry modules to be considered first party so the root of the app appears in the trace. return !module.path.match(/[/\\](expo-router[/\\]entry|expo[/\\]AppEntry)/); } return false; }, createModuleIdFactory: env.EXPO_USE_METRO_REQUIRE ? createStableModuleIdFactory.bind(null, serverRoot) : createNumericModuleIdFactory, getModulesRunBeforeMainModule: () => { const preModules: string[] = [ // MUST be first require.resolve(path.join(reactNativePath, 'Libraries/Core/InitializeCore')), ]; const stdRuntime = resolveFrom.silent(projectRoot, 'expo/src/winter'); if (stdRuntime) { preModules.push(stdRuntime); } // We need to shift this to be the first module so web Fast Refresh works as expected. // This will only be applied if the module is installed and imported somewhere in the bundle already. const metroRuntime = resolveFrom.silent(projectRoot, '@expo/metro-runtime'); if (metroRuntime) { preModules.push(metroRuntime); } return preModules; }, getPolyfills: ({ platform }) => { // Do nothing for nullish platforms. if (!platform) { return []; } if (platform === 'web') { return [ // Ensure that the error-guard polyfill is included in the web polyfills to // make metro-runtime work correctly. require.resolve('@react-native/js-polyfills/error-guard'), ]; } // Native behavior. return require('@react-native/js-polyfills')(); }, }, server: { rewriteRequestUrl: getRewriteRequestUrl(projectRoot), port: Number(env.RCT_METRO_PORT) || 8081, // NOTE(EvanBacon): Moves the server root down to the monorepo root. // This enables proper monorepo support for web. unstable_serverRoot: serverRoot, }, symbolicator: { customizeFrame: getDefaultCustomizeFrame(), }, transformerPath: require.resolve('./transform-worker/transform-worker'), transformer: { // Custom: These are passed to `getCacheKey` and ensure invalidation when the version changes. // @ts-expect-error: not on type. unstable_renameRequire: false, postcssHash: getPostcssConfigHash(projectRoot), browserslistHash: pkg.browserslist ? stableHash(JSON.stringify(pkg.browserslist)).toString('hex') : null, sassVersion, // Ensure invalidation when the version changes due to the Babel plugin. reanimatedVersion, // Ensure invalidation when using identical projects in monorepos _expoRelativeProjectRoot: path.relative(serverRoot, projectRoot), unstable_collectDependenciesPath: require.resolve('./transform-worker/collect-dependencies'), // `require.context` support unstable_allowRequireContext: true, allowOptionalDependencies: true, babelTransformerPath: require.resolve('./babel-transformer'), // See: path_to_url#L72-L74 asyncRequireModulePath: resolveFrom( reactNativePath, metroDefaultValues.transformer.asyncRequireModulePath ), assetRegistryPath: '@react-native/assets-registry/registry', assetPlugins: getAssetPlugins(projectRoot), getTransformOptions: async () => ({ transform: { experimentalImportSupport: false, inlineRequires: false, }, }), }, }); return withExpoSerializers(metroConfig, { unstable_beforeAssetSerializationPlugins }); } // re-export for use in config files. export { MetroConfig, INTERNAL_CALLSITES_REGEX }; // re-export for legacy cases. export const EXPO_DEBUG = env.EXPO_DEBUG; function getPkgVersion(projectRoot: string, pkgName: string): string | null { const targetPkg = resolveFrom.silent(projectRoot, pkgName); if (!targetPkg) return null; const targetPkgJson = findUpPackageJson(targetPkg); if (!targetPkgJson) return null; const pkg = JsonFile.read(targetPkgJson); debug(`${pkgName} package.json:`, targetPkgJson); const pkgVersion = pkg.version; if (typeof pkgVersion === 'string') { return pkgVersion; } return null; } function findUpPackageJson(cwd: string): string | null { if (['.', path.sep].includes(cwd)) return null; const found = resolveFrom.silent(cwd, './package.json'); if (found) { return found; } return findUpPackageJson(path.dirname(cwd)); } ```
/content/code_sandbox/packages/@expo/metro-config/src/ExpoMetroConfig.ts
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
3,247
```xml <?xml version="1.0" encoding="utf-8"?> <!-- path_to_url Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <com.google.android.material.chip.Chip xmlns:android="path_to_url" xmlns:app="path_to_url" style="@style/Widget.Material3.Chip.Filter" android:layout_width="wrap_content" android:layout_height="wrap_content"/> ```
/content/code_sandbox/catalog/java/io/material/catalog/chip/res/layout/cat_chip_group_item_filter.xml
xml
2016-12-05T16:11:29
2024-08-16T17:51:42
material-components-android
material-components/material-components-android
16,176
110
```xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="path_to_url" android:versionCode="1" android:versionName="1.0" package="Xamarin.Forms_Performance_Integration"> <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="30" /> <application android:label="Xamarin.Forms.Performance.Integration"></application> </manifest> ```
/content/code_sandbox/tests/Xamarin.Forms-Performance-Integration/Droid/Properties/AndroidManifest.xml
xml
2016-03-30T15:37:14
2024-08-16T19:22:13
android
dotnet/android
1,905
91
```xml import { MstError, stringStartsWith } from "../internal" /** * path_to_url * path_to_url */ export interface IJsonPatch { readonly op: "replace" | "add" | "remove" readonly path: string readonly value?: any } export interface IReversibleJsonPatch extends IJsonPatch { readonly oldValue: any // This goes beyond JSON-patch, but makes sure each patch can be inverse applied } /** * @internal * @hidden */ export function splitPatch(patch: IReversibleJsonPatch): [IJsonPatch, IJsonPatch] { if (!("oldValue" in patch)) throw new MstError(`Patches without \`oldValue\` field cannot be inversed`) return [stripPatch(patch), invertPatch(patch)] } /** * @internal * @hidden */ export function stripPatch(patch: IReversibleJsonPatch): IJsonPatch { // strips `oldvalue` information from the patch, so that it becomes a patch conform the json-patch spec // this removes the ability to undo the patch switch (patch.op) { case "add": return { op: "add", path: patch.path, value: patch.value } case "remove": return { op: "remove", path: patch.path } case "replace": return { op: "replace", path: patch.path, value: patch.value } } } function invertPatch(patch: IReversibleJsonPatch): IJsonPatch { switch (patch.op) { case "add": return { op: "remove", path: patch.path } case "remove": return { op: "add", path: patch.path, value: patch.oldValue } case "replace": return { op: "replace", path: patch.path, value: patch.oldValue } } } /** * Simple simple check to check it is a number. */ function isNumber(x: string): boolean { return typeof x === "number" } /** * Escape slashes and backslashes. * * path_to_url */ export function escapeJsonPath(path: string): string { if (isNumber(path) === true) { return "" + path } if (path.indexOf("/") === -1 && path.indexOf("~") === -1) return path return path.replace(/~/g, "~0").replace(/\//g, "~1") } /** * Unescape slashes and backslashes. */ export function unescapeJsonPath(path: string): string { return path.replace(/~1/g, "/").replace(/~0/g, "~") } /** * Generates a json-path compliant json path from path parts. * * @param path * @returns */ export function joinJsonPath(path: string[]): string { // `/` refers to property with an empty name, while `` refers to root itself! if (path.length === 0) return "" const getPathStr = (p: string[]) => p.map(escapeJsonPath).join("/") if (path[0] === "." || path[0] === "..") { // relative return getPathStr(path) } else { // absolute return "/" + getPathStr(path) } } /** * Splits and decodes a json path into several parts. * * @param path * @returns */ export function splitJsonPath(path: string): string[] { // `/` refers to property with an empty name, while `` refers to root itself! const parts = path.split("/").map(unescapeJsonPath) const valid = path === "" || path === "." || path === ".." || stringStartsWith(path, "/") || stringStartsWith(path, "./") || stringStartsWith(path, "../") if (!valid) { throw new MstError(`a json path must be either rooted, empty or relative, but got '${path}'`) } // '/a/b/c' -> ["a", "b", "c"] // '../../b/c' -> ["..", "..", "b", "c"] // '' -> [] // '/' -> [''] // './a' -> [".", "a"] // /./a' -> [".", "a"] equivalent to './a' if (parts[0] === "") { parts.shift() } return parts } ```
/content/code_sandbox/src/core/json-patch.ts
xml
2016-09-04T18:28:25
2024-08-16T08:48:55
mobx-state-tree
mobxjs/mobx-state-tree
6,917
951
```xml import React, {FunctionComponent, MouseEvent, CSSProperties} from 'react' import _ from 'lodash' const handleClick = (e: MouseEvent<HTMLDivElement>): void => { e.stopPropagation() } const randomSize = (): CSSProperties => { const width = _.random(60, 200) return {width: `${width}px`} } const LoaderSkeleton: FunctionComponent = () => { return ( <> <div className="flux-schema-tree flux-schema--child" onClick={handleClick} > <div className="flux-schema--item no-hover"> <div className="flux-schema--expander" /> <div className="flux-schema--item-skeleton" style={randomSize()} /> </div> </div> <div className="flux-schema-tree flux-schema--child"> <div className="flux-schema--item no-hover"> <div className="flux-schema--expander" /> <div className="flux-schema--item-skeleton" style={randomSize()} /> </div> </div> <div className="flux-schema-tree flux-schema--child"> <div className="flux-schema--item no-hover"> <div className="flux-schema--expander" /> <div className="flux-schema--item-skeleton" style={randomSize()} /> </div> </div> </> ) } export default LoaderSkeleton ```
/content/code_sandbox/ui/src/flux/components/LoaderSkeleton.tsx
xml
2016-08-24T23:28:56
2024-08-13T19:50:03
chronograf
influxdata/chronograf
1,494
296
```xml import * as React from 'react'; import cx from 'classnames'; import { createSvgIcon } from '../utils/createSvgIcon'; import { iconClassNames } from '../utils/iconClassNames'; export const BroadcastViewFullscreenIcon = createSvgIcon({ svg: ({ classes }) => ( <svg role="presentation" focusable="false" viewBox="8 8 16 16" className={classes.svg}> <path className={cx(iconClassNames.outline, classes.outlinePart)} d="M23.143 11.429H8.857a.857.857 0 0 0-.857.857v7.429a.857.857 0 0 0 .857.857h14.286a.857.857 0 0 0 .857-.858v-7.428a.857.857 0 0 0-.857-.857zm.286 8.286a.286.286 0 0 1-.286.286H8.857a.286.286 0 0 1-.286-.286v-7.429A.286.286 0 0 1 8.857 12h14.286a.286.286 0 0 1 .286.286z" /> <g className={cx(iconClassNames.filled, classes.filledPart)}> <path d="M9.143 12.571h13.714v6.857H9.143z" /> <path d="M23.143 11.429H8.857a.857.857 0 0 0-.857.857v7.429a.857.857 0 0 0 .857.857h14.286a.857.857 0 0 0 .857-.858v-7.428a.857.857 0 0 0-.857-.857zm.286 8.286a.286.286 0 0 1-.286.286H8.857a.286.286 0 0 1-.286-.286v-7.429A.286.286 0 0 1 8.857 12h14.286a.286.286 0 0 1 .286.286z" /> </g> </svg> ), displayName: 'BroadcastViewFullscreenIcon', }); ```
/content/code_sandbox/packages/fluentui/react-icons-northstar/src/components/BroadcastViewFullscreenIcon.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
520