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
export function generateMetadata() {
return {
title: 'Create Next App',
}
}
export default function Page() {
return <h1>Hello from Page</h1>
}
``` | /content/code_sandbox/test/e2e/app-dir/parallel-route-not-found/app/not-found-metadata/slot-error/page.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 40 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="path_to_url">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="Driver Files">
<UniqueIdentifier>{8E41214B-6785-4CFE-B992-037D68949A14}</UniqueIdentifier>
<Extensions>inf;inv;inx;mof;mc;</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="USB3380Flash.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="USB3380Flash.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Inf Include="USB3380Flash.inf">
<Filter>Driver Files</Filter>
</Inf>
</ItemGroup>
</Project>
``` | /content/code_sandbox/usb3380_flash/windows/USB3380Flash/USB3380Flash.vcxproj.filters | xml | 2016-07-27T16:26:36 | 2024-08-16T09:54:47 | pcileech | ufrisk/pcileech | 4,640 | 437 |
```xml
import { scaleBand } from 'd3-scale';
import { ViewDimensions } from './types/view-dimension.interface';
import { StringOrNumberOrDate } from '../models/chart-data.model';
export interface GridItem {
data: GridData;
height: number;
width: number;
x: number;
y: number;
}
export interface GridData {
extra?: any;
label: string;
name: StringOrNumberOrDate;
percent: number;
total: number;
value: number;
}
export function gridSize(dims: ViewDimensions, len: number, minWidth: number): [number, number] {
let rows = 1;
let cols = len;
const width = dims.width;
if (width > minWidth) {
while (width / cols < minWidth) {
rows += 1;
cols = Math.ceil(len / rows);
}
}
return [cols, rows];
}
export function gridLayout(
dims: ViewDimensions,
data: GridData[],
minWidth: number,
designatedTotal: number
): GridItem[] {
const xScale: any = scaleBand<number>();
const yScale: any = scaleBand<number>();
const width = dims.width;
const height = dims.height;
const [columns, rows] = gridSize(dims, data.length, minWidth);
const xDomain = [];
const yDomain = [];
for (let i = 0; i < rows; i++) {
yDomain.push(i);
}
for (let i = 0; i < columns; i++) {
xDomain.push(i);
}
xScale.domain(xDomain);
yScale.domain(yDomain);
xScale.rangeRound([0, width], 0.1);
yScale.rangeRound([0, height], 0.1);
const res = [];
const total = designatedTotal ? designatedTotal : getTotal(data);
const cardWidth = xScale.bandwidth();
const cardHeight = yScale.bandwidth();
for (let i = 0; i < data.length; i++) {
res[i] = {};
res[i].data = {
name: data[i] ? data[i].name : '',
value: data[i] ? data[i].value : undefined,
extra: data[i] ? data[i].extra : undefined,
label: data[i] ? data[i].label : ''
};
res[i].x = xScale(i % columns);
res[i].y = yScale(Math.floor(i / columns));
res[i].width = cardWidth;
res[i].height = cardHeight;
res[i].data.percent = total > 0 ? res[i].data.value / total : 0;
res[i].data.total = total;
}
return res;
}
function getTotal(results: any): number {
return results.map(d => (d ? d.value : 0)).reduce((sum, val) => sum + val, 0);
}
``` | /content/code_sandbox/projects/swimlane/ngx-charts/src/lib/common/grid-layout.helper.ts | xml | 2016-07-22T15:58:41 | 2024-08-02T15:56:24 | ngx-charts | swimlane/ngx-charts | 4,284 | 635 |
```xml
export const SpaceType = {
DEFAULT: "default",
PRESERVE: "preserve",
} as const;
``` | /content/code_sandbox/src/file/shared/space-type.ts | xml | 2016-03-26T23:43:56 | 2024-08-16T13:02:47 | docx | dolanmiu/docx | 4,139 | 24 |
```xml
import ButtonToolbar from './ButtonToolbar';
export type { ButtonToolbarProps } from './ButtonToolbar';
export default ButtonToolbar;
``` | /content/code_sandbox/src/ButtonToolbar/index.tsx | xml | 2016-06-06T02:27:46 | 2024-08-16T16:41:54 | rsuite | rsuite/rsuite | 8,263 | 26 |
```xml
export * from "./components";
export * from "./helpers";
export * from "./SubmitHookContext";
export { default as withSubmitHookContext } from "./withSubmitHookContext";
export { default as SubmitHookHandler } from "./SubmitHookHandler";
``` | /content/code_sandbox/client/src/core/client/framework/lib/form/index.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 51 |
```xml
<!--
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url">
<parent>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-all</artifactId>
<version>4.8.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>rocketmq-store</artifactId>
<name>rocketmq-store ${project.version}</name>
<dependencies>
<dependency>
<groupId>io.openmessaging.storage</groupId>
<artifactId>dledger</artifactId>
<version>0.2.2</version>
<exclusions>
<exclusion>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-remoting</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>rocketmq-common</artifactId>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
``` | /content/code_sandbox/store/pom.xml | xml | 2016-06-15T08:56:27 | 2024-07-22T17:20:00 | RocketMQC | ProgrammerAnthony/RocketMQC | 1,072 | 419 |
```xml
describe('Login', () => {
it('Page opens', () => {
cy.visit('/');
cy.get('.card-body');
cy.get('.col-sm-12').contains('Login');
});
it('Login', () => {
cy.visit('/');
cy.get('.card-body');
cy.get('.col-sm-12').contains('Login');
/* ==== Generated with Cypress Studio ==== */
cy.get('#username').type('admin');
cy.get('#password').clear();
cy.get('#password').type('admin');
cy.intercept({
method: 'Get',
url: '/pgapi/gallery/content/',
}).as('getContent');
cy.get('.col-sm-12 > .btn').click();
/* ==== End Cypress Studio ==== */
cy.get('.mb-0 > :nth-child(1) > .nav-link').contains('Gallery');
cy.wait('@getContent').then((interception) => {
assert.isNotNull(interception.response.body, '1st API call has data');
});
});
});
``` | /content/code_sandbox/test/cypress/e2e/login.cy.ts | xml | 2016-03-12T11:46:41 | 2024-08-16T19:56:44 | pigallery2 | bpatrik/pigallery2 | 1,727 | 218 |
```xml
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SelectProtocolComponent } from './select-protocol.component';
describe('SelectProtocolComponent', () => {
let component: SelectProtocolComponent;
let fixture: ComponentFixture<SelectProtocolComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ SelectProtocolComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SelectProtocolComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
``` | /content/code_sandbox/maxkey-web-frontend/maxkey-web-mgt-app/src/app/routes/apps/select-protocol/select-protocol.component.spec.ts | xml | 2016-11-16T03:06:50 | 2024-08-16T09:22:42 | MaxKey | dromara/MaxKey | 1,423 | 124 |
```xml
import {
Column,
Entity,
Geography,
Geometry,
Index,
Point,
PrimaryGeneratedColumn,
} from "../../../../../src"
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column("geometry", {
nullable: true,
})
@Index({
spatial: true,
})
geom: Geometry
@Column("geometry", {
nullable: true,
spatialFeatureType: "Point",
})
pointWithoutSRID: Point
@Column("geometry", {
nullable: true,
spatialFeatureType: "Point",
srid: 4326,
})
point: Point
@Column("geography", {
nullable: true,
})
geog: Geography
}
``` | /content/code_sandbox/test/functional/spatial/cockroachdb/entity/Post.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 166 |
```xml
//
//
// Microsoft Bot Framework: path_to_url
//
// Bot Framework Emulator Github:
// path_to_url
//
// All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import * as HttpStatus from 'http-status-codes';
import * as Restify from 'restify';
import { BotEndpoint } from '../../../../state/botEndpoint';
import { sendErrorResponse } from '../../../../utils/sendErrorResponse';
import { TokenCache } from '../tokenCache';
import { TokenParams } from '../types/TokenParams';
export function signOut(req: Restify.Request, res: Restify.Response, next: Restify.Next): any {
try {
const params: TokenParams = req.params;
const botEndpoint: BotEndpoint = (req as any).botEndpoint;
TokenCache.deleteTokenFromCache(botEndpoint.botId, params.userId, params.connectionName);
res.send(HttpStatus.OK);
res.end();
} catch (err) {
sendErrorResponse(req, res, next, err);
}
next();
}
``` | /content/code_sandbox/packages/app/main/src/server/routes/channel/userToken/handlers/signOut.ts | xml | 2016-11-11T23:15:09 | 2024-08-16T12:45:29 | BotFramework-Emulator | microsoft/BotFramework-Emulator | 1,803 | 426 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/**
* Evaluates the natural logarithm of the probability density function (PDF) for a Frchet distribution.
*
* @param x - input value
* @returns evaluated natural logarithm of the PDF
*/
type Unary = ( x: number ) => number;
/**
* Interface for the natural logarithm of the probability density function (logPDF) of a Frchet distribution.
*/
interface LogPDF {
/**
* Evaluates the logarithm of the probability density function (PDF) for a Frchet distribution with shape `alpha`, scale `s`, and location `m` at a value `x`.
*
* ## Notes
*
* - If provided `alpha <= 0` or `s <= 0`, the function returns `NaN`.
*
* @param x - input value
* @param alpha - shape parameter
* @param s - scale parameter
* @param m - location parameter
* @returns evaluated logPDF
*
* @example
* var y = logpdf( 10.0, 2.0, 3.0, 2.0 );
* // returns ~-3.489
*
* @example
* var y = logpdf( -2.0, 1.0, 3.0, -3.0 );
* // returns ~-1.901
*
* @example
* var y = logpdf( 0.0, 2.0, 1.0, 1.0 );
* // returns -Infinity
*
* @example
* var y = logpdf( NaN, 2.0, 1.0, -1.0 );
* // returns NaN
*
* @example
* var y = logpdf( 0.0, NaN, 1.0, -1.0 );
* // returns NaN
*
* @example
* var y = logpdf( 0.0, 2.0, NaN, -1.0 );
* // returns NaN
*
* @example
* var y = logpdf( 0.0, 2.0, 1.0, NaN );
* // returns NaN
*
* @example
* var y = logpdf( 0.0, -1.0, 1.0, 0.0 );
* // returns NaN
*
* @example
* var y = logpdf( 0.0, 1.0, -1.0, 0.0 );
* // returns NaN
*/
( x: number, alpha: number, s: number, m: number ): number;
/**
* Returns a function for evaluating the logarithm of the probability density function (PDF) for a Frchet distribution with shape `alpha`, scale `s`, and location `m`.
*
* @param alpha - shape parameter
* @param s - scale parameter
* @param m - location parameter
* @returns logPDF
*
* @example
* var mylogpdf = logpdf.factory( 3.0, 3.0, 5.0 );
*
* var y = mylogpdf( 10.0 );
* // returns ~-2.259
*
* y = mylogpdf( 7.0 );
* // returns ~-1.753
*/
factory( alpha: number, s: number, m: number ): Unary;
}
/**
* Frchet distribution natural logarithm of the probability density function (logPDF).
*
* @param x - input value
* @param alpha - shape parameter
* @param s - scale parameter
* @param m - location parameter
* @returns evaluated logPDF
*
* @example
* var y = logpdf( 10.0, 2.0, 3.0, 5.0 );
* // returns ~-2.298
*
* y = logpdf( 0.0, 2.0, 3.0, 2.0 );
* // returns -Infinity
*
* var mylogpdf = logpdf.factory( 3.0, 3.0, 5.0 );
* y = mylogpdf( 10.0 );
* // returns ~-2.259
*
* y = mylogpdf( 7.0 );
* // returns ~-1.753
*/
declare var logPDF: LogPDF;
// EXPORTS //
export = logPDF;
``` | /content/code_sandbox/lib/node_modules/@stdlib/stats/base/dists/frechet/logpdf/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 1,048 |
```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 error2json = require( './index' );
// TESTS //
// The function returns an object...
{
error2json( new Error( 'beep' ) ); // $ExpectType any
error2json( new TypeError( 'beep' ) ); // $ExpectType any
error2json( new SyntaxError( 'beep' ) ); // $ExpectType any
error2json( new URIError( 'beep' ) ); // $ExpectType any
error2json( new ReferenceError( 'beep' ) ); // $ExpectType any
error2json( new RangeError( 'beep' ) ); // $ExpectType any
error2json( new EvalError( 'beep' ) ); // $ExpectType any
}
// The compiler throws an error if the function is provided a value other than an error object...
{
error2json( 'abc' ); // $ExpectError
error2json( true ); // $ExpectError
error2json( false ); // $ExpectError
error2json( null ); // $ExpectError
error2json( undefined ); // $ExpectError
error2json( 5 ); // $ExpectError
error2json( [] ); // $ExpectError
error2json( {} ); // $ExpectError
error2json( ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the function is provided insufficient arguments...
{
error2json(); // $ExpectError
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/error/to-json/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 367 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="path_to_url"
package="com.hussienalrubaye.services">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
``` | /content/code_sandbox/CitySunsetTime/app/src/main/AndroidManifest.xml | xml | 2016-09-26T16:36:28 | 2024-08-13T08:59:01 | AndroidTutorialForBeginners | hussien89aa/AndroidTutorialForBeginners | 4,360 | 159 |
```xml
import { css } from '@emotion/css';
import { stylesFactory } from '@grafana/ui';
import { GrafanaTheme } from '@grafana/data';
import { getPmmTheme } from 'shared/components/helpers/getPmmTheme';
export const getStyles = stylesFactory((theme: GrafanaTheme) => {
const parameters = getPmmTheme(theme);
return {
getFiltersWrapper: (height) => css`
border: 1px solid rgba(40, 40, 40);
height: ${height}px;
padding: 10px 16px !important;
border-radius: 3px;
`,
filtersField: css`
width: 100%;
input {
color: ${parameters.mainTextColor} !important;
background-color: ${parameters.table.backgroundColor} !important;
}
`,
icon: css`
fill: #c6c6c6;
`,
filtersHeader: css`
display: flex;
align-items: baseline;
padding: 15px 0px 5px;
height: 50px;
justify-content: space-between;
`,
filtersDisabled: css`
opacity: 0.6;
pointer-events: none;
`,
showAllButton: css`
padding: 0 !important;
height: auto;
`,
title: css`
margin: 3px;
color: ${parameters.mainTextColor} !important;
`,
resetButton: css`
padding: 0 !important;
height: auto;
`,
};
});
``` | /content/code_sandbox/pmm-app/src/pmm-qan/panel/components/Filters/Filters.styles.ts | xml | 2016-01-22T07:14:23 | 2024-08-13T13:01:59 | grafana-dashboards | percona/grafana-dashboards | 2,661 | 333 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<swipeitems>
<item
value="pizza"
title="Pizza"
description="Pizza is love. Pizza is life." />
<item
value="burger"
title="Hamburger"
description="EY WOOD LAKE TO BYE A AMBURGER" />
<item
value="sushi"
title="Sushi"
description="Who doesn't love raw fish?" />
</swipeitems>
``` | /content/code_sandbox/swipe-selector/src/androidTest/res/xml/swipe_items_harcoded.xml | xml | 2016-02-22T21:08:29 | 2024-04-24T16:49:21 | SwipeSelector | roughike/SwipeSelector | 1,089 | 110 |
```xml
/**
* Automatically generated by expo-modules-test-core.
*
* This autogenerated file provides a mock for native Expo module,
* and works out of the box with the expo jest preset.
* */
export async function isAvailableAsync(): Promise<any> {}
export async function setUpdateInterval(): Promise<any> {}
``` | /content/code_sandbox/packages/expo-sensors/mocks/ExponentAccelerometer.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 62 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
xmlns="path_to_url"
xmlns:activiti="path_to_url"
targetNamespace="Examples">
<process id="catchSignal">
<startEvent id="start" />
<sequenceFlow sourceRef="start" targetRef="waitState" />
<userTask id="waitState" name="Test User Task" />
<sequenceFlow sourceRef="waitState" targetRef="end" />
<endEvent id="end" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable-engine/src/test/resources/org/flowable/engine/test/bpmn/event/signal/SignalEventTest.testSignalUserTask.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 131 |
```xml
import { Flex, Spacer } from '@chakra-ui/react';
import { TabeDocumentation } from './components/table-document';
export const TablesMetadata = () => {
return (
<Flex px={3} pb={0} flexDirection="column" flex={1} width="100%">
<TabeDocumentation />
</Flex>
);
};
``` | /content/code_sandbox/src/renderer/views/admin/views/add/metadata/tables-metadata.tsx | xml | 2016-05-14T02:18:49 | 2024-08-16T02:46:28 | ElectroCRUD | garrylachman/ElectroCRUD | 1,538 | 73 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="path_to_url">
<item
android:drawable="@drawable/checked_bg"
android:state_checked="true"
>
</item>
<item
android:drawable="@drawable/normal_bg"/>
</selector>
``` | /content/code_sandbox/imitate/src/main/res/drawable/tag_bg.xml | xml | 2016-08-08T08:52:10 | 2024-08-12T19:24:13 | AndroidAnimationExercise | REBOOTERS/AndroidAnimationExercise | 1,868 | 70 |
```xml
import * as React from 'react';
import {
createPresenceComponentVariant,
Field,
makeStyles,
mergeClasses,
type MotionImperativeRef,
motionTokens,
Slider,
Switch,
tokens,
} from '@fluentui/react-components';
import { Collapse } from '@fluentui/react-motion-components-preview';
import description from './CollapseCustomization.stories.md';
const useClasses = makeStyles({
container: {
display: 'grid',
gridTemplate: `"controls ." "card card" / 1fr 1fr`,
gap: '20px 10px',
},
card: {
gridArea: 'card',
padding: '10px',
},
controls: {
display: 'flex',
flexDirection: 'column',
gridArea: 'controls',
border: `${tokens.strokeWidthThicker} solid ${tokens.colorNeutralForeground3}`,
borderRadius: tokens.borderRadiusMedium,
boxShadow: tokens.shadow16,
padding: '10px',
},
field: {
flex: 1,
},
sliderField: {
gridTemplateColumns: 'min-content 1fr',
},
sliderLabel: {
textWrap: 'nowrap',
},
item: {
backgroundColor: tokens.colorBrandBackground,
border: `${tokens.strokeWidthThicker} solid ${tokens.colorTransparentStroke}`,
borderRadius: '50%',
width: '100px',
height: '100px',
},
});
const CustomCollapseVariant = createPresenceComponentVariant(Collapse, {
enter: { duration: motionTokens.durationSlow, easing: motionTokens.curveEasyEaseMax },
exit: { duration: motionTokens.durationNormal, easing: motionTokens.curveEasyEaseMax },
});
const LoremIpsum = () => (
<>
{'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. '.repeat(
10,
)}
</>
);
export const Customization = () => {
const classes = useClasses();
const motionRef = React.useRef<MotionImperativeRef>();
const [animateOpacity, setAnimateOpacity] = React.useState(true);
const [playbackRate, setPlaybackRate] = React.useState<number>(30);
const [visible, setVisible] = React.useState<boolean>(true);
const [unmountOnExit, setUnmountOnExit] = React.useState<boolean>(false);
// Heads up!
// This is optional and is intended solely to slow down the animations, making motions more visible in the examples.
React.useEffect(() => {
motionRef.current?.setPlaybackRate(playbackRate / 100);
}, [playbackRate, visible]);
return (
<div className={classes.container}>
<div className={classes.controls}>
<Field className={classes.field}>
<Switch label="Visible" checked={visible} onChange={() => setVisible(v => !v)} />
</Field>
<Field className={classes.field}>
<Switch
label={<code>animateOpacity</code>}
checked={animateOpacity}
onChange={() => setAnimateOpacity(v => !v)}
/>
</Field>
<Field className={classes.field}>
<Switch
label={<code>unmountOnExit</code>}
checked={unmountOnExit}
onChange={() => setUnmountOnExit(v => !v)}
/>
</Field>
<Field
className={mergeClasses(classes.field, classes.sliderField)}
label={{
children: (
<>
<code>playbackRate</code>: {playbackRate}%
</>
),
className: classes.sliderLabel,
}}
orientation="horizontal"
>
<Slider
aria-valuetext={`Value is ${playbackRate}%`}
className={mergeClasses(classes.field, classes.sliderField)}
value={playbackRate}
onChange={(ev, data) => setPlaybackRate(data.value)}
min={0}
max={100}
step={5}
/>
</Field>
</div>
<CustomCollapseVariant
animateOpacity={animateOpacity}
imperativeRef={motionRef}
visible={visible}
unmountOnExit={unmountOnExit}
>
<div className={classes.card}>
<LoremIpsum />
</div>
</CustomCollapseVariant>
</div>
);
};
Customization.parameters = {
docs: {
description: {
story: description,
},
},
};
``` | /content/code_sandbox/packages/react-components/react-motion-components-preview/stories/src/Collapse/CollapseCustomization.stories.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 946 |
```xml
export { CreateNamespaceView } from './CreateNamespaceView';
``` | /content/code_sandbox/app/react/kubernetes/namespaces/CreateView/index.tsx | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 13 |
```xml
import * as React from 'react';
import createSvgIcon from '../utils/createSvgIcon';
const LaptopSelectedIcon = createSvgIcon({
svg: ({ classes }) => (
<svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false">
<path d="M1016 1592l72 72H128q-25 0-48-10t-41-29-28-41-11-48q0-16 3-36t10-39 16-36 22-30l205-206V384h1408v805l-91 91H347l-203 202q-3 3-6 10t-5 16-4 16-1 12h945l-57 56zm-632-440h1152V512H384v640zm1645 158l-557 557-269-269 90-91 179 179 467-467 90 91z" />
</svg>
),
displayName: 'LaptopSelectedIcon',
});
export default LaptopSelectedIcon;
``` | /content/code_sandbox/packages/react-icons-mdl2/src/components/LaptopSelectedIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 248 |
```xml
import styled from "@emotion/styled"
import { User } from "@signal-app/api"
import { observer } from "mobx-react-lite"
import { FC, useState } from "react"
import { Helmet } from "react-helmet-async"
import { Alert } from "../components/Alert.js"
import { CircularProgress } from "../components/CircularProgress.js"
import { UserSongList } from "../components/UserSongList.js"
import { useAsyncEffect } from "../hooks/useAsyncEffect.js"
import { useStores } from "../hooks/useStores.js"
import { PageLayout, PageTitle } from "../layouts/PageLayout.js"
import { Localized } from "../localize/useLocalization.js"
const Bio = styled.p`
margin-top: 1rem;
`
const SectionTitle = styled.h2`
margin-top: 2rem;
font-size: 1.5rem;
margin-bottom: 0.5rem;
`
export interface UserPageProps {
userId: string
}
export const UserPage: FC<UserPageProps> = observer(({ userId }) => {
const { userRepository } = useStores()
const [isLoading, setIsLoading] = useState(true)
const [user, setUser] = useState<User | null>(null)
const [error, setError] = useState<Error | null>(null)
useAsyncEffect(async () => {
try {
const user = await userRepository.get(userId)
setUser(user)
setIsLoading(false)
} catch (e) {
setError(e as Error)
}
}, [userId])
if (isLoading) {
return (
<PageLayout>
<PageTitle>User</PageTitle>
<CircularProgress /> Loading...
</PageLayout>
)
}
if (error !== null) {
return (
<PageLayout>
<PageTitle>User</PageTitle>
<Alert severity="warning">
Failed to load user profile: {error.message}
</Alert>
</PageLayout>
)
}
if (user === null) {
return (
<PageLayout>
<PageTitle>User</PageTitle>
<Alert severity="warning">
<Localized name="user-not-found" />
</Alert>
</PageLayout>
)
}
return (
<PageLayout>
<Helmet>
<title>{`${user.name} - signal`}</title>
</Helmet>
<PageTitle>{user.name}</PageTitle>
<Bio>{user.bio}</Bio>
<SectionTitle>
<Localized name="tracks" />
</SectionTitle>
<UserSongList userId={userId} />
</PageLayout>
)
})
``` | /content/code_sandbox/packages/community/src/pages/UserPage.tsx | xml | 2016-03-06T15:19:53 | 2024-08-15T14:27:10 | signal | ryohey/signal | 1,238 | 560 |
```xml
import { IUser } from "./IUser";
import { IUserPresence } from "./IUserPresence";
export interface IUserInfo extends IUser {
title:string;
pictureUrl?: string;
userUrl?:string;
presence?: IUserPresence;
id?:string;
}
``` | /content/code_sandbox/samples/react-modern-organization-chart/src/Entities/IUserInfo.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 57 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Galerie simple</string>
<string name="app_launcher_name">Galerie</string>
<string name="edit">Modifier</string>
<string name="open_camera">Ouvrir l\'appareil photo</string>
<string name="hidden">(cach)</string>
<string name="excluded">(exclu)</string>
<string name="pin_folder">pingler le dossier</string>
<string name="unpin_folder">Librer le dossier</string>
<string name="pin_to_the_top">pingler le dossier</string>
<string name="show_all">AffichageDossiers</string>
<string name="all_folders">Dossiers</string>
<string name="folder_view">AffichageGalerie</string>
<string name="other_folder">Autre dossier</string>
<string name="show_on_map">Afficher sur la carte</string>
<string name="unknown_location">Position inconnue</string>
<string name="volume">Volume</string>
<string name="brightness">Luminosit</string>
<string name="lock_orientation">Verrouiller la rotation</string>
<string name="unlock_orientation">Dverrouiller la rotation</string>
<string name="change_orientation">Orientation</string>
<string name="force_portrait">Forcer la vue portrait</string>
<string name="force_landscape">Forcer la vue paysage</string>
<string name="use_default_orientation">Utiliser l\'orientation par dfaut</string>
<string name="fix_date_taken">Corriger les dates de prise de vue</string>
<string name="fixing">Correction en cours</string>
<string name="dates_fixed_successfully">Dates corriges</string>
<string name="no_date_takens_found">Aucune date de prise de vue trouve</string>
<string name="share_resized">Partager une version redimensionne</string>
<string name="switch_to_file_search">Basculer vers la recherche de fichiers</string>
<string name="set_as_default_folder">Dossier par dfaut</string>
<string name="unset_as_default_folder">Oublier le dossier</string>
<string name="reorder_by_dragging">Rordonner par glisser</string>
<string name="reorder_by_dragging_pro">Rordonner par glisser (Pro)</string>
<string name="restore_to_path">Restauration vers "%s"</string>
<!-- Filter -->
<string name="filter_media">Filtrer les mdias</string>
<string name="images">Images</string>
<string name="videos">Vidos</string>
<string name="gifs">GIF</string>
<string name="raw_images">Images RAW</string>
<string name="svgs">SVG</string>
<string name="portraits">Portraits</string>
<string name="no_media_with_filters">Aucun fichier mdia trouv avec les filtres slectionns.</string>
<string name="change_filters_underlined"><u>Modifier les filtres</u></string>
<!-- Hide / Exclude -->
<string name="hide_folder_description">Cette option cache le dossier en y ajoutant un fichier .nomedia, elle cachera aussi tous les sous-dossiers. Vous pouvez afficher ces dossiers avec l\'option "Afficher les fichiers cachs" dans les paramtres. Continuer\?</string>
<string name="exclude_folder_description">La slection sera exclue ainsi que ses sous-dossiers dans "Galerie simple" uniquement. Vous pouvez grer les dossiers exclus depuis les paramtres.</string>
<string name="exclude_folder_parent">Exclure un dossier parent \?</string>
<string name="excluded_activity_placeholder">Exclure des dossiers les cachera ainsi que leurs sous-dossiers uniquement dans "Galerie simple", ils seront toujours visibles depuis d\'autres applications.
\n
\nSi vous voulez aussi les cacher ailleurs, utilisez la fonction Cacher.</string>
<string name="hidden_folders">Dossiers cachs</string>
<string name="manage_hidden_folders">Grer les dossiers cachs</string>
<string name="hidden_folders_placeholder">Il semblerait que vous n\'ayez pas de dossier cach par un fichier .nomedia.</string>
<string name="hidden_all_files">Vous devez accorder l\'application l\'accs tous les fichiers pour voir les fichiers cachs, sinon elle ne peut pas fonctionner.</string>
<string name="cant_unhide_folder">Si un dossier ou l\'un de ses dossiers parents a un point avant son nom, il est cach et ne peut pas tre affich comme ceci. Vous devez supprimer le point en le renommant.</string>
<!-- Include folders -->
<string name="include_folders">Dossiers ajouts</string>
<string name="manage_included_folders">Grer les dossiers ajouts</string>
<string name="add_folder">Ajouter un dossier</string>
<string name="included_activity_placeholder">Si vous avez des dossiers contenant des mdias qui ne sont pas affichs dans l\'application, vous pouvez les ajouter manuellement ici.
\n
\nCet ajout n\'exclura aucun autre dossier.</string>
<string name="no_media_add_included">Aucun fichier multimdia n\'a t trouv. Vous pouvez ajouter manuellement des dossiers contenant des fichiers multimdia.</string>
<!-- Resizing -->
<string name="resize_and_save">Redimensionner la slection et enregistrer</string>
<string name="width">Largeur</string>
<string name="height">Hauteur</string>
<string name="keep_aspect_ratio">Conserver le rapport d\'affichage</string>
<string name="invalid_values">Veuillez entrer une rsolution valide</string>
<string name="resize_multiple_images">Redimensionner plusieurs images</string>
<string name="resize_factor">Facteur de redimensionnement</string>
<string name="resize_factor_info">Redimensionner les images au pourcentage donn, la valeur doit tre comprise entre 10 et 90.</string>
<string name="resize_factor_error">Entrer un nombre entre 10 et 90</string>
<plurals name="failed_to_resize_images">
<item quantity="one">chec de redimensionnement de %d image</item>
<item quantity="many">chec de redimensionnement de %d images</item>
<item quantity="other">chec de redimensionnement de %d images</item>
</plurals>
<string name="images_resized_successfully">Les images ont t redimensionnes avec succs</string>
<!-- Editor -->
<string name="editor">diteur</string>
<string name="basic_editor">diteur simple</string>
<string name="advanced_editor">diteur avanc</string>
<string name="rotate">Pivoter</string>
<string name="invalid_image_path">Emplacement d\'image invalide</string>
<string name="invalid_video_path">Emplacement de vido invalide</string>
<string name="image_editing_failed">L\'dition de l\'image a chou</string>
<string name="video_editing_failed">L\'dition de la vido a chou</string>
<string name="image_editing_cancelled">L\'dition de l\'image a t annule</string>
<string name="video_editing_cancelled">L\'dition de la vido a t annule</string>
<string name="file_edited_successfully">Le fichier a t dit avec succs</string>
<string name="image_edited_successfully">L\'image a t dite avec succs</string>
<string name="video_edited_successfully">La vido a t dite avec succs</string>
<string name="edit_image_with">Modifier l\'image avec :</string>
<string name="edit_video_with">Modifier la vido avec :</string>
<string name="no_image_editor_found">Aucun diteur d\'image trouv</string>
<string name="no_video_editor_found">Aucun diteur de vido trouv</string>
<string name="unknown_file_location">Emplacement du fichier inconnu</string>
<string name="error_saving_file">Impossible de remplacer le fichier source</string>
<string name="rotate_left">Pivoter gauche</string>
<string name="rotate_right">Pivoter droite</string>
<string name="rotate_one_eighty">Pivoter 180</string>
<string name="transform">Transformer</string>
<string name="crop">Rogner</string>
<string name="draw">Dessiner</string>
<string name="flip">Retourner</string>
<string name="flip_horizontally">Retourner horizontalement</string>
<string name="flip_vertically">Retourner verticalement</string>
<string name="free_aspect_ratio">Libre</string>
<!-- available as an option: 1:1, 4:3, 16:9, free -->
<string name="other_aspect_ratio">Autre</string>
<!-- available as an option: 1:1, 4:3, 16:9, free, other -->
<!-- Set wallpaper -->
<string name="simple_wallpaper">Fond d\'cran simple</string>
<string name="set_as_wallpaper">Dfinir comme fond d\'cran</string>
<string name="set_as_wallpaper_failed">chec de la dfinition en tant que fond d\'cran</string>
<string name="set_as_wallpaper_with">Dfinir comme fond d\'cran avec :</string>
<string name="setting_wallpaper">Dfinition du fond d\'cran en cours</string>
<string name="wallpaper_set_successfully">Fond d\'cran dfini</string>
<string name="portrait_aspect_ratio">Rapport d\'affichage portrait</string>
<string name="landscape_aspect_ratio">Rapport d\'affichage paysage</string>
<string name="home_screen">cran d\'accueil</string>
<string name="lock_screen">cran de dverrouillage</string>
<string name="home_and_lock_screen">cran d\'accueil et cran de dverrouillage</string>
<string name="allow_changing_aspect_ratio">Autoriser la modification du rapport d\'aspect</string>
<!-- Slideshow -->
<string name="slideshow">Diaporama</string>
<string name="interval">Intervalle</string>
<string name="include_photos">Inclure les images</string>
<string name="include_videos">Inclure les vidos</string>
<string name="include_gifs">Inclure les GIF</string>
<string name="random_order">Ordre alatoire</string>
<string name="move_backwards">Dfilement invers</string>
<string name="loop_slideshow">Diaporama en boucle</string>
<string name="animation">Animation</string>
<string name="no_animation">Aucune</string>
<string name="fade">Fondu</string>
<string name="slide">Glissement</string>
<string name="slideshow_ended">Diaporama termin</string>
<string name="no_media_for_slideshow">Aucun mdia trouv pour le diaporama</string>
<!-- View types -->
<string name="group_direct_subfolders">Mode sous-dossiers</string>
<!-- Grouping at media thumbnails -->
<string name="group_by">Grouper par</string>
<string name="do_not_group_files">Ne pas grouper les fichiers</string>
<string name="by_folder">Dossier</string>
<string name="by_last_modified">Date de modification</string>
<string name="by_last_modified_daily">Date de modification (par jour)</string>
<string name="by_last_modified_monthly">Date de modification (par mois)</string>
<string name="by_date_taken">Date de prise de vue</string>
<string name="by_date_taken_daily">Date de prise de vue (par jour)</string>
<string name="by_date_taken_monthly">Date de prise de vue (par mois)</string>
<string name="by_file_type">Type de fichier</string>
<string name="by_extension">Extension</string>
<string name="show_file_count_section_header">Afficher le nombre d\'lments dans les enttes</string>
<string name="grouping_and_sorting">Grouper par et Trier par sont deux modes indpendants</string>
<!-- Widgets -->
<string name="folder_on_widget">Dossier affich dans le widget :</string>
<string name="show_folder_name">Afficher le nom du dossier</string>
<!-- Settings -->
<string name="autoplay_videos">Lecture automatique des vidos</string>
<string name="remember_last_video_position">Mmoriser la position de lecture des vidos</string>
<string name="loop_videos">Lecture en boucle des vidos</string>
<string name="animate_gifs">Animer les miniatures des GIF</string>
<string name="max_brightness">Luminosit maximale</string>
<string name="crop_thumbnails">Recadrer les miniatures en carr</string>
<string name="show_thumbnail_video_duration">Afficher la dure des vidos</string>
<string name="screen_rotation_by">Orientation de l\'affichage</string>
<string name="screen_rotation_system_setting">Paramtres systme</string>
<string name="screen_rotation_device_rotation">Rotation de l\'appareil</string>
<string name="screen_rotation_aspect_ratio">Rapport d\'affichage</string>
<string name="black_background_at_fullscreen">Arrire-plan et barre d\'tat noirs</string>
<string name="scroll_thumbnails_horizontally">Faire dfiler les miniatures horizontalement</string>
<string name="hide_system_ui_at_fullscreen">Cacher automatiquement l\'interface utilisateur</string>
<string name="delete_empty_folders">Supprimer les dossiers vides aprs avoir supprim leur contenu</string>
<string name="allow_photo_gestures">Contrler la luminosit des images par gestes verticaux</string>
<string name="allow_video_gestures">Contrler le volume et la luminosit des vidos avec des gestes verticaux</string>
<string name="show_media_count">Afficher le nombre de fichiers des dossiers</string>
<string name="show_extended_details">Afficher les informations supplmentaires du mdia en plein cran</string>
<string name="manage_extended_details">Grer les informations supplmentaires</string>
<string name="one_finger_zoom">Activer les zoom un doigt sur les images en plein cran</string>
<string name="allow_instant_change">Appuyer sur les cots de l\'cran pour changer instantanment de mdia</string>
<string name="allow_deep_zooming_images">Activer les options de zoom avances</string>
<string name="hide_extended_details">Cacher les informations supplmentaires si la barre d\'tat est masque</string>
<string name="show_at_bottom">Afficher les boutons d\'action</string>
<string name="show_recycle_bin">Afficher la corbeille en affichage Galerie</string>
<string name="deep_zoomable_images">Niveau de zoom</string>
<string name="show_highest_quality">Afficher les images dans la meilleure qualit possible</string>
<string name="show_recycle_bin_last">Afficher la corbeille en fin de liste sur l\'cran principal</string>
<string name="allow_down_gesture">Fermer la vue plein cran par un geste vers le bas</string>
<string name="allow_one_to_one_zoom">Permettre un zoom avant 1:1 par double appui</string>
<string name="open_videos_on_separate_screen">Ouvrir les vidos dans une application externe</string>
<string name="show_notch">Afficher une encoche si disponible</string>
<string name="allow_rotating_gestures">Pivoter les images par gestes</string>
<string name="file_loading_priority">Priorit de chargement des fichiers</string>
<string name="speed">Rapide</string>
<string name="compromise">Compromis</string>
<string name="avoid_showing_invalid_files">viter l\'affichage de fichiers invalides</string>
<string name="show_image_file_types">Afficher les types d\'image</string>
<string name="allow_zooming_videos">Zoomer les vidos par un double appui</string>
<string name="folder_thumbnail_style">Style des miniatures des dossiers</string>
<string name="file_thumbnail_style">Style des miniatures des fichiers</string>
<string name="mark_favorite_items">Marquer les lments favoris</string>
<string name="thumbnail_spacing">Espacement des miniatures</string>
<string name="show_file_count_line">Afficher le nombre de fichiers sur une autre ligne</string>
<string name="show_file_count_brackets">Afficher le nombre de fichiers entre parenthses</string>
<string name="show_file_count_none">Ne pas afficher le nombre de fichiers</string>
<string name="limit_folder_title">Limiter une ligne les noms de fichiers</string>
<string name="square">Carr</string>
<string name="rounded_corners">Arrondi</string>
<string name="export_favorite_paths">Exporter les favoris</string>
<string name="import_favorite_paths">Importer des favoris</string>
<string name="paths_imported_successfully">Favoris imports</string>
<string name="media_management_prompt">Pour vous assurer que toutes les oprations de fichiers fonctionnent de manire fiable, veuillez faire de cette application l\'application de gestion des mdias dans les paramtres de votre appareil.</string>
<string name="password_protect_excluded">Protection par mot de passe de la visibilit des dossiers exclus</string>
<string name="media_management_manual">Quelque chose s\'est mal pass, veuillez aller dans les paramtres de votre appareil - Applis - Accs aux applications spciales - Applis de gestion des mdias et autorisez cette application grer les mdias.</string>
<string name="media_management_note">Si la redirection ne fonctionne pas, allez dans les paramtres de votre appareil - Applis - Accs aux applications spciales - Applis de gestion des mdias et autorisez cette application grer les mdias.</string>
<string name="media_management_alternative">Si vous ne voulez pas le faire, vous pouvez aussi aller dans les Paramtres de votre appareil - Applis - Accs aux applications spciales - Applis de gestion des mdias et autoriser cette application grer les mdias.</string>
<string name="alternative_media_access">Vous pouvez galement n\'autoriser que l\'accs aux fichiers multimdias. Dans ce cas, vous ne pourrez cependant pas travailler avec les fichiers cachs.</string>
<string name="media_only">Mdias uniquement</string>
<string name="all_files">Tous les fichiers</string>
<string name="search_all_files">Rechercher des fichiers au lieu des dossiers sur l\'cran principal</string>
<string name="show_all_folders">Afficher un bouton de menu pour afficher rapidement le contenu de tous les dossiers</string>
<!-- Setting sections -->
<string name="thumbnails">Miniatures</string>
<string name="fullscreen_media">Plein cran</string>
<string name="extended_details">Dtails supplmentaires</string>
<string name="bottom_actions">Barre d\'actions</string>
<!-- Bottom actions -->
<string name="manage_bottom_actions">Grer la barre d\'actions</string>
<string name="toggle_favorite">Activer/dsactiver le favori</string>
<string name="toggle_file_visibility">Visibilit du fichier</string>
<!-- New editor strings -->
<string name="pesdk_transform_button_freeCrop">Libre</string>
<string name="pesdk_transform_button_resetCrop">Rinitialiser</string>
<string name="pesdk_transform_button_squareCrop">Carr</string>
<string name="pesdk_transform_title_name">Transformer</string>
<string name="pesdk_filter_title_name">Filtres</string>
<string name="pesdk_filter_asset_none">Aucun</string>
<string name="pesdk_adjustments_title_name">Ajuster</string>
<string name="pesdk_adjustments_button_shadowTool">Ombres</string>
<string name="pesdk_adjustments_button_exposureTool">Exposition</string>
<string name="pesdk_adjustments_button_highlightTool">Dtails</string>
<string name="pesdk_adjustments_button_brightnessTool">Luminosit</string>
<string name="pesdk_adjustments_button_contrastTool">Contraste</string>
<string name="pesdk_adjustments_button_saturationTool">Saturation</string>
<string name="pesdk_adjustments_button_clarityTool">Clart</string>
<string name="pesdk_adjustments_button_gammaTool">Gamma</string>
<string name="pesdk_adjustments_button_blacksTool">Noirs</string>
<string name="pesdk_adjustments_button_whitesTool">Blancs</string>
<string name="pesdk_adjustments_button_temperatureTool">Temprature</string>
<string name="pesdk_adjustments_button_sharpnessTool">Nettet</string>
<string name="pesdk_adjustments_button_reset">Rinitialiser</string>
<string name="pesdk_focus_title_name">Floutage</string>
<string name="pesdk_focus_title_disabled">Aucun</string>
<string name="pesdk_focus_button_radial">Radial</string>
<string name="pesdk_focus_button_linear">Linaire</string>
<string name="pesdk_focus_button_mirrored">Miroir</string>
<string name="pesdk_focus_button_gaussian">Gaussien</string>
<string name="pesdk_text_title_input">Ajouter un texte</string>
<string name="pesdk_text_title_name">Texte</string>
<string name="pesdk_text_title_options">Options du texte</string>
<string name="pesdk_text_title_textColor">Couleur du texte</string>
<string name="pesdk_text_title_font">Police</string>
<string name="pesdk_text_button_add">Ajouter</string>
<string name="pesdk_text_button_edit">diter</string>
<string name="pesdk_text_button_straighten">Redresser</string>
<string name="pesdk_text_button_font">Police</string>
<string name="pesdk_text_button_color">Couleur</string>
<string name="pesdk_text_button_backgroundColor">Fond</string>
<string name="pesdk_text_button_alignment">Alignement</string>
<string name="pesdk_text_button_bringToFront">Devant</string>
<string name="pesdk_text_button_delete">Supprimer</string>
<string name="pesdk_text_text_editTextPlaceholder">Votre texte</string>
<string name="pesdk_brush_title_name">Pinceau</string>
<string name="pesdk_brush_button_color">Couleur</string>
<string name="pesdk_brush_button_size">Taille</string>
<string name="pesdk_brush_button_hardness">Contour</string>
<string name="pesdk_brush_button_bringToFront">Devant</string>
<string name="pesdk_brush_button_delete">Supprimer</string>
<string name="pesdk_brush_title_brushColor">Couleur du pinceau</string>
<string name="pesdk_editor_title_name">diteur</string>
<string name="pesdk_editor_title_closeEditorAlert">Fermer l\'diteur \?</string>
<string name="pesdk_editor_text_closeEditorAlert">Voulez-vous vraiment abandonner les modifications \?</string>
<string name="pesdk_editor_button_closeEditorAlertConfirmation">Oui</string>
<string name="pesdk_editor_button_closeEditorAlertCancelation">Non</string>
<string name="pesdk_editor_cancel">Annuler</string>
<string name="pesdk_editor_accept">Accepter</string>
<string name="pesdk_editor_save">Enregistrer</string>
<string name="pesdk_editor_text_exportProgressUnknown">Exportation</string>
<string name="pesdk_editor_text_exportProgress" formatted="false">Exportation %s</string>
<string name="pesdk_sticker_title_name">Autocollant</string>
<string name="pesdk_sticker_title_color">Couleur de l\'autocollant</string>
<string name="pesdk_sticker_title_options">Options de l\'autocollant</string>
<string name="pesdk_sticker_button_add">Ajouter</string>
<string name="pesdk_sticker_button_color">Couleur</string>
<string name="pesdk_sticker_button_delete">Supprimer</string>
<string name="pesdk_sticker_button_bringToFront">Devant</string>
<string name="pesdk_sticker_button_straighten">Redresser</string>
<string name="pesdk_sticker_button_replace">Remplacer</string>
<string name="pesdk_sticker_button_opacity">Transparence</string>
<string name="pesdk_sticker_button_contrast">Contraste</string>
<string name="pesdk_sticker_button_saturation">Saturation</string>
<string name="pesdk_sticker_button_brightness">Luminosit</string>
<string name="pesdk_sticker_category_name_custom">Tlversements</string>
<string name="pesdk_overlay_title_name">Superposition</string>
<string name="pesdk_overlay_button_blendModeNormal">Normal</string>
<string name="pesdk_overlay_button_blendModeDarken">Assombrir</string>
<string name="pesdk_overlay_button_blendModeScreen">cran</string>
<string name="pesdk_overlay_button_blendModeOverlay">Recouvrir</string>
<string name="pesdk_overlay_button_blendModeLighten">Allger</string>
<string name="pesdk_overlay_button_blendModeMultiply">Dupliquer</string>
<string name="pesdk_overlay_button_blendModeColorBurn">Brlure de couleur</string>
<string name="pesdk_overlay_button_blendModeSoftLight">Lumire douce</string>
<string name="pesdk_overlay_button_blendModeHardLight">Lumire forte</string>
<string name="pesdk_overlay_asset_none">Aucune</string>
<string name="pesdk_overlay_asset_golden">Dor</string>
<string name="pesdk_overlay_asset_lightleak1">Fuite lgre 1</string>
<string name="pesdk_overlay_asset_mosaic">Mosaque</string>
<string name="pesdk_overlay_asset_paper">Papier</string>
<string name="pesdk_overlay_asset_rain">Pluie</string>
<string name="pesdk_overlay_asset_vintage">Vintage</string>
<string name="pesdk_common_button_flipH">Symtrie H</string>
<string name="pesdk_common_button_flipV">Symtrie V</string>
<string name="pesdk_common_button_undo">Annuler</string>
<string name="pesdk_common_button_redo">Refaire</string>
<string name="pesdk_common_title_colorPicker">Slecteur de couleur</string>
<string name="pesdk_common_title_transparentColor">Transparent</string>
<string name="pesdk_common_title_whiteColor">Blanc</string>
<string name="pesdk_common_title_grayColor">Gris</string>
<string name="pesdk_common_title_blackColor">Noir</string>
<string name="pesdk_common_title_lightBlueColor">Bleu clair</string>
<string name="pesdk_common_title_blueColor">Bleu</string>
<string name="pesdk_common_title_purpleColor">Violet</string>
<string name="pesdk_common_title_orchidColor">Orchide</string>
<string name="pesdk_common_title_pinkColor">Rose</string>
<string name="pesdk_common_title_redColor">Rouge</string>
<string name="pesdk_common_title_orangeColor">Orange</string>
<string name="pesdk_common_title_goldColor">Or</string>
<string name="pesdk_common_title_yellowColor">Jaune</string>
<string name="pesdk_common_title_oliveColor">Olive</string>
<string name="pesdk_common_title_greenColor">Vert</string>
<string name="pesdk_common_title_aquamarinColor">Aquamarin</string>
<string name="pesdk_common_title_pipettableColor">Couleur de la pipette</string>
<string name="vesdk_video_trim_title_name">Couper</string>
<!-- FAQ -->
<string name="faq_1_title">Comment faire de "Galerie simple" ma galerie par dfaut\?</string>
<string name="faq_1_text">Il faut dans un premier temps, trouver l\'application Galerie par dfaut dans la section Applications des paramtres de l\'appareil, puis appuyer sur "Ouvrir par dfaut", et enfin slectionner "Rinitialiser les paramtres par dfaut". La prochaine fois que vous ouvrirez une image ou une vido, il vous sera propos de choisir une application, choisissez "Galerie simple" puis "Toujours".</string>
<string name="faq_2_title">J\'ai verrouill l\'application avec un mot de passe et je ne m\'en rappelle plus. Que faire \?</string>
<string name="faq_2_text">Il y a deux faons de procder. Soit vous rinstallez l\'application, soit vous recherchez l\'application dans les paramtres de l\'appareil et appuyez sur "Supprimer les donnes". Ceci rinitialisera seulement les paramtres de l\'application et ne supprimera pas vos fichiers.</string>
<string name="faq_3_title">Comment faire pour qu\'un dossier soit toujours affich tout en haut \?</string>
<string name="faq_3_text">Vous devez simplement effectuer un appui prolong sur le dossier en question et choisir "pingler en haut" dans le menu d\'actions. Vous pouvez en pingler plusieurs. Les lments pingls seront alors tris selon l\'ordre par dfaut.</string>
<string name="faq_4_title">Comment avancer rapidement dans les vidos \?</string>
<string name="faq_4_text">Appuyez deux fois sur le ct de l\'cran, ou appuyez sur la valeur de dure actuelle ou maximale prs de la barre de recherche. Si vous activez l\'ouverture des vidos sur un cran spar dans les paramtres de l\'application, vous pouvez galement utiliser des gestes horizontaux.</string>
<string name="faq_5_title">Quelle est la diffrence entre cacher et exclure un dossier\?</string>
<string name="faq_5_text">Exclure un dossier permet de ne pas l\'afficher uniquement dans "Galerie simple", alors que cacher un dossier rend le dossier invisible sur l\'ensemble de l\'appareil, y compris pour les autres applications de galerie. Dans le dernier cas, un fichier .nomedia est cr dans le dossier cach, et peut tre supprim avec n\'importe quel explorateur de fichiers. Notez que certains appareils ne permettent pas de cacher certains dossiers tels qu\'Appareil photo, Captures d\'cran et Tlchargements.</string>
<string name="faq_6_title">Pourquoi des dossiers avec des pochettes d\'albums musicaux ou des miniatures d\'images sont affichs \?</string>
<string name="faq_6_text">Il est possible que des dossiers qui ne devraient pas tre affichs le soient. Vous pouvez les exclure facilement en les slectionnant par un appui prolong, puis en choisissant l\'option "Exclure le dossier", aprs quoi vous pouvez aussi slectionner le dossier parent, ce qui devrait viter l\'apparition de dossiers similaires.</string>
<string name="faq_7_title">Un dossier avec des images n\'apparat pas. Que faire \?</string>
<string name="faq_7_text">Cela peut arriver pour de multiples raisons, mais c\'est facile rsoudre. Allez dans Paramtres, puis Grer les dossiers ajouts, appuyez sur + et slectionnez le dossier voulu.</string>
<string name="faq_8_title">Comment faire apparatre uniquement certains dossiers \?</string>
<string name="faq_8_text">Ajouter un dossier dans les "Dossiers ajouts" rend visible l\'ensemble du contenu du dossier. Pour exclure certains dossiers, il faut aller dans Paramtres, puis "Grer les dossiers exclus", exclure le dossier racine /, puis ajouter les dossiers souhaits dans "Paramtres", puis "Grer les dossiers ajouts". Seuls les dossiers slectionns seront visibles, du fait que les exclusions et inclusions sont rcursives, et si un dossier est la fois exclus et inclus, il sera affich.</string>
<string name="faq_10_title">Puis-je recadrer des images avec cette application \?</string>
<string name="faq_10_text">Oui, vous pouvez recadrer les images dans l\'diteur en faisant glisser les coins de l\'image. Vous pouvez accder l\'diteur en appuyant longuement sur une vignette d\'image et en slectionnant "Modifier", ou en slectionnant "Modifier" en mode plein cran.</string>
<string name="faq_11_title">Puis-je regrouper les miniatures des fichiers multimdias \?</string>
<string name="faq_11_text">Bien sr, il vous suffit d\'utiliser l\'option de menu "Grouper par" lorsque vous tes dans l\'affichage des miniatures. Vous pouvez regrouper les fichiers selon plusieurs critres, y compris la date de prise de vue. Si vous utilisez la fonction "Afficher tous les contenus", vous pouvez galement les regrouper par dossier.</string>
<string name="faq_12_title">Le tri par date de prise de vue ne semble pas fonctionner correctement, comment puis-je le corriger \?</string>
<string name="faq_12_text">Cela est probablement d au fait que les fichiers ont t copis depuis quelque part. Vous pouvez corriger cela en slectionnant les miniatures de fichier et en slectionnant "Corriger les dates de prise de vue".</string>
<string name="faq_13_title">Je vois des bandes de couleurs sur les images. Comment puis-je amliorer la qualit \?</string>
<string name="faq_13_text">La solution actuelle d\'affichage des images fonctionne bien dans la grande majorit des cas, mais si vous voulez une qualit d\'image encore meilleure, vous pouvez activer l\'option "Afficher les images dans la meilleure qualit possible" dans la section "Niveau de zoom" des paramtres de l\'application.</string>
<string name="faq_14_title">J\'ai cach un fichier ou un dossier. Comment puis-je en rtablir l\'affichage \?</string>
<string name="faq_14_text">Vous pouvez soit appuyer sur l\'option "Afficher les fichiers cachs" du menu de l\'cran principal, ou appuyer sur le bouton "Afficher les fichiers cachs" dans les paramtres de l\'application. Si vous voulez rtablir leur affichage, effectuez un appui prolong dessus et appuyez sur le symbole "il" permettant l\'affichage. Les dossiers sont cachs en ajoutant un fichier .nomedia leur racine, vous pouvez galement supprimer ce fichier avec n\'importe quel explorateur de fichiers. Notez que le masquage fonctionne de manire rcursive, donc si vous masquez un dossier, tous les sous-dossiers seront galement masqus. Donc, pour afficher les sous-dossiers, vous devez afficher le dossier parent.</string>
<string name="faq_15_title">Pourquoi l\'application prend-elle tant de place \?</string>
<string name="faq_15_text">Le cache d\'application peut prendre jusqu\' 250 Mo pour acclrer le chargement des images. Si l\'application occupe encore plus d\'espace, c\'est probablement parce que vous avez des lments dans la corbeille. Ces fichiers comptent pour la taille de l\'application. Vous pouvez vider la corbeille en l\'ouvrant et en supprimant tous les fichiers ou partir des paramtres de l\'application. Chaque fichier de la corbeille est automatiquement supprim aprs 30 jours.</string>
<string name="faq_16_title">Qu\'est ce qui se passe avec les fichiers et dossiers cachs et pourquoi je ne peux plus les voir\?</string>
<string name="faq_16_text"> partir d\'Android 11, vous ne pouvez plus cacher ou afficher des fichiers ou des dossiers, et vous ne pouvez pas non plus voir ceux qui sont masqus dans les applications de la galerie. Vous devrez utiliser un gestionnaire de fichiers pour cela.</string>
<string name="faq_16_text_extra">Vous pouvez galement accorder cette galerie l\'accs tous les fichiers via les paramtres de votre appareil, ce qui nous permettra de montrer les lments cachs et de rendre les oprations sur les fichiers plus fiables en gnral.</string>
<string name="faq_17_title">Pourquoi je ne peux plus inclure des dossiers manquants\?</string>
<string name="faq_17_text">Cette fonctionnalit ne fonctionne plus en raison des modifications apportes au systme avec Android 11. L\'application ne peut plus parcourir les dossiers rels, elle s\'appuie sur le MediaStore pour rcuprer les donnes.</string>
<string name="faq_18_title">Pourquoi des publicits apparaissent pendant la lecture d\'une vido\?</string>
<string name="faq_18_text">Nos applications ne comportent aucune publicit. Si vous en voyez pendant la lecture d\'une vido, vous devez srement utiliser le lecteur vido d\'une autre application. Essayez de trouver le lecteur vido par dfaut dans les paramtres de votre appareil, puis faites "Supprimer les valeurs par dfaut". Lors du prochain lancement d\'une vido, une invite de slection d\'application s\'affichera, et vous pourrez choisir l\'application que vous souhaitez utiliser.</string>
<!--
Haven't found some strings? There's more at
path_to_url
-->
</resources>
``` | /content/code_sandbox/app/src/main/res/values-fr/strings.xml | xml | 2016-02-16T21:17:13 | 2024-08-16T15:29:22 | Simple-Gallery | SimpleMobileTools/Simple-Gallery | 3,580 | 9,005 |
```xml
import * as React from 'react';
import Moment from 'react-moment';
import { WebPartTitle } from '@pnp/spfx-controls-react/lib/WebPartTitle';
import { Placeholder } from '@pnp/spfx-controls-react/lib/Placeholder';
import { List } from '@fluentui/react/lib/List';
import { Link } from '@fluentui/react/lib/Link';
import { Label } from '@fluentui/react/lib/Label';
import { Icon } from '@fluentui/react/lib/Icon';
import { Spinner, SpinnerSize } from '@fluentui/react/lib/Spinner';
import * as strings from 'RssReaderWebPartStrings';
import styles from './RssReader.module.scss';
import { IRssReaderProps, IRssReaderState } from './';
import { RssResultsTemplate } from '../Layouts';
import { RssReaderService, IRssReaderService } from '../../../../services/RssReaderService';
import {
IRssReaderResponse,
IRssResult,
IRssItem,
IRssReaderRequest,
FeedLayoutOption } from '../../../../models';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
export default class RssReader extends React.Component<IRssReaderProps, IRssReaderState> {
private viewAllLinkLabel: string = strings.DefaultFeedViewAllLinkLabel;
private feedLoadingLabel: string = strings.DefaultFeedLoadingLabel;
private themeVariant: IReadonlyTheme;
constructor(props:IRssReaderProps) {
super(props);
//override default label values if needed
if (this.props.feedViewAllLinkLabel && this.props.feedViewAllLinkLabel.length > 0) {
this.viewAllLinkLabel = this.props.feedViewAllLinkLabel;
}
if (this.props.feedLoadingLabel && this.props.feedLoadingLabel.length > 0) {
this.feedLoadingLabel = this.props.feedLoadingLabel;
}
this.state = {
rssFeedReady: false,
rssFeed: {} as IRssReaderResponse,
rssFeedError: ''
};
this.themeVariant = this.props.themeVariant;
//load the rss feed
this.loadRssFeed();
}
public render(): React.ReactElement<IRssReaderProps> {
return (
<div className={ styles.rssReader } style={{backgroundColor: this.themeVariant.semanticColors.bodyBackground}}>
<div className={styles.rssReaderHeader}>
<WebPartTitle displayMode={this.props.displayMode}
title={this.props.title}
updateProperty={this.props.updateProperty}
themeVariant={this.props.themeVariant}
moreLink={this.state.rssFeedReady && this.state.rssFeed && this.props.feedViewAllLink && this.props.feedViewAllLink.length > 0 && (
<Link style={{color: this.themeVariant.semanticColors.link}} href={this.props.feedViewAllLink}>{this.viewAllLinkLabel}</Link>
)}/>
</div>
{!this.props.feedUrl || this.props.feedUrl.length < 1 ? (
<Placeholder
iconName='Edit'
iconText='Configure your web part'
description='Please configure the web part.'
buttonLabel='Configure'
onConfigure={this._onConfigure} />
) : (
<div>
{!this.state.rssFeedReady ? (
<div>
{this.state.rssFeedError ? (
<div className={styles.messageError}>
<Icon
iconName={"Warning"}
className={styles.messageErrorIcon}
/>
<Label className={styles.messageErrorLabel}>{strings.RssLoadError + ' - ' + this.state.rssFeedError}</Label>
</div>
) : (
<Spinner size={SpinnerSize.large} label={this.feedLoadingLabel} />
)}
</div>
) : (
<div>
{this.state.rssFeed ? (
<div>
{this.props.selectedLayout === FeedLayoutOption.Default && (
<List
className={styles.rssReaderList + (this.props.backgroundColor ? " " + styles.rssReaderListPadding : "")}
items={this.state.rssFeed.query.results.rss}
onRenderCell={this._onRenderListRow}
style={this.props.useThemeBackgroundColor ? {backgroundColor: this.themeVariant.semanticColors.bodyBackground} : this.props.backgroundColor ? {backgroundColor: this.props.backgroundColor} : {}}
/>
)}
{this.props.selectedLayout === FeedLayoutOption.Custom && (
<div>
<RssResultsTemplate
templateService={this.props.templateService}
templateContent={this.props.templateContent}
templateContext={
{
items: this.state.rssFeed.query.results.rss,
totalItemCount: this.state.rssFeedReady ? this.state.rssFeed.query.count : 0,
returnedItemCount: this.state.rssFeedReady ? this.state.rssFeed.query.results.rss.length : 0,
strings: strings,
}
}
/>
</div>
)}
</div>
) : (
<div>
<Spinner size={SpinnerSize.large} label={strings.NoReturnedFeed} />
</div>
)}
</div>
)}
</div>
)}
</div>
);
}
public componentDidUpdate(prevProps: any): void {
//if specific resources change, we need to reload feed
if(this.props.feedUrl !== prevProps.feedUrl ||
this.props.feedService !== prevProps.feedService ||
this.props.feedServiceApiKey !== prevProps.feedServiceApiKey ||
this.props.feedServiceUrl !== prevProps.feedServiceUrl ||
this.props.useCorsProxy !== prevProps.useCorsProxy ||
this.props.corsProxyUrl !== prevProps.corsProxyUrl ||
this.props.disableCorsMode !== prevProps.disableCorsMode ||
this.props.maxCount !== prevProps.maxCount ||
this.props.selectedLayout !== prevProps.selectedLayout ||
this.props.externalTemplateUrl !== prevProps.externalTemplateUrl ||
this.props.inlineTemplateText !== prevProps.inlineTemplateText ||
this.props.showDesc !== prevProps.showDesc ||
this.props.showPubDate !== prevProps.showPubDate ||
this.props.descCharacterLimit !== prevProps.descCharacterLimit ||
this.props.titleLinkTarget !== prevProps.titleLinkTarget ||
this.props.dateFormat !== prevProps.dateFormat ||
this.props.backgroundColor !== prevProps.backgroundColor ||
this.props.useThemeBackgroundColor !== prevProps.useThemeBackgroundColor ||
this.props.useThemeFontColor !== prevProps.useThemeFontColor ||
this.props.fontColor !== prevProps.fontColor ||
this.props.themeVariant !== prevProps.themeVariant
) {
this.loadRssFeed();
}
if(this.props.feedViewAllLinkLabel !== prevProps.feedViewAllLinkLabel) {
this.viewAllLinkLabel = this.props.feedViewAllLinkLabel;
}
if(this.props.feedLoadingLabel !== prevProps.feedLoadingLabel) {
this.feedLoadingLabel = this.props.feedLoadingLabel;
}
}
private _onConfigure = (): void => {
this.props.propertyPane.open();
}
private decodeHtml = (html: string): string => {
const txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
/*
_onReaderListRow used by Default feed Layout
*/
private _onRenderListRow = (item: IRssResult, index: number | undefined): JSX.Element => {
const thisItem: IRssItem = item.channel.item;
//may need to strip html from description
let displayDesc: string = thisItem.description;
const div = document.createElement("div");
div.innerHTML = displayDesc;
displayDesc = (div.textContent || div.innerText || "").replace(/ /ig, "").trim();
return (
<div className={styles.rssReaderListItem} data-is-focusable={true}>
<div className={styles.itemTitle}>
<Link
href={thisItem.link}
target={this.props.titleLinkTarget ? this.props.titleLinkTarget : "_self"}
style={this.props.useThemeFontColor ? {color: this.themeVariant.semanticColors.link} : this.props.fontColor ? {color: this.props.fontColor} : {}}
>
{this.decodeHtml(thisItem.title)}
</Link>
</div>
{this.props.showPubDate && (
<div className={styles.itemDate} style={{color: this.themeVariant.semanticColors.bodySubtext}}>
{this.props.dateFormat && this.props.dateFormat.length > 0 ? (
<Moment
format={this.props.dateFormat}
date={thisItem.pubDate}
/>
) : (
<div>{(new Date(thisItem.pubDate)).toLocaleDateString()}</div>
)}
</div>
)}
{this.props.showDesc && (
<div className={styles.itemContent} style={{color: this.themeVariant.semanticColors.bodyText}}>
{this.props.descCharacterLimit && (displayDesc.length > this.props.descCharacterLimit) ? (
<div>
{displayDesc.substring(0, this.props.descCharacterLimit) + '...'}
</div>
) :
(
<div>
{displayDesc}
</div>
)}
</div>
)}
</div>
);
}
/*
load a rss feed based on properties
*/
private loadRssFeed = async (): Promise<void> => {
//require a feed url
if (this.props.feedUrl && this.props.feedUrl.length > 0) {
//always reset set
this.setState({rssFeedReady: false, rssFeed: null});
const rssReaderService: IRssReaderService = new RssReaderService();
//build the query
const feedRequest: IRssReaderRequest = {} as IRssReaderRequest;
feedRequest.url = this.props.feedUrl;
feedRequest.feedService = this.props.feedService;
feedRequest.feedServiceApiKey = this.props.feedServiceApiKey;
feedRequest.feedServiceUrl = this.props.feedServiceUrl;
//cors
feedRequest.useCorsProxy = this.props.useCorsProxy;
if (this.props.useCorsProxy) {
feedRequest.corsProxyUrl = this.props.corsProxyUrl;
}
feedRequest.disableCorsMode = this.props.disableCorsMode;
feedRequest.maxCount = this.props.maxCount;
//local storage / caching
feedRequest.useLocalStorage = this.props.cacheResults;
if (this.props.cacheResults) {
feedRequest.useLocalStorageTimeout = this.props.cacheResultsMinutes;
feedRequest.useLocalStorageKeyPrefix = this.props.cacheStorageKeyPrefix;
}
try {
//attempt to get feed
const rssFeed: IRssReaderResponse = await rssReaderService.getFeed(feedRequest);
if (rssFeed && rssFeed.query && rssFeed.query.results) {
this.setState({
rssFeedReady: true,
rssFeed: rssFeed,
rssFeedError: ""
});
}
else {
this.setState({
rssFeedReady: true,
rssFeed: null,
rssFeedError: strings.ErrorNoResults
});
}
}
catch (error) {
this.setState({
rssFeedReady: false,
rssFeed: null,
rssFeedError: error
});
}
}
}
}
``` | /content/code_sandbox/samples/react-rss-reader/src/webparts/rssReader/components/RssReader/RssReader.tsx | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 2,411 |
```xml
import { ItemLayout } from '@fluentui/react-northstar';
import * as React from 'react';
const ItemLayoutMinimalPerf = () => <ItemLayout />;
ItemLayoutMinimalPerf.iterations = 5000;
ItemLayoutMinimalPerf.filename = 'ItemLayoutMinimal.perf.tsx';
export default ItemLayoutMinimalPerf;
``` | /content/code_sandbox/packages/fluentui/docs/src/examples/components/ItemLayout/Performance/ItemLayoutMinimal.perf.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 74 |
```xml
import fs from "fs";
import path from "path";
import crypto from "crypto";
import {expect} from "chai";
import util from "../util";
import Config from "../../server/config";
import storage from "../../server/plugins/storage";
import link from "../../server/plugins/irc-events/link";
import {Request, Response} from "express";
describe("Image storage", function () {
// Increase timeout due to unpredictable I/O on CI services
this.timeout(util.isRunningOnCI() ? 25000 : 5000);
this.slow(300);
const testImagePath = path.resolve(__dirname, "../../client/img/logo-grey-bg-120x120px.png");
const correctImageHash = crypto
.createHash("sha256")
.update(fs.readFileSync(testImagePath))
.digest("hex");
const correctImageURL = `storage/${correctImageHash.substring(
0,
2
)}/${correctImageHash.substring(2, 4)}/${correctImageHash.substring(4)}.png`;
const testSvgPath = path.resolve(__dirname, "../../client/img/logo-grey-bg.svg");
const correctSvgHash = crypto
.createHash("sha256")
.update(fs.readFileSync(testSvgPath))
.digest("hex");
const correctSvgURL = `storage/${correctSvgHash.substring(0, 2)}/${correctSvgHash.substring(
2,
4
)}/${correctSvgHash.substring(4)}.svg`;
before(function (done) {
this.app = util.createWebserver();
this.app.get("/real-test-image.png", function (req, res) {
res.sendFile(testImagePath);
});
this.app.get("/logo.svg", function (req, res) {
res.sendFile(testSvgPath);
});
this.connection = this.app.listen(0, "127.0.0.1", () => {
this.port = this.connection.address().port;
this.host = this.connection.address().address;
done();
});
this._makeUrl = (_path: string): string => `path_to_url{this.host}:${this.port}/${_path}`;
});
after(function (done) {
this.connection.close(done);
});
after(function (done) {
// After storage tests run, remove the remaining empty
// storage folder so we return to the clean state
const dir = Config.getStoragePath();
fs.rmdir(dir, done);
});
beforeEach(function () {
this.irc = util.createClient();
this.network = util.createNetwork();
Config.values.prefetchStorage = true;
});
afterEach(function () {
Config.values.prefetchStorage = false;
});
it("should store the thumbnail", function (done) {
const thumb_url = this._makeUrl("thumb");
const message = this.irc.createMessage({
text: thumb_url,
});
link(this.irc, this.network.channels[0], message, message.text);
const real_test_img_url = this._makeUrl("real-test-image.png");
this.app.get("/thumb", function (req, res) {
res.send(
`<title>Google</title><meta property='og:image' content='${real_test_img_url}'>`
);
});
this.irc.once("msg:preview", function (data) {
expect(data.preview.head).to.equal("Google");
expect(data.preview.link).to.equal(thumb_url);
expect(data.preview.thumb).to.equal(correctImageURL);
done();
});
});
it("should store the image", function (done) {
const real_test_img_url = this._makeUrl("real-test-image.png");
const message = this.irc.createMessage({
text: real_test_img_url,
});
link(this.irc, this.network.channels[0], message, message.text);
this.irc.once("msg:preview", function (data) {
expect(data.preview.type).to.equal("image");
expect(data.preview.link).to.equal(real_test_img_url);
expect(data.preview.thumb).to.equal(correctImageURL);
done();
});
});
it("should lookup correct extension type", function (done) {
const msg_url = this._makeUrl("svg-preview");
const message = this.irc.createMessage({
text: msg_url,
});
const logo_url = this._makeUrl("logo.svg");
this.app.get("/svg-preview", function (req: Request, res: Response) {
res.send(`<title>test title</title><meta property='og:image' content='${logo_url}'>`);
});
link(this.irc, this.network.channels[0], message, message.text);
this.irc.once("msg:preview", function (data) {
expect(data.preview.type).to.equal("link");
expect(data.preview.link).to.equal(msg_url);
expect(data.preview.thumb).to.equal(correctSvgURL);
done();
});
});
it("should clear storage folder", function () {
const dir = Config.getStoragePath();
expect(fs.readdirSync(dir)).to.not.be.empty;
storage.emptyDir();
expect(fs.readdirSync(dir)).to.be.empty;
expect(fs.existsSync(dir)).to.be.true;
});
});
``` | /content/code_sandbox/test/plugins/storage.ts | xml | 2016-02-09T03:16:03 | 2024-08-16T10:52:38 | thelounge | thelounge/thelounge | 5,518 | 1,109 |
```xml
import {OpenSpecTypes} from "../common/OpenSpecTypes.js";
import {OS2BaseSchema, OS2Schema} from "./OS2Schema.js";
export type OS2BaseParameter = {
name: string;
in: "body" | "query" | "path" | "header" | "formData";
required?: boolean;
description?: string;
};
export type OS2BodyParameter = OS2BaseParameter & {
in: "body";
schema?: OS2Schema;
};
export type OS2GenericFormat = {
type?: OpenSpecTypes;
format?: string;
};
export type OS2IntegerFormat = {
type: "integer";
format?: "int32" | "int64";
};
export type OS2NumberFormat = {
type: "number";
format?: "float" | "double";
};
export type OS2StringFormat = {
type: "string";
format?: "" | "byte" | "binary" | "date" | "date-time" | "password";
};
export type OS2SchemaFormatConstraints = OS2GenericFormat | OS2IntegerFormat | OS2NumberFormat | OS2StringFormat;
export type OS2BaseFormatContrainedParameter = OS2BaseParameter & OS2SchemaFormatConstraints;
export type ParameterCollectionFormat = "csv" | "ssv" | "tsv" | "pipes" | "multi";
export type OS2QueryParameter = OS2BaseFormatContrainedParameter &
OS2BaseSchema & {
in: "query";
allowEmptyValue?: boolean;
collectionFormat?: ParameterCollectionFormat;
};
export type OS2PathParameter = OS2BaseFormatContrainedParameter &
OS2BaseSchema & {
in: "path";
required: true;
};
export type OS2HeaderParameter = OS2BaseFormatContrainedParameter &
OS2BaseSchema & {
in: "header";
};
export type OS2FormDataParameter = OS2BaseFormatContrainedParameter &
OS2BaseSchema & {
in: "formData";
type: OpenSpecTypes;
allowEmptyValue?: boolean;
collectionFormat?: ParameterCollectionFormat;
};
export type OS2Parameter = OS2BodyParameter | OS2FormDataParameter | OS2QueryParameter | OS2PathParameter | OS2HeaderParameter;
``` | /content/code_sandbox/packages/specs/openspec/src/openspec2/OS2Parameter.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 488 |
```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 a single-precision floating-point numeric value is infinite.
*
* @param x - value to test
* @returns boolean indicating whether the value is infinite
*
* @example
* var bool = isInfinitef( Infinity );
* // returns true
*
* @example
* var bool = isInfinitef( -Infinity );
* // returns true
*
* @example
* var bool = isInfinitef( 5.0 );
* // returns false
*
* @example
* var bool = isInfinitef( NaN );
* // returns false
*/
declare function isInfinitef( x: number ): boolean;
// EXPORTS //
export = isInfinitef;
``` | /content/code_sandbox/lib/node_modules/@stdlib/math/base/assert/is-infinitef/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 202 |
```xml
// See LICENSE in the project root for license information.
import { wrapWordsToLines } from './wrap-words-to-lines';
export function printPruneHelp(): void {
const help: string = `eslint-bulk prune
Usage:
eslint-bulk prune
This command is a thin wrapper around ESLint that communicates with @rushstack/eslint-patch to delete all unused suppression entries in all .eslint-bulk-suppressions.json files under the current working directory.`;
const wrapped: string[] = wrapWordsToLines(help);
for (const line of wrapped) {
console.log(line);
}
}
export function printHelp(): void {
const help: string = `eslint-bulk <command>
Usage:
eslint-bulk suppress --rule RULENAME1 [--rule RULENAME2...] PATH1 [PATH2...]
eslint-bulk suppress --all PATH1 [PATH2...]
eslint-bulk suppress --help
eslint-bulk prune
eslint-bulk prune --help
eslint-bulk --help
This command line tool is a thin wrapper around ESLint that communicates with @rushstack/eslint-patch to suppress or prune unused suppressions in the local .eslint-bulk-suppressions.json file.
Commands:
eslint-bulk suppress [options] <path...>
Use this command to generate a new .eslint-bulk-suppressions.json file or add suppression entries to the existing file. Specify the files and rules you want to suppress.
Please run "eslint-bulk suppress --help" to learn more.
eslint-bulk prune
Use this command to delete all unused suppression entries in all .eslint-bulk-suppressions.json files under the current working directory.
Please run "eslint-bulk prune --help" to learn more.
`;
const wrapped: string[] = wrapWordsToLines(help);
for (const line of wrapped) {
console.log(line);
}
}
export function printSuppressHelp(): void {
const help: string = `eslint-bulk suppress [options] <path...>
Usage:
eslint-bulk suppress --rule RULENAME1 [--rule RULENAME2...] PATH1 [PATH2...]
eslint-bulk suppress --all PATH1 [PATH2...]
eslint-bulk suppress --help
This command is a thin wrapper around ESLint that communicates with @rushstack/eslint-patch to either generate a new .eslint-bulk-suppressions.json file or add suppression entries to the existing file. Specify the files and rules you want to suppress.
Argument:
<path...>
Glob patterns for paths to suppress, same as eslint files argument. Should be relative to the project root.
Options:
-h, -H, --help
Display this help message.
-R, --rule
The full name of the ESLint rule you want to bulk-suppress. Specify multiple rules with --rule NAME1 --rule RULENAME2.
-A, --all
Bulk-suppress all rules in the specified file patterns.`;
const wrapped: string[] = wrapWordsToLines(help);
for (const line of wrapped) {
console.log(line);
}
}
``` | /content/code_sandbox/eslint/eslint-patch/src/eslint-bulk-suppressions/cli/utils/print-help.ts | xml | 2016-09-30T00:28:20 | 2024-08-16T18:54:35 | rushstack | microsoft/rushstack | 5,790 | 646 |
```xml
import { makeStyles } from '@fluentui/react-components';
export const useItemLayoutStyles = makeStyles({
root: {
display: 'grid',
gridTemplateColumns: 'auto 1fr auto auto',
minHeight: '48px',
},
contentMedia: {
alignSelf: 'start',
gridColumnStart: 3,
gridColumnEnd: 4,
gridRowStart: 2,
gridRowEnd: 3,
fontSize: '12px',
lineHeight: 1.3333,
},
contentWrapper: {
alignSelf: 'start',
gridColumnStart: 2,
gridColumnEnd: 3,
gridRowStart: 2,
gridRowEnd: 3,
marginRight: '8px',
fontSize: '12px',
lineHeight: 1.3333,
},
header: {
alignSelf: 'end',
gridColumnStart: 2,
gridColumnEnd: 3,
gridRowStart: 1,
gridRowEnd: 2,
fontSize: '14px',
marginRight: '8px',
},
headerMedia: {
alignSelf: 'end',
gridColumnStart: 3,
gridColumnEnd: 4,
gridRowStart: 1,
gridRowEnd: 2,
fontSize: '12px',
lineHeight: 1.3333,
},
startMedia: {
alignSelf: 'center',
gridColumnStart: 1,
gridColumnEnd: 2,
gridRowStart: 1,
gridRowEnd: 3,
marginRight: '8px',
},
endMedia: {
alignSelf: 'center',
gridColumnStart: 4,
gridColumnEnd: 5,
gridRowStart: 1,
gridRowEnd: 3,
},
});
``` | /content/code_sandbox/packages/react-components/react-migration-v0-v9/library/src/components/ItemLayout/ItemLayout.styles.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 388 |
```xml
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormControl } from '@angular/forms';
import { TestMaskComponent } from './utils/test-component.component';
import { provideEnvironmentNgxMask } from '../lib/ngx-mask.providers';
import { NgxMaskDirective } from '../lib/ngx-mask.directive';
import { optionsConfig } from '../lib/ngx-mask.config';
function createComponentWithDefaultConfig(
defaultConfig?: optionsConfig
): ComponentFixture<TestMaskComponent> {
TestBed.configureTestingModule({
declarations: [TestMaskComponent],
imports: [ReactiveFormsModule, NgxMaskDirective],
providers: [provideEnvironmentNgxMask(defaultConfig)],
});
const fixture = TestBed.createComponent(TestMaskComponent);
return fixture;
}
describe('Default config', () => {
it('default config - decimalMarker and thousandSeparator', () => {
const fixture = createComponentWithDefaultConfig({
decimalMarker: ',',
thousandSeparator: '.',
});
const component = fixture.componentInstance;
component.mask = 'separator';
component.form = new FormControl(1234.56);
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
expect(fixture.nativeElement.querySelector('input').value).toBe('1.234,56');
});
});
it('default config - decimalMarker and thousandSeparator', () => {
const fixture = createComponentWithDefaultConfig({
decimalMarker: '.',
thousandSeparator: ' ',
});
const component = fixture.componentInstance;
component.mask = 'separator';
component.form = new FormControl(1234.56);
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
expect(fixture.nativeElement.querySelector('input').value).toBe('1 234.56');
});
});
it('default config overriden - decimalMarker and thousandSeparator', () => {
const fixture = createComponentWithDefaultConfig({
decimalMarker: '.',
thousandSeparator: ' ',
});
const component = fixture.componentInstance;
component.mask = 'separator';
// Override default decimalMarker and thousandSeparator
component.decimalMarker = ',';
component.thousandSeparator = '.';
component.form = new FormControl(1234.56);
component.specialCharacters = ['/']; // Explicit set needed to prevent bug in ngx-mask.directive.ts OnChanges event (if specialCharacters is undefined, OnChanges function will return prematurely and won't apply provided thousandSeparator and decimalMarker)
fixture.detectChanges();
fixture.whenRenderingDone().then(() => {
expect(fixture.nativeElement.querySelector('input').value).toBe('1.234,56');
});
});
});
``` | /content/code_sandbox/projects/ngx-mask-lib/src/test/default-config.spec.ts | xml | 2016-09-23T20:44:28 | 2024-08-15T12:52:51 | ngx-mask | JsDaddy/ngx-mask | 1,150 | 542 |
```xml
<vector xmlns:android="path_to_url"
android:width="240dp" android:height="160dp"
android:viewportWidth="3" android:viewportHeight="2">
<path android:fillColor="#CE1126" android:pathData="M0,0h3v2h-3z" />
<path android:fillColor="#FCD116" android:pathData="M0,0h2v2h-2z" />
<path android:fillColor="#14B53A" android:pathData="M0,0h1v2h-1z" />
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_flag_ml.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 134 |
```xml
import * as compose from "lodash.flowright";
import {
BoardsQueryResponse,
StagesQueryResponse
} from "@erxes/ui-sales/src/boards/types";
import { DepartmentsQueryResponse } from "@erxes/ui/src/team/types";
import { IButtonMutateProps } from "@erxes/ui/src/types";
import { IOption } from "../types";
import { IPipeline } from "@erxes/ui-sales/src/boards/types";
import PipelineForm from "../components/PipelineForm";
import React from "react";
import Spinner from "@erxes/ui/src/components/Spinner";
import { gql } from "@apollo/client";
import { graphql } from "@apollo/client/react/hoc";
import { queries } from "@erxes/ui-sales/src/settings/boards/graphql";
import { queries as teamQueries } from "@erxes/ui/src/team/graphql";
import { queries as tagQueries } from "@erxes/ui-tags/src/graphql";
import { TagsQueryResponse } from "@erxes/ui-tags/src/types";
import { withProps } from "@erxes/ui/src/utils";
type Props = {
pipeline?: IPipeline;
boardId?: string;
renderButton: (props: IButtonMutateProps) => JSX.Element;
closeModal: () => void;
show: boolean;
type: string;
options?: IOption;
};
type FinalProps = {
stagesQuery: StagesQueryResponse;
boardsQuery: BoardsQueryResponse;
departmentsQuery: DepartmentsQueryResponse;
tagsQuery: TagsQueryResponse;
} & Props;
class PipelineFormContainer extends React.Component<FinalProps> {
render() {
const {
stagesQuery,
boardsQuery,
departmentsQuery,
boardId,
renderButton,
options,
tagsQuery
} = this.props;
if (
(stagesQuery && stagesQuery.loading) ||
(boardsQuery && boardsQuery.loading) ||
(departmentsQuery && departmentsQuery.loading) ||
(tagsQuery && tagsQuery.loading)
) {
return <Spinner />;
}
const stages = stagesQuery ? stagesQuery.salesStages : [];
const boards = boardsQuery.salesBoards || [];
const departments = departmentsQuery.departments || [];
const tags = tagsQuery.tags || [];
const extendedProps = {
...this.props,
stages,
boards,
departments,
boardId,
renderButton,
tags
};
const Form = options?.PipelineForm || PipelineForm;
return <Form {...extendedProps} />;
}
}
export default withProps<Props>(
compose(
graphql(gql(tagQueries.tags), {
name: "tagsQuery",
options: (props: Props) => ({
variables: { type: `sales:${props.type}` }
})
}),
graphql<Props, StagesQueryResponse, { pipelineId: string }>(
gql(queries.stages),
{
name: "stagesQuery",
skip: props => !props.pipeline,
options: ({ pipeline }: { pipeline?: IPipeline }) => ({
variables: { pipelineId: pipeline ? pipeline._id : "", isAll: true },
fetchPolicy: "network-only"
})
}
),
graphql<{}, DepartmentsQueryResponse>(gql(teamQueries.departments), {
name: "departmentsQuery"
}),
graphql<Props, BoardsQueryResponse, {}>(gql(queries.boards), {
name: "boardsQuery",
options: ({ type }) => ({
variables: { type }
})
})
)(PipelineFormContainer)
);
``` | /content/code_sandbox/packages/plugin-sales-ui/src/settings/boards/containers/PipelineForm.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 738 |
```xml
import React from 'react';
import { render, screen } from '@testing-library/react';
import StepItem from '../StepItem';
import '../styles/index.less';
describe('StepItem styles', () => {
it('Should render the correct styles', () => {
render(<StepItem data-testid="step_item" />);
expect(screen.getByTestId('step_item')).to.have.style('padding-left', '40px');
});
});
``` | /content/code_sandbox/src/Steps/test/StepItemStylesSpec.tsx | xml | 2016-06-06T02:27:46 | 2024-08-16T16:41:54 | rsuite | rsuite/rsuite | 8,263 | 89 |
```xml
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<response>
<result code="1000">
<msg>Command completed successfully</msg>
</result>
<resData>
<domain:renData
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>example.tld</domain:name>
<domain:exDate>2001-04-03T22:00:00.0Z</domain:exDate>
</domain:renData>
</resData>
<trID>
<clTRID>ABC-12345</clTRID>
<svTRID>server-trid</svTRID>
</trID>
</response>
</epp>
``` | /content/code_sandbox/core/src/test/resources/google/registry/flows/domain/domain_renew_response_missing_period.xml | xml | 2016-02-29T20:16:48 | 2024-08-15T19:49:29 | nomulus | google/nomulus | 1,685 | 178 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="path_to_url"
xmlns:app="path_to_url">
<item
android:id="@+id/action_reboot"
android:icon="@drawable/ic_restart"
android:title="@string/reboot"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_settings"
android:icon="@drawable/ic_settings_md2"
android:title="@string/settings"
app:showAsAction="ifRoom" />
</menu>
``` | /content/code_sandbox/app/apk/src/main/res/menu/menu_home_md2.xml | xml | 2016-09-08T12:42:53 | 2024-08-16T19:41:25 | Magisk | topjohnwu/Magisk | 46,424 | 121 |
```xml
import { Event, EventEmitter, QuickInputButtons, QuickPickItem } from 'vscode';
import { CreateEnv } from '../../common/utils/localize';
import {
MultiStepAction,
MultiStepNode,
showQuickPick,
showQuickPickWithBack,
} from '../../common/vscodeApis/windowApis';
import { traceError, traceVerbose } from '../../logging';
import {
CreateEnvironmentOptions,
CreateEnvironmentResult,
CreateEnvironmentProvider,
EnvironmentWillCreateEvent,
EnvironmentDidCreateEvent,
} from './proposed.createEnvApis';
import { CreateEnvironmentOptionsInternal } from './types';
const onCreateEnvironmentStartedEvent = new EventEmitter<EnvironmentWillCreateEvent>();
const onCreateEnvironmentExitedEvent = new EventEmitter<EnvironmentDidCreateEvent>();
let startedEventCount = 0;
function isBusyCreatingEnvironment(): boolean {
return startedEventCount > 0;
}
function fireStartedEvent(options?: CreateEnvironmentOptions): void {
onCreateEnvironmentStartedEvent.fire({ options });
startedEventCount += 1;
}
function fireExitedEvent(result?: CreateEnvironmentResult, options?: CreateEnvironmentOptions, error?: Error): void {
startedEventCount -= 1;
if (result) {
onCreateEnvironmentExitedEvent.fire({ options, ...result });
} else if (error) {
onCreateEnvironmentExitedEvent.fire({ options, error });
}
}
export function getCreationEvents(): {
onCreateEnvironmentStarted: Event<EnvironmentWillCreateEvent>;
onCreateEnvironmentExited: Event<EnvironmentDidCreateEvent>;
isCreatingEnvironment: () => boolean;
} {
return {
onCreateEnvironmentStarted: onCreateEnvironmentStartedEvent.event,
onCreateEnvironmentExited: onCreateEnvironmentExitedEvent.event,
isCreatingEnvironment: isBusyCreatingEnvironment,
};
}
async function createEnvironment(
provider: CreateEnvironmentProvider,
options: CreateEnvironmentOptions & CreateEnvironmentOptionsInternal,
): Promise<CreateEnvironmentResult | undefined> {
let result: CreateEnvironmentResult | undefined;
let err: Error | undefined;
try {
fireStartedEvent(options);
result = await provider.createEnvironment(options);
} catch (ex) {
if (ex === QuickInputButtons.Back) {
traceVerbose('Create Env: User clicked back button during environment creation');
if (!options.showBackButton) {
return undefined;
}
}
err = ex as Error;
throw err;
} finally {
fireExitedEvent(result, options, err);
}
return result;
}
interface CreateEnvironmentProviderQuickPickItem extends QuickPickItem {
id: string;
}
async function showCreateEnvironmentQuickPick(
providers: readonly CreateEnvironmentProvider[],
options?: CreateEnvironmentOptions & CreateEnvironmentOptionsInternal,
): Promise<CreateEnvironmentProvider | undefined> {
const items: CreateEnvironmentProviderQuickPickItem[] = providers.map((p) => ({
label: p.name,
description: p.description,
id: p.id,
}));
if (options?.providerId) {
const provider = providers.find((p) => p.id === options.providerId);
if (provider) {
return provider;
}
}
let selectedItem: CreateEnvironmentProviderQuickPickItem | CreateEnvironmentProviderQuickPickItem[] | undefined;
if (options?.showBackButton) {
selectedItem = await showQuickPickWithBack(items, {
placeHolder: CreateEnv.providersQuickPickPlaceholder,
matchOnDescription: true,
ignoreFocusOut: true,
});
} else {
selectedItem = await showQuickPick(items, {
placeHolder: CreateEnv.providersQuickPickPlaceholder,
matchOnDescription: true,
ignoreFocusOut: true,
});
}
if (selectedItem) {
const selected = Array.isArray(selectedItem) ? selectedItem[0] : selectedItem;
if (selected) {
const selections = providers.filter((p) => p.id === selected.id);
if (selections.length > 0) {
return selections[0];
}
}
}
return undefined;
}
function getOptionsWithDefaults(
options?: CreateEnvironmentOptions & CreateEnvironmentOptionsInternal,
): CreateEnvironmentOptions & CreateEnvironmentOptionsInternal {
return {
installPackages: true,
ignoreSourceControl: true,
showBackButton: false,
selectEnvironment: true,
...options,
};
}
export async function handleCreateEnvironmentCommand(
providers: readonly CreateEnvironmentProvider[],
options?: CreateEnvironmentOptions & CreateEnvironmentOptionsInternal,
): Promise<CreateEnvironmentResult | undefined> {
const optionsWithDefaults = getOptionsWithDefaults(options);
let selectedProvider: CreateEnvironmentProvider | undefined;
const envTypeStep = new MultiStepNode(
undefined,
async (context?: MultiStepAction) => {
if (providers.length > 0) {
try {
selectedProvider = await showCreateEnvironmentQuickPick(providers, optionsWithDefaults);
} catch (ex) {
if (ex === MultiStepAction.Back || ex === MultiStepAction.Cancel) {
return ex;
}
throw ex;
}
if (!selectedProvider) {
return MultiStepAction.Cancel;
}
} else {
traceError('No Environment Creation providers were registered.');
if (context === MultiStepAction.Back) {
// There are no providers to select, so just step back.
return MultiStepAction.Back;
}
}
return MultiStepAction.Continue;
},
undefined,
);
let result: CreateEnvironmentResult | undefined;
const createStep = new MultiStepNode(
envTypeStep,
async (context?: MultiStepAction) => {
if (context === MultiStepAction.Back) {
// This step is to trigger creation, which can go into other extension.
return MultiStepAction.Back;
}
if (selectedProvider) {
try {
result = await createEnvironment(selectedProvider, optionsWithDefaults);
} catch (ex) {
if (ex === MultiStepAction.Back || ex === MultiStepAction.Cancel) {
return ex;
}
throw ex;
}
}
return MultiStepAction.Continue;
},
undefined,
);
envTypeStep.next = createStep;
const action = await MultiStepNode.run(envTypeStep);
if (options?.showBackButton) {
if (action === MultiStepAction.Back || action === MultiStepAction.Cancel) {
result = { action, workspaceFolder: undefined, path: undefined, error: undefined };
}
}
if (result) {
return Object.freeze(result);
}
return undefined;
}
``` | /content/code_sandbox/src/client/pythonEnvironments/creation/createEnvironment.ts | xml | 2016-01-19T10:50:01 | 2024-08-12T21:05:24 | pythonVSCode | DonJayamanne/pythonVSCode | 2,078 | 1,377 |
```xml
import { Liquid } from '../../../src/liquid'
const liquid = new Liquid()
const cases = [
{
text: `
<div>
<p>
{{ 'John' }}
</p>
</div>
`,
expected: `
<div>
<p>
John
</p>
</div>
`
}, {
text: `
<div>
<p>
{{- 'John' -}}
</p>
</div>
`,
expected: `
<div>
<p>John</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true -%}
yes
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p>yes</p>
</div>
`
}, {
text: `
<div>
<p>
{% if true %}
yes
{% endif %}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{% if false %}
no
{% endif %}
</p>
</div>
`,
expected: `
<div>
<p>
</p>
</div>
`
}, {
text: '<p>{{- \'John\' -}}</p>',
expected: '<p>John</p>'
}, {
text: '<p>{%- if true -%}yes{%- endif -%}</p>',
expected: '<p>yes</p>'
}, {
text: '<p>{%- if false -%}no{%- endif -%}</p>',
expected: '<p></p>'
}, {
text: '<p> {%- if true %} yes {% endif -%} </p>',
expected: '<p> yes </p>'
}, {
text: '<p> {%- if false %} no {% endif -%} </p>',
expected: '<p></p>'
}, {
text: '<p> {% if true -%} yes {%- endif %} </p>',
expected: '<p> yes </p>'
}, {
text: '<p> {% if false -%} no {%- endif %} </p>',
expected: '<p> </p>'
}, {
text: '<p> {% if true -%} yes {% endif -%} </p>',
expected: '<p> yes </p>'
}, {
text: '<p> {% if false -%} no {% endif -%} </p>',
expected: '<p> </p>'
}, {
text: '<p> {%- if true %} yes {%- endif %} </p>',
expected: '<p> yes </p>'
}, {
text: '<p> {%- if false %} no {%- endif %} </p>',
expected: '<p> </p>'
}, {
text: `
<div>
<p>
{{- 'John' }}
</p>
</div>
`,
expected: `
<div>
<p>John
</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true %}
yes
{%- endif %}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if false %}
no
{%- endif %}
</p>
</div>
`,
expected: `
<div>
<p>
</p>
</div>
`
}, {
text: `
<div>
<p>
{{ 'John' -}}
</p>
</div>
`,
expected: `
<div>
<p>
John</p>
</div>
`
}, {
text: `
<div>
<p>
{% if true -%}
yes
{% endif -%}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{% if false -%}
no
{% endif -%}
</p>
</div>
`,
expected: `
<div>
<p>
</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true %}
yes
{% endif -%}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if false %}
no
{% endif -%}
</p>
</div>
`,
expected: `
<div>
<p></p>
</div>
`
}, {
text: `
<div>
<p>
{% if true -%}
yes
{%- endif %}
</p>
</div>
`,
expected: `
<div>
<p>
yes
</p>
</div>
`
}, {
text: `
<div>
<p>
{% if false -%}
no
{%- endif %}
</p>
</div>
`,
expected: `
<div>
<p>
</p>
</div>
`
}, {
text: `
<div>
<p>
{{- 'John' -}}
</p>
</div>
`,
expected: `
<div>
<p>John</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true -%}
yes
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p>yes</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if false -%}
no
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p></p>
</div>
`
}, {
text: `
<div>
<p>
{{- 'John' -}},
{{- '30' -}}
</p>
</div>
`,
expected: `
<div>
<p>John,30</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if true -%}
yes
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p>yes</p>
</div>
`
}, {
text: `
<div>
<p>
{%- if false -%}
no
{%- endif -%}
</p>
</div>
`,
expected: `
<div>
<p></p>
</div>
`
}, {
text: `
<div>
<p>
{{- 'John' -}}
{{- '30' -}}
</p>
<b>
{{ 'John' -}}
{{- '30' }}
</b>
<i>
{{- 'John' }}
{{ '30' -}}
</i>
</div>
`,
expected: `
<div>
<p>John30</p>
<b>
John30
</b>
<i>John
30</i>
</div>
`
}, {
text: `
<div>
{%- if true -%}
{%- if true -%}
<p>
{{- 'John' -}}
</p>
{%- endif -%}
{%- endif -%}
</div>
`,
expected: `
<div><p>John</p></div>
`
}, {
text: `
<div>
{% raw %}
{%- if true -%}
<p>
{{- 'John' -}}
</p>
{%- endif -%}
{% endraw %}
</div>
`,
expected: `
<div>
{%- if true -%}
<p>
{{- 'John' -}}
</p>
{%- endif -%}
</div>
`
}
]
describe('Whitespace Control', function () {
cases.forEach(item => it(
item.text,
async () => {
const html = await liquid.parseAndRender(item.text)
expect(html).toBe(item.expected)
}
))
})
``` | /content/code_sandbox/test/integration/liquid/whitespace-ctrl.spec.ts | xml | 2016-06-13T07:39:30 | 2024-08-16T16:56:50 | liquidjs | harttle/liquidjs | 1,485 | 2,045 |
```xml
/*your_sha256_hash-----------------------------
*your_sha256_hash----------------------------*/
import type { languages } from '../../fillers/monaco-editor-core';
export const conf: languages.LanguageConfiguration = {
comments: {
lineComment: '#',
blockComment: ['/*', '*/']
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"', notIn: ['string'] }
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '"', close: '"' }
]
};
export const language = <languages.IMonarchLanguage>{
defaultToken: '',
tokenPostfix: '.hcl',
keywords: [
'var',
'local',
'path',
'for_each',
'any',
'string',
'number',
'bool',
'true',
'false',
'null',
'if ',
'else ',
'endif ',
'for ',
'in',
'endfor'
],
operators: [
'=',
'>=',
'<=',
'==',
'!=',
'+',
'-',
'*',
'/',
'%',
'&&',
'||',
'!',
'<',
'>',
'?',
'...',
':'
],
symbols: /[=><!~?:&|+\-*\/\^%]+/,
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
terraformFunctions:
/(abs|ceil|floor|log|max|min|pow|signum|chomp|format|formatlist|indent|join|lower|regex|regexall|replace|split|strrev|substr|title|trimspace|upper|chunklist|coalesce|coalescelist|compact|concat|contains|distinct|element|flatten|index|keys|length|list|lookup|map|matchkeys|merge|range|reverse|setintersection|setproduct|setunion|slice|sort|transpose|values|zipmap|base64decode|base64encode|base64gzip|csvdecode|jsondecode|jsonencode|urlencode|yamldecode|yamlencode|abspath|dirname|pathexpand|basename|file|fileexists|fileset|filebase64|templatefile|formatdate|timeadd|timestamp|base64sha256|base64sha512|bcrypt|filebase64sha256|filebase64sha512|filemd5|filemd1|filesha256|filesha512|md5|rsadecrypt|sha1|sha256|sha512|uuid|uuidv5|cidrhost|cidrnetmask|cidrsubnet|tobool|tolist|tomap|tonumber|toset|tostring)/,
terraformMainBlocks: /(module|data|terraform|resource|provider|variable|output|locals)/,
tokenizer: {
root: [
// highlight main blocks
[
/^@terraformMainBlocks([ \t]*)([\w-]+|"[\w-]+"|)([ \t]*)([\w-]+|"[\w-]+"|)([ \t]*)(\{)/,
['type', '', 'string', '', 'string', '', '@brackets']
],
// highlight all the remaining blocks
[
/(\w+[ \t]+)([ \t]*)([\w-]+|"[\w-]+"|)([ \t]*)([\w-]+|"[\w-]+"|)([ \t]*)(\{)/,
['identifier', '', 'string', '', 'string', '', '@brackets']
],
// highlight block
[
/(\w+[ \t]+)([ \t]*)([\w-]+|"[\w-]+"|)([ \t]*)([\w-]+|"[\w-]+"|)(=)(\{)/,
['identifier', '', 'string', '', 'operator', '', '@brackets']
],
// terraform general highlight - shared with expressions
{ include: '@terraform' }
],
terraform: [
// highlight terraform functions
[/@terraformFunctions(\()/, ['type', '@brackets']],
// all other words are variables or keywords
[
/[a-zA-Z_]\w*-*/, // must work with variables such as foo-bar and also with negative numbers
{
cases: {
'@keywords': { token: 'keyword.$0' },
'@default': 'variable'
}
}
],
{ include: '@whitespace' },
{ include: '@heredoc' },
// delimiters and operators
[/[{}()\[\]]/, '@brackets'],
[/[<>](?!@symbols)/, '@brackets'],
[
/@symbols/,
{
cases: {
'@operators': 'operator',
'@default': ''
}
}
],
// numbers
[/\d*\d+[eE]([\-+]?\d+)?/, 'number.float'],
[/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
[/\d[\d']*/, 'number'],
[/\d/, 'number'],
[/[;,.]/, 'delimiter'], // delimiter: after number because of .\d floats
// strings
[/"/, 'string', '@string'], // this will include expressions
[/'/, 'invalid']
],
heredoc: [
[/<<[-]*\s*["]?([\w\-]+)["]?/, { token: 'string.heredoc.delimiter', next: '@heredocBody.$1' }]
],
heredocBody: [
[
/([\w\-]+)$/,
{
cases: {
'$1==$S2': [
{
token: 'string.heredoc.delimiter',
next: '@popall'
}
],
'@default': 'string.heredoc'
}
}
],
[/./, 'string.heredoc']
],
whitespace: [
[/[ \t\r\n]+/, ''],
[/\/\*/, 'comment', '@comment'],
[/\/\/.*$/, 'comment'],
[/#.*$/, 'comment']
],
comment: [
[/[^\/*]+/, 'comment'],
[/\*\//, 'comment', '@pop'],
[/[\/*]/, 'comment']
],
string: [
[/\$\{/, { token: 'delimiter', next: '@stringExpression' }],
[/[^\\"\$]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/"/, 'string', '@popall']
],
stringInsideExpression: [
[/[^\\"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/"/, 'string', '@pop']
],
stringExpression: [
[/\}/, { token: 'delimiter', next: '@pop' }],
[/"/, 'string', '@stringInsideExpression'],
{ include: '@terraform' }
]
}
};
``` | /content/code_sandbox/src/basic-languages/hcl/hcl.ts | xml | 2016-06-07T16:56:31 | 2024-08-16T17:17:05 | monaco-editor | microsoft/monaco-editor | 39,508 | 1,803 |
```xml
<UserControl x:Class="Dopamine.Views.Common.AppearanceLanguage"
xmlns="path_to_url"
xmlns:d="path_to_url"
xmlns:x="path_to_url"
xmlns:mc="path_to_url"
xmlns:prismMvvm="clr-namespace:Prism.Mvvm;assembly=Prism.Wpf"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
prismMvvm:ViewModelLocator.AutoWireViewModel="True">
<ComboBox x:Name="ComboBoxLanguage" Style="{StaticResource MetroComboBox}" Padding="0" HorizontalAlignment="Left" VerticalContentAlignment="Center" Width="150" ItemsSource="{Binding Languages}" SelectedItem="{Binding SelectedLanguage}"/>
</UserControl>
``` | /content/code_sandbox/Dopamine/Views/Common/AppearanceLanguage.xaml | xml | 2016-07-13T21:34:42 | 2024-08-15T03:30:43 | dopamine-windows | digimezzo/dopamine-windows | 1,786 | 160 |
```xml
import * as pulumi from "@pulumi/pulumi";
import * as aws_native from "@pulumi/aws-native";
const role = new aws_native.iam.Role("role", {
roleName: "ScriptIAMRole",
assumeRolePolicyDocument: {
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: "sts:AssumeRole",
Principal: {
Service: [
"cloudformation.amazonaws.com",
"gamelift.amazonaws.com",
],
},
}],
},
});
``` | /content/code_sandbox/tests/testdata/codegen/using-object-as-input-for-any-pp/nodejs/using-object-as-input-for-any.ts | xml | 2016-10-31T21:02:47 | 2024-08-16T19:47:04 | pulumi | pulumi/pulumi | 20,743 | 115 |
```xml
import { ReactNode, createContext, useCallback, useContext, useEffect, useRef } from 'react';
import type { Action, ThunkDispatch } from '@reduxjs/toolkit';
import { createSelector } from '@reduxjs/toolkit';
import type { ThunkAction } from 'redux-thunk';
import {
baseUseDispatch as useDispatch,
baseUseSelector as useSelector,
baseUseStore as useStore,
} from '@proton/react-redux-store';
import type { ReducerValue } from './interface';
const createQueue = <T,>() => {
let queue: T[] = [];
const enqueue = (value: T) => {
return queue.push(value);
};
const consume = (cb: (value: T) => void) => {
queue.forEach(cb);
queue.length = 0;
};
let symbol: Symbol;
const resetId = () => {
symbol = Symbol('debug');
};
resetId();
return {
enqueue,
consume,
resetId,
getId: () => symbol,
};
};
export type Queue = ReturnType<typeof createQueue>;
export const ModelQueueContext = createContext<Queue | null>(null);
export const ModelThunkDispatcher = ({ children }: { children: ReactNode }) => {
const store = useStore();
const state = useRef<Queue | null>(null);
if (!state.current) {
state.current = createQueue();
}
const queue = state.current;
useEffect(() => {
if (!queue) {
return;
}
const dispatchAll = () => {
queue.consume((thunk: any) => {
store.dispatch(thunk());
});
};
let queued = false;
let cancel: () => void;
const consume = () => {
if (queued) {
return;
}
queued = true;
// Not supported on safari
if (!!globalThis.requestIdleCallback) {
const handle = requestIdleCallback(
() => {
queued = false;
dispatchAll();
},
{ timeout: 100 }
);
cancel = () => {
cancelIdleCallback(handle);
};
} else {
const handle = setTimeout(() => {
queued = false;
dispatchAll();
}, 10);
cancel = () => {
clearTimeout(handle);
};
}
};
const originalEnqueue = queue.enqueue;
queue.enqueue = (newThunk: any) => {
const result = originalEnqueue(newThunk);
consume();
return result;
};
consume();
return () => {
queue.enqueue = originalEnqueue;
queue.resetId();
cancel();
};
}, [store, queue]);
return <ModelQueueContext.Provider value={queue}>{children}</ModelQueueContext.Provider>;
};
export const createHooks = <State, Extra, Returned, ThunkArg = void>(
thunk: (arg?: ThunkArg) => ThunkAction<Promise<Returned>, State, Extra, Action>,
selector: (state: State) => ReducerValue<Returned>,
options: { periodic: boolean } = { periodic: true }
) => {
const useGet = (): ((arg?: ThunkArg) => Promise<Returned>) => {
const dispatch = useDispatch<ThunkDispatch<State, Extra, Action>>();
return useCallback((arg?: ThunkArg) => dispatch(thunk(arg)), []);
};
let queueRef: { state: boolean; queue: Queue | null; id: null | any; once: boolean } = {
state: false,
queue: null,
id: null,
// Should the hook trigger the thunk periodically. For now 'periodic' means once per page load.
once: !options.periodic,
};
const hookSelector = createSelector(selector, (result): [Returned | undefined, boolean] => {
if (!result) {
return [undefined, true];
}
const { error, value } = result;
if ((error !== undefined || value !== undefined) && queueRef.state) {
// Reset the queued state when the thunk has resolved.
queueRef.state = false;
}
if (error && value === undefined) {
const thrownError = new Error(error.message);
thrownError.name = error.name || thrownError.name;
thrownError.stack = error.stack || thrownError.stack;
throw thrownError;
}
if (queueRef.state && queueRef.queue?.getId() !== queueRef.id) {
queueRef.state = false;
}
if ((value === undefined || !queueRef.once) && !queueRef.state && queueRef.queue) {
queueRef.state = true;
queueRef.once = true;
queueRef.queue.enqueue(thunk);
}
const loading = value === undefined;
return [value, loading];
});
const useValue = (): [Returned | undefined, boolean] => {
queueRef.queue = useContext(ModelQueueContext);
return useSelector(hookSelector);
};
return {
useGet,
useValue,
};
};
``` | /content/code_sandbox/packages/redux-utilities/asyncModelThunk/hooks.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,060 |
```xml
import { assert } from 'chai';
import { IdentifierNamesGenerator } from '../../../../../src/enums/generators/identifier-names-generators/IdentifierNamesGenerator';
import { NO_ADDITIONAL_NODES_PRESET } from '../../../../../src/options/presets/NoCustomNodes';
import { getStringArrayRegExp } from '../../../../helpers/get-string-array-regexp';
import { readFileAsString } from '../../../../helpers/readFileAsString';
import { JavaScriptObfuscator } from '../../../../../src/JavaScriptObfuscatorFacade';
describe('MangledIdentifierNamesGenerator', () => {
describe('generateWithPrefix', () => {
describe('Variant #1: should not generate same name for string array as existing name in code', () => {
describe('Variant #1: `renameGlobals` option is disabled', () => {
const stringArrayStorageRegExp: RegExp = getStringArrayRegExp(['abc'], {
kind: 'const',
name: 'ab'
});
const lastVariableDeclarationIdentifierNameRegExp: RegExp = /const aa *= *ac\(0x0\);/;
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-1.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator,
identifiersPrefix: 'a',
transformObjectKeys: true,
stringArray: true,
stringArrayThreshold: 1
}
).getObfuscatedCode();
});
it('Match #1: should generate correct identifier for string array', () => {
assert.match(obfuscatedCode, stringArrayStorageRegExp);
});
it('Match #2: should keep identifier name for last variable declaration', () => {
assert.match(obfuscatedCode, lastVariableDeclarationIdentifierNameRegExp);
});
});
describe('Variant #2: `renameGlobals` option is enabled', () => {
const stringArrayStorageRegExp: RegExp = getStringArrayRegExp(['abc'], {
kind: 'const',
name: 'ab'
});
const lastVariableDeclarationIdentifierNameRegExp: RegExp = /const aB *= *ac\(0x0\);/;
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-1.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator,
identifiersPrefix: 'a',
renameGlobals: true,
transformObjectKeys: true,
stringArray: true,
stringArrayThreshold: 1
}
).getObfuscatedCode();
});
it('Match #1: should generate correct identifier for string array', () => {
assert.match(obfuscatedCode, stringArrayStorageRegExp);
});
it('Match #2: should keep identifier name for last variable declaration', () => {
assert.match(obfuscatedCode, lastVariableDeclarationIdentifierNameRegExp);
});
});
});
describe('Variant #2: should not generate same prefixed name for identifier in code as prefixed name of string array', () => {
describe('Variant #1: `renameGlobals` option is disabled', () => {
const stringArrayStorageRegExp: RegExp = getStringArrayRegExp(['abc', 'last'], {
kind: 'const',
name: 'aa'
});
const functionDeclarationIdentifierNameRegExp: RegExp = /function foo *\(\) *{/;
const lastVariableDeclarationIdentifierNameRegExp: RegExp = /const ac *= *ab\(0x1\);/;
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-2.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator,
identifiersPrefix: 'a',
transformObjectKeys: true,
stringArray: true,
stringArrayThreshold: 1
}
).getObfuscatedCode();
});
it('Match #1: should generate correct identifier name for string array', () => {
assert.match(obfuscatedCode, stringArrayStorageRegExp);
});
it('Match #2: should keep identifier name for function declaration', () => {
assert.match(obfuscatedCode, functionDeclarationIdentifierNameRegExp);
});
it('Match #3: should keep identifier name for last variable declaration', () => {
assert.match(obfuscatedCode, lastVariableDeclarationIdentifierNameRegExp);
});
});
describe('Variant #2: `renameGlobals` option is enabled', () => {
const stringArrayStorageRegExp: RegExp = getStringArrayRegExp(['abc', 'last'], {
kind: 'const',
name: 'aa'
});
const functionDeclarationIdentifierNameRegExp: RegExp = /function ac *\(\) *{/;
const lastVariableDeclarationIdentifierNameRegExp: RegExp = /const ad *= *ab\(0x1\);/;
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-2.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator,
identifiersPrefix: 'a',
renameGlobals: true,
transformObjectKeys: true,
stringArray: true,
stringArrayThreshold: 1
}
).getObfuscatedCode();
});
it('Match #1: should generate correct identifier name for string array', () => {
assert.match(obfuscatedCode, stringArrayStorageRegExp);
});
it('Match #2: should generate correct identifier name for function declaration', () => {
assert.match(obfuscatedCode, functionDeclarationIdentifierNameRegExp);
});
it('Match #3: should keep identifier name for last variable declaration', () => {
assert.match(obfuscatedCode, lastVariableDeclarationIdentifierNameRegExp);
});
});
});
});
describe('generateForLexicalScope', () => {
describe('Variant #1: Should generate different names set for different lexical scopes', () => {
describe('Variant #1: `renameGlobals` option is disabled', () => {
const variableIdentifierRegExp: RegExp = /var foo *= *'abc';/;
const functionDeclarationRegExp1: RegExp = /function bar *\(a, *b\) *{}/;
const functionDeclarationRegExp2: RegExp = /function baz *\(a, *b\) *{}/;
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-1.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator
}
).getObfuscatedCode();
});
it('Match #1: should keep identifier name for variable declaration', () => {
assert.match(obfuscatedCode, variableIdentifierRegExp);
});
it('Match #2: should generate valid identifier names for function', () => {
assert.match(obfuscatedCode, functionDeclarationRegExp1);
});
it('Match #3: should generate valid identifier names for function', () => {
assert.match(obfuscatedCode, functionDeclarationRegExp2);
});
});
describe('Variant #2: `renameGlobals` option is enabled', () => {
const variableIdentifierRegExp: RegExp = /var a *= *'abc';/;
const functionDeclarationRegExp1: RegExp = /function b *\(d, *e\) *{}/;
const functionDeclarationRegExp2: RegExp = /function c *\(d, *e\) *{}/;
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-1.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator,
renameGlobals: true
}
).getObfuscatedCode();
});
it('Match #1: should generate valid identifier name for variable declaration', () => {
assert.match(obfuscatedCode, variableIdentifierRegExp);
});
it('Match #2: should generate valid identifier names for function', () => {
assert.match(obfuscatedCode, functionDeclarationRegExp1);
});
it('Match #3: should generate valid identifier names for function', () => {
assert.match(obfuscatedCode, functionDeclarationRegExp2);
});
});
});
describe('Variant #2: Should generate different names set for different lexical scopes when string array is enabled', () => {
describe('Variant #1: `renameGlobals` option is disabled', () => {
const stringArrayIdentifierRegExp: RegExp = getStringArrayRegExp(['abc'], {
kind: 'var',
name: 'a'
});
const variableIdentifierRegExp: RegExp = /var foo *= *b\(0x0\);/;
const functionDeclarationRegExp1: RegExp = /function bar *\(c, *d\) *{}/;
const functionDeclarationRegExp2: RegExp = /function baz *\(c, *d\) *{}/;
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-1.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator,
stringArray: true,
stringArrayThreshold: 1
}
).getObfuscatedCode();
});
it('Match #1: should generate valid identifier names for string array', () => {
assert.match(obfuscatedCode, stringArrayIdentifierRegExp);
});
it('Match #2: should keep identifier name for variable declaration', () => {
assert.match(obfuscatedCode, variableIdentifierRegExp);
});
it('Match #3: should generate valid identifier names for function', () => {
assert.match(obfuscatedCode, functionDeclarationRegExp1);
});
it('Match #4: should generate valid identifier names for function', () => {
assert.match(obfuscatedCode, functionDeclarationRegExp2);
});
});
describe('Variant #2: `renameGlobals` option is enabled', () => {
const stringArrayIdentifierRegExp: RegExp = getStringArrayRegExp(['abc'], {
kind: 'var',
name: 'a'
});
const variableIdentifierRegExp: RegExp = /var c *= *b\(0x0\);/;
const functionDeclarationRegExp1: RegExp = /function d *\(f, *g\) *{}/;
const functionDeclarationRegExp2: RegExp = /function e *\(f, *g\) *{}/;
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-1.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator,
renameGlobals: true,
stringArray: true,
stringArrayThreshold: 1
}
).getObfuscatedCode();
});
it('Match #1: should generate valid identifier names for string array', () => {
assert.match(obfuscatedCode, stringArrayIdentifierRegExp);
});
it('Match #2: should generate valid identifier name for variable declaration', () => {
assert.match(obfuscatedCode, variableIdentifierRegExp);
});
it('Match #3: should generate valid identifier names for function', () => {
assert.match(obfuscatedCode, functionDeclarationRegExp1);
});
it('Match #4: should generate valid identifier names for function', () => {
assert.match(obfuscatedCode, functionDeclarationRegExp2);
});
});
});
describe('Variant #3: Should generate different names set for different lexical scopes: nested functions', () => {
describe('Variant #1: `renameGlobals` option is disabled', () => {
const regExp: RegExp = new RegExp(`` +
`var foo *= *'abc'; *` +
`function bar *\\(a, *b\\) *{` +
`function c *\\(e, *f\\) *{ *} *` +
`function d *\\(e, *f\\) *{ *} *` +
`} *` +
`function baz *\\(a, *b\\) *{` +
`function c *\\(e, *f\\) *{ *} *` +
`function d *\\(e, *f\\) *{ *} *` +
`}` +
``);
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-2.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator
}
).getObfuscatedCode();
});
it('Match #1: should generate valid identifier names', () => {
assert.match(obfuscatedCode, regExp);
});
});
describe('Variant #2: `renameGlobals` option is enabled', () => {
const regExp: RegExp = new RegExp(`` +
`var a *= *'abc'; *` +
`function b *\\(d, *e\\) *{` +
`function f *\\(h, *i\\) *{ *} *` +
`function g *\\(h, *i\\) *{ *} *` +
`} *` +
`function c *\\(d, *e\\) *{` +
`function f *\\(h, *i\\) *{ *} *` +
`function g *\\(h, *i\\) *{ *} *` +
`}` +
``);
let obfuscatedCode: string;
before(() => {
const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-2.js');
obfuscatedCode = JavaScriptObfuscator.obfuscate(
code,
{
...NO_ADDITIONAL_NODES_PRESET,
identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator,
renameGlobals: true
}
).getObfuscatedCode();
});
it('Match #1: should generate valid identifier names', () => {
assert.match(obfuscatedCode, regExp);
});
});
});
});
});
``` | /content/code_sandbox/test/functional-tests/generators/identifier-names-generators/mangled-identifier-names-generator/MangledIdentifierNamesGenerator.spec.ts | xml | 2016-05-09T08:16:53 | 2024-08-16T19:43:07 | javascript-obfuscator | javascript-obfuscator/javascript-obfuscator | 13,358 | 3,247 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE language SYSTEM "language.dtd"
[
<!ENTITY space " ">
<!ENTITY end ";">
]>
<!--
-->
<language name="Modelines"
version="4"
kateversion="5.0"
section="Other"
extensions=""
mimetype=""
author="Alex Turbov (i.zaufi@gmail.com)"
license="MIT"
hidden="true"
priority="6">
<!--
The main purpose of this file is to be included into other syntax files.
NOTE Default colors are set to 'Comment', so if u don't want to highight it,
just leave colors as is...
TODO Support for other modelines? emacs/vim??
-->
<highlighting>
<list name="ModelineStartKeyword">
<item>kate:</item>
</list>
<list name="Booleans">
<item>auto-brackets</item>
<!-- NOTE Deprecated -->
<!-- <item>auto-insert-doxygen</item> -->
<item>automatic-spell-checking</item> <!-- NOTE Since KDE 4.?? -->
<item>backspace-indents</item>
<item>block-selection</item>
<item>bookmark-sorting</item>
<item>bom</item>
<item>byte-order-marker</item>
<item>byte-order-mark</item>
<item>dynamic-word-wrap</item>
<item>folding-markers</item>
<item>folding-preview</item> <!-- Since KTextEditor 5.24 -->
<item>icon-border</item>
<item>indent-pasted-text</item> <!-- Since KDE 4.11 -->
<item>keep-extra-spaces</item>
<item>line-numbers</item>
<item>newline-at-eof</item> <!-- Since KDE 4.9 -->
<item>overwrite-mode</item>
<item>persistent-selection</item>
<!-- NOTE Deprecated since KDE 4.10 -->
<!-- <item>remove-trailing-space</item> -->
<item>replace-tabs-save</item>
<item>replace-tabs</item>
<item>replace-trailing-space-save</item>
<item>smart-home</item>
<item>scrollbar-minimap</item> <!-- Since KTextEditor 5.24 -->
<item>scrollbar-preview</item> <!-- Since KTextEditor 5.24 -->
<item>space-indent</item>
<item>show-tabs</item>
<item>show-trailing-spaces</item> <!-- NOTE Since KDE 4.?? -->
<item>tab-indents</item>
<item>word-wrap</item>
<item>wrap-cursor</item>
</list>
<list name="True">
<item>on</item>
<item>true</item>
<item>1</item>
</list>
<list name="False">
<item>off</item>
<item>false</item>
<item>0</item>
</list>
<list name="Integrals">
<item>auto-center-lines</item>
<item>font-size</item>
<item>indent-mode</item>
<item>indent-width</item>
<item>tab-width</item>
<item>undo-steps</item>
<item>word-wrap-column</item>
</list>
<list name="Strings">
<item>background-color</item>
<item>bracket-highlight-color</item>
<item>current-line-color</item>
<item>default-dictionary</item>
<item>encoding</item> <!-- NOTE Since KDE 4.?? -->
<item>eol</item> <!-- Valid settings are unix, mac and dos -->
<item>end-of-line</item> <!-- Valid settings are unix, mac and dos -->
<item>font</item>
<item>hl</item>
<item>icon-bar-color</item>
<item>mode</item> <!-- NOTE Since KDE 4.?? -->
<item>scheme</item>
<item>selection-color</item>
<item>syntax</item>
<item>word-wrap-marker-color</item>
</list>
<list name="RemoveSpaces">
<item>remove-trailing-spaces</item>
</list>
<list name="RemoveSpacesOptions">
<item>0</item>
<item>-</item>
<item>none</item>
<item>modified</item>
<item>mod</item>
<item>+</item>
<item>1</item>
<item>all</item>
<item>*</item>
<item>2</item>
</list>
<contexts>
<context name="Normal" attribute="Comment" lineEndContext="#pop">
<DetectSpaces />
<keyword String="ModelineStartKeyword" context="Modeline" attribute="Keyword" />
<RegExpr String="kate-(mimetype|wildcard)\(.*\):" context="Modeline" attribute="Keyword" />
</context>
<context name="Modeline" attribute="Comment" lineEndContext="#pop">
<DetectSpaces />
<keyword String="Booleans" context="Booleans" attribute="Variable" />
<keyword String="Integrals" context="Integrals" attribute="Variable" />
<keyword String="Strings" context="Strings" attribute="Variable" />
<keyword String="RemoveSpaces" context="RemoveSpaces" attribute="Variable" />
<LineContinue context="#pop" />
</context>
<context name="Booleans" attribute="Comment" lineEndContext="#pop">
<DetectSpaces />
<keyword String="True" attribute="Option ON" context="#stay" />
<keyword String="False" attribute="Option OFF" context="#stay" />
<DetectChar char="&end;" context="#pop" attribute="Variable" />
<LineContinue context="#pop" />
</context>
<context name="Integrals" attribute="Comment" lineEndContext="#pop">
<DetectSpaces />
<Int attribute="Number" context="#stay" />
<DetectChar char="&end;" context="#pop" attribute="Variable" />
<LineContinue context="#pop" />
</context>
<context name="Strings" attribute="String" lineEndContext="#pop">
<DetectSpaces />
<RegExpr String="[^&end;&space;]" context="#stay" />
<DetectChar char="&end;" context="#pop" attribute="Variable" />
<LineContinue context="#pop" />
</context>
<context name="RemoveSpaces" attribute="Comment" lineEndContext="#pop">
<DetectSpaces />
<keyword String="RemoveSpacesOptions" attribute="Value" context="#pop!RemoveSpacesEnd" />
<DetectChar char="&end;" context="#pop" attribute="Variable" />
<LineContinue context="#pop" />
</context>
<context name="RemoveSpacesEnd" attribute="Comment" lineEndContext="#pop">
<DetectChar char="&end;" context="#pop" attribute="Variable" />
</context>
</contexts>
<itemDatas>
<itemData name="Comment" defStyleNum="dsComment" spellChecking="true" />
<itemData name="Keyword" defStyleNum="dsAnnotation" spellChecking="false" />
<itemData name="Variable" defStyleNum="dsCommentVar" spellChecking="false" />
<itemData name="Number" defStyleNum="dsDecVal" spellChecking="false" />
<itemData name="String" defStyleNum="dsString" spellChecking="false" />
<itemData name="Value" defStyleNum="dsOthers" spellChecking="false" />
<itemData name="Option ON" defStyleNum="dsOthers" spellChecking="false" />
<itemData name="Option OFF" defStyleNum="dsOthers" spellChecking="false" />
</itemDatas>
</highlighting>
<general>
<keywords casesensitive="1" weakDeliminator=":-+*" />
</general>
</language>
<!-- kate: indent-width 2; -->
``` | /content/code_sandbox/src/data/extra/syntax-highlighting/syntax/modelines.xml | xml | 2016-10-05T07:24:54 | 2024-08-16T05:03:40 | vnote | vnotex/vnote | 11,687 | 1,809 |
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.jdt.junit.launchconfig">
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
<listEntry value="/commons-compiler-tests/src/test/java"/>
</listAttribute>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
<listEntry value="2"/>
</listAttribute>
<listAttribute key="org.eclipse.debug.ui.favoriteGroups">
<listEntry value="org.eclipse.debug.ui.launchGroup.debug"/>
<listEntry value="org.eclipse.debug.ui.launchGroup.run"/>
</listAttribute>
<stringAttribute key="org.eclipse.jdt.junit.CONTAINER" value="=commons-compiler-tests/src\/test\/java=/test=/true=/=/optional=/true=/=/maven.pomderived=/true=/"/>
<booleanAttribute key="org.eclipse.jdt.junit.KEEPRUNNING_ATTR" value="false"/>
<stringAttribute key="org.eclipse.jdt.junit.TESTNAME" value=""/>
<stringAttribute key="org.eclipse.jdt.junit.TEST_KIND" value="org.eclipse.jdt.junit.loader.junit4"/>
<booleanAttribute key="org.eclipse.jdt.launching.ATTR_USE_CLASSPATH_ONLY_JAR" value="false"/>
<listAttribute key="org.eclipse.jdt.launching.CLASSPATH">
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry containerPath="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8" path="5" type="4"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry containerPath="org.eclipse.jdt.junit.JUNIT_CONTAINER/4" path="5" type="4"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry path="5" projectName="commons-compiler-jdk" type="1"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry path="5" projectName="commons-compiler" type="1"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry path="5" projectName="commons-compiler-tests" type="1"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry path="5" projectName="jdisasm" type="1"/> "/>
</listAttribute>
<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.m2e.launchconfig.classpathProvider"/>
<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="false"/>
<stringAttribute key="org.eclipse.jdt.launching.JRE_CONTAINER" value="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11"/>
<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value=""/>
<listAttribute key="org.eclipse.jdt.launching.MODULEPATH"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="commons-compiler-tests"/>
<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.m2e.launchconfig.sourcepathProvider"/>
<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-ea -ss6m -Xverify:all -DxxSimpleCompiler.disassembleClassFilesToStdout=true -DxxAbstractCompiler.disassembleClassFilesToStdout=true -Dorg.codehaus.commons.compiler.util.Disassembler.printStackMap=true -Dorg.codehaus.commons.compiler.util.Disassembler.printAllOffsets=true -Dxxorg.codehaus.commons.compiler.util.Disassembler.printAllAttributes=true -Dxxorg.codehaus.commons.compiler.util.Disassembler.dumpConstantPool=true -Dxxorg.codehaus.commons.compiler.util.Disassembler.showClassPoolIndexes=true"/>
</launchConfiguration>
``` | /content/code_sandbox/commons-compiler-tests/launch/commons-compiler-tests (jdk, JavaSE-11).launch | xml | 2016-06-12T16:42:49 | 2024-08-16T02:16:53 | janino | janino-compiler/janino | 1,225 | 1,168 |
```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.
-->
<LinearLayout
xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<GridLayout
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:columnCount="3"
android:rowCount="12">
</GridLayout>
</androidx.core.widget.NestedScrollView>
<!-- Padding is used to avoid clipping the FAB's shadows. This is not normally necessary for
full-screen containers. -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:orientation="horizontal">
<Button
android:id="@+id/show_hide_fabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="4dp"
android:text="@string/hide_fabs_label"/>
<Button
android:id="@+id/rotate_fabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:text="@string/rotate_fabs_label"/>
</LinearLayout>
<io.material.catalog.feature.BottomWindowInsetView
android:layout_width="wrap_content"
android:layout_height="0dp"
/>
</LinearLayout>
``` | /content/code_sandbox/catalog/java/io/material/catalog/fab/res/layout/cat_fab_fragment.xml | xml | 2016-12-05T16:11:29 | 2024-08-16T17:51:42 | material-components-android | material-components/material-components-android | 16,176 | 422 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="path_to_url" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../LocalizableStrings.resx">
<body>
<trans-unit id="AppFullName">
<source>Add a project-to-project reference to the project.</source>
<target state="translated">Aggiunge un riferimento P2P (da progetto a progetto) al progetto.</target>
<note />
</trans-unit>
<trans-unit id="AppDescription">
<source>Command to add project to project reference</source>
<target state="translated">Comando per aggiungere il riferimento P2P (da progetto a progetto)</target>
<note />
</trans-unit>
<trans-unit id="CmdFrameworkDescription">
<source>Add the reference only when targeting a specific framework.</source>
<target state="translated">Aggiunge il riferimento solo se destinato a un framework specifico.</target>
<note />
</trans-unit>
<trans-unit id="ProjectPathArgumentName">
<source>PROJECT_PATH</source>
<target state="translated">PROJECT_PATH</target>
<note />
</trans-unit>
<trans-unit id="ProjectPathArgumentDescription">
<source>The paths to the projects to add as references.</source>
<target state="translated">Percorsi dei progetti da aggiungere come riferimenti.</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/Cli/dotnet/commands/dotnet-add/dotnet-add-reference/xlf/LocalizableStrings.it.xlf | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 410 |
```xml
import { Path } from 'slate'
export const input = {
path: [0, 1],
another: [],
}
export const test = ({ path, another }) => {
return Path.relative(path, another)
}
export const output = [0, 1]
``` | /content/code_sandbox/packages/slate/test/interfaces/Path/relative/root.tsx | xml | 2016-06-18T01:52:42 | 2024-08-16T18:43:42 | slate | ianstormtaylor/slate | 29,492 | 59 |
```xml
import { useCallback, useRef } from 'react';
import { getPatternGroups } from '../utils';
import { useUpdateEffect } from '@/internals/hooks';
export function useFieldCursor<V = Date | null>(format: string, value?: V) {
const typeCount = useRef(0);
const increment = useCallback(() => {
typeCount.current += 1;
}, []);
const reset = useCallback(() => {
typeCount.current = 0;
}, []);
const isResetValue = useCallback(() => {
return typeCount.current === 0;
}, []);
// Check if the cursor should move to the next field
const isMoveCursor = useCallback(
(value: number, pattern: string) => {
const patternGroup = getPatternGroups(format, pattern);
if (value.toString().length === patternGroup.length) {
return true;
} else if (pattern === 'y' && typeCount.current === 4) {
return true;
} else if (pattern !== 'y' && typeCount.current === 2) {
return true;
}
switch (pattern) {
case 'M':
return parseInt(`${value}0`) > 12;
case 'd':
return parseInt(`${value}0`) > 31;
case 'H':
return parseInt(`${value}0`) > 23;
case 'h':
return parseInt(`${value}0`) > 12;
case 'm':
case 's':
return parseInt(`${value}0`) > 59;
default:
return false;
}
},
[format]
);
useUpdateEffect(() => {
if (!value) {
reset();
}
}, [value]);
return { increment, reset, isMoveCursor, isResetValue };
}
export default useFieldCursor;
``` | /content/code_sandbox/src/DateInput/hooks/useFieldCursor.ts | xml | 2016-06-06T02:27:46 | 2024-08-16T16:41:54 | rsuite | rsuite/rsuite | 8,263 | 390 |
```xml
/*your_sha256_hash----------
zero
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
your_sha256_hash-----------*/
export { Angle } from './angle'
export { Radian } from './radian'
export { Matrix } from './matrix'
export { Plane } from './plane'
export { Quaternion } from './quaternion'
export { Single } from './single'
export { Vector2 } from './vector2'
export { Vector3 } from './vector3'
export { Vector4 } from './vector4'
export { VectorN } from './vectorN'
export { Ray } from './ray'
export { Triangle } from './triangle'
export { Box } from './box'
export { Sphere } from './sphere'
export { Frustum } from './frustum'
``` | /content/code_sandbox/src/engine/math/index.ts | xml | 2016-10-10T11:59:07 | 2024-08-16T11:00:47 | zero | sinclairzx81/zero | 2,412 | 368 |
```xml
import { QueueItem } from '../reducers/queue';
import { Queue } from './actionTypes';
import * as QueueOperations from './queue';
describe('Queue actions tests', () => {
describe('finds streams for track', () => {
const getSelectedStreamProvider = jest.spyOn(QueueOperations, 'getSelectedStreamProvider');
const resolveTrackStreams = jest.spyOn(QueueOperations, 'resolveTrackStreams');
afterEach(() => {
getSelectedStreamProvider.mockReset();
resolveTrackStreams.mockReset();
});
test('remote track is removed from the queue when no streams are available', () => {
// Mock an empty search result for streams.
resolveTrackStreams.mockResolvedValueOnce([]);
// Configure a dummy stream provider. It is not actually used in this execution path.
getSelectedStreamProvider.mockReturnValueOnce({});
// Set up the queue with an arbitrary track, which doesn't have any stream.
const trackIndex = 123;
const queueItems: QueueItem[] = [];
queueItems[trackIndex] = {
artist: 'Artist Name',
name: 'Track Name',
local: false,
streams: null
};
const stateResolver = () => ({
queue: {
queueItems
},
settings: {
useStreamVerification: false
}
});
const dispatchOperation = jest.fn();
const findStreamsForTrackOperation = QueueOperations.findStreamsForTrack(trackIndex);
findStreamsForTrackOperation(dispatchOperation, stateResolver)
.then(() => {
// The track without streams should have been removed from the queue.
expect(dispatchOperation).toHaveBeenCalledWith({
type: Queue.REMOVE_QUEUE_ITEM,
payload: { index: trackIndex }
});
});
});
});
});
``` | /content/code_sandbox/packages/app/app/actions/queue.test.ts | xml | 2016-09-22T22:58:21 | 2024-08-16T15:47:39 | nuclear | nukeop/nuclear | 11,862 | 372 |
```xml
(() => {
pipe(
serviceEventFromMessage(msg),
TE.chain(
flow(
publishServiceEvent(analytics),
TE.mapLeft(nackFromError)
)
)
)()
.then(messageResponse(logger, msg))
.catch((err: Error) => {
logger.error(
pipe(
O.fromNullable(err.stack),
O.getOrElse(constant(err.message))
)
);
process.exit(1);
});
})();
``` | /content/code_sandbox/tests/format/typescript/functional-composition/pipe-function-calls.ts | xml | 2016-11-29T17:13:37 | 2024-08-16T17:29:57 | prettier | prettier/prettier | 48,913 | 98 |
```xml
import { Interpolation } from '../types';
export default function interleave<Props extends object>(
strings: readonly string[],
interpolations: Interpolation<Props>[]
): Interpolation<Props>[] {
const result: Interpolation<Props>[] = [strings[0]];
for (let i = 0, len = interpolations.length; i < len; i += 1) {
result.push(interpolations[i], strings[i + 1]);
}
return result;
}
``` | /content/code_sandbox/packages/styled-components/src/utils/interleave.ts | xml | 2016-08-16T06:41:32 | 2024-08-16T12:59:53 | styled-components | styled-components/styled-components | 40,332 | 100 |
```xml
import { type CompletionItem } from '@pnpm/tabtab'
export type CompletionFunc = (
options: Record<string, unknown>,
params: string[]
) => Promise<CompletionItem[]>
``` | /content/code_sandbox/cli/command/src/index.ts | xml | 2016-01-28T07:40:43 | 2024-08-16T12:38:47 | pnpm | pnpm/pnpm | 28,869 | 40 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
<testsuite name="tensorflow/python/kernel_tests/cwise_ops_test" tests="1" failures="0" errors="0">
<testcase name="tensorflow/python/kernel_tests/cwise_ops_test" status="run"></testcase>
</testsuite>
</testsuites>
``` | /content/code_sandbox/testlogs/python27/2016_07_17/tensorflow/python/kernel_tests/cwise_ops_test/test_shard_16_of_50.xml | xml | 2016-03-12T06:26:47 | 2024-08-12T19:21:52 | tensorflow-on-raspberry-pi | samjabrahams/tensorflow-on-raspberry-pi | 2,242 | 79 |
```xml
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at path_to_url
*/
import {normalize, Path} from '@angular-devkit/core';
import {Tree, UpdateRecorder} from '@angular-devkit/schematics';
import {DirectoryEntry, FileSystem} from '../update-tool/file-system';
import * as path from 'path';
/**
* File system that leverages the virtual tree from the CLI devkit. This file
* system is commonly used by `ng update` migrations that run as part of the
* Angular CLI.
*/
export class DevkitFileSystem extends FileSystem {
private _updateRecorderCache = new Map<string, UpdateRecorder>();
constructor(private _tree: Tree) {
super();
}
resolve(...segments: string[]): Path {
// Note: We use `posix.resolve` as the devkit paths are using posix separators.
return normalize(path.posix.resolve('/', ...segments.map(normalize)));
}
edit(filePath: Path) {
if (this._updateRecorderCache.has(filePath)) {
return this._updateRecorderCache.get(filePath)!;
}
const recorder = this._tree.beginUpdate(filePath);
this._updateRecorderCache.set(filePath, recorder);
return recorder;
}
commitEdits() {
this._updateRecorderCache.forEach(r => this._tree.commitUpdate(r));
this._updateRecorderCache.clear();
}
fileExists(filePath: Path) {
return this._tree.exists(filePath);
}
directoryExists(dirPath: Path) {
// The devkit tree does not expose an API for checking whether a given
// directory exists. It throws a specific error though if a directory
// is being read as a file. We use that to check if a directory exists.
try {
this._tree.get(dirPath);
} catch (e) {
// Note: We do not use an `instanceof` check here. It could happen that
// the devkit version used by the CLI is different than the one we end up
// loading. This can happen depending on how Yarn/NPM hoists the NPM
// packages / whether there are multiple versions installed. Typescript
// throws a compilation error if the type isn't specified and we can't
// check the type, so we have to cast the error output to any.
if ((e as any).constructor.name === 'PathIsDirectoryException') {
return true;
}
}
return false;
}
overwrite(filePath: Path, content: string) {
this._tree.overwrite(filePath, content);
}
create(filePath: Path, content: string) {
this._tree.create(filePath, content);
}
delete(filePath: Path) {
this._tree.delete(filePath);
}
read(filePath: Path) {
const buffer = this._tree.read(filePath);
return buffer !== null ? buffer.toString() : null;
}
readDirectory(dirPath: Path): DirectoryEntry {
const {subdirs: directories, subfiles: files} = this._tree.getDir(dirPath);
return {directories, files};
}
}
``` | /content/code_sandbox/src/cdk/schematics/ng-update/devkit-file-system.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 672 |
```xml
import {RemoteGitHubV4Entity} from './RemoteGitHubV4Entity';
export type RemoteGitHubV4ViewerEntity = RemoteGitHubV4Entity & {
viewer: {
login: string;
}
}
``` | /content/code_sandbox/src/Renderer/Library/Type/RemoteGitHubV4/RemoteGitHubV4ViewerEntity.ts | xml | 2016-05-10T12:55:31 | 2024-08-11T04:32:50 | jasper | jasperapp/jasper | 1,318 | 45 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.ActivityRxToast">
<com.tamsiree.rxui.view.RxTitle
android:id="@+id/rx_title"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_55"
android:background="@color/colorPrimary"
app:leftIconVisibility="true"
app:title="RxToast"
app:titleColor="@color/White" />
<RelativeLayout
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/ova"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin">
<Button
android:id="@+id/button_error_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="5dp"
android:background="#ddFD4C5B"
android:text=""
android:textColor="@color/White" />
<Button
android:id="@+id/button_success_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button_error_toast"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="5dp"
android:background="#dd52BA97"
android:text=""
android:textColor="@color/White" />
<Button
android:id="@+id/button_info_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button_success_toast"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="5dp"
android:background="#dd2196F3"
android:text=""
android:textColor="@color/White" />
<Button
android:id="@+id/button_warning_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button_info_toast"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="5dp"
android:background="#ddFFA900"
android:text=""
android:textColor="@color/White" />
<Button
android:id="@+id/button_normal_toast_wo_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button_warning_toast"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="5dp"
android:background="#dd666666"
android:text="ICON"
android:textColor="@color/White" />
<Button
android:id="@+id/button_normal_toast_w_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button_normal_toast_wo_icon"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_margin="5dp"
android:background="#dd666666"
android:text="ICON"
android:textColor="@color/White" />
</RelativeLayout>
</LinearLayout>
``` | /content/code_sandbox/RxDemo/src/main/res/layout/activity_rx_toast.xml | xml | 2016-09-24T09:30:45 | 2024-08-16T09:54:41 | RxTool | Tamsiree/RxTool | 12,242 | 975 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>16B2555</string>
<key>CFBundleExecutable</key>
<string>VoodooPS2Mouse</string>
<key>CFBundleGetInfoString</key>
<key>CFBundleIdentifier</key>
<string>org.rehabman.voodoo.driver.PS2Mouse</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>Voodoo PS/2 Mouse</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>1.8.24f</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>1.8.24</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>8B62</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>16B2649</string>
<key>DTSDKName</key>
<string>macosx10.12</string>
<key>DTXcode</key>
<string>0810</string>
<key>DTXcodeBuild</key>
<string>8B62</string>
<key>IOKitPersonalities</key>
<dict>
<key>ApplePS2Mouse</key>
<dict>
<key>CFBundleIdentifier</key>
<string>org.rehabman.voodoo.driver.PS2Mouse</string>
<key>HIDPointerAccelerationType</key>
<string>HIDTrackpadAcceleration</string>
<key>HIDScrollAccelerationType</key>
<string>HIDTrackpadScrollAcceleration</string>
<key>IOClass</key>
<string>ApplePS2Mouse</string>
<key>IOProviderClass</key>
<string>ApplePS2MouseDevice</string>
<key>Platform Profile</key>
<dict>
<key>Default</key>
<dict>
<key>ActLikeTrackpad</key>
<false/>
<key>ButtonCount</key>
<integer>3</integer>
<key>DefaultResolution</key>
<integer>240</integer>
<key>DisableDevice</key>
<false/>
<key>DisableLEDUpdating</key>
<false/>
<key>FakeMiddleButton</key>
<false/>
<key>ForceDefaultResolution</key>
<true/>
<key>ForceSetResolution</key>
<false/>
<key>MiddleClickTime</key>
<integer>100000000</integer>
<key>MouseCount</key>
<integer>0</integer>
<key>MouseYInverter</key>
<integer>1</integer>
<key>QuietTimeAfterTyping</key>
<integer>500000000</integer>
<key>ResolutionMode</key>
<integer>3</integer>
<key>ScrollResolution</key>
<integer>5</integer>
<key>ScrollYInverter</key>
<integer>1</integer>
<key>TrackpadScroll</key>
<true/>
<key>WakeDelay</key>
<integer>1000</integer>
</dict>
<key>HPQOEM</key>
<dict>
<key>1411</key>
<string>ProBook</string>
<key>1619</key>
<string>ProBook</string>
<key>161C</key>
<string>ProBook</string>
<key>164F</key>
<string>ProBook</string>
<key>167C</key>
<string>ProBook</string>
<key>167E</key>
<string>ProBook</string>
<key>1680</key>
<string>ProBook</string>
<key>179B</key>
<string>ProBook</string>
<key>179C</key>
<string>ProBook</string>
<key>17A9</key>
<string>ProBook</string>
<key>17F0</key>
<string>ProBook</string>
<key>17F3</key>
<string>ProBook</string>
<key>17F6</key>
<string>ProBook</string>
<key>1942</key>
<string>ProBook</string>
<key>1949</key>
<string>ProBook</string>
<key>198F</key>
<string>ProBook</string>
<key>ProBook</key>
<dict>
<key>ActLikeTrackpad</key>
<true/>
<key>DisableDevice</key>
<true/>
</dict>
<key>ProBook-102</key>
<string>ProBook</string>
<key>ProBook-87</key>
<string>ProBook</string>
</dict>
</dict>
<key>ProductID</key>
<integer>547</integer>
<key>USBMouseStopsTrackpad</key>
<integer>0</integer>
<key>VendorID</key>
<integer>1452</integer>
</dict>
</dict>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.iokit.IOHIDFamily</key>
<string>1.0.0b1</string>
<key>com.apple.kpi.iokit</key>
<string>9.0.0</string>
<key>com.apple.kpi.libkern</key>
<string>9.0.0</string>
<key>com.apple.kpi.mach</key>
<string>9.0.0</string>
<key>org.rehabman.voodoo.driver.PS2Controller</key>
<string>1.8.24</string>
</dict>
<key>OSBundleRequired</key>
<string>Console</string>
<key>Source Code</key>
<string>path_to_url
</dict>
</plist>
``` | /content/code_sandbox/Clover-Configs/LG/LG 15Z960/CLOVER/kexts/Other/VoodooPS2Controller.kext/Contents/PlugIns/VoodooPS2Mouse.kext/Contents/Info.plist | xml | 2016-11-05T04:22:54 | 2024-08-12T19:25:53 | Hackintosh-Installer-University | huangyz0918/Hackintosh-Installer-University | 3,937 | 1,621 |
```xml
import * as React from 'react';
import createSvgIcon from '../utils/createSvgIcon';
const AlignHorizontalLeftIcon = createSvgIcon({
svg: ({ classes }) => (
<svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false">
<path d="M0 0h128v2048H0V0zm1408 896H256V384h1152v512zm-128-384H384v256h896V512zm640 640v512H256v-512h1664zm-128 128H384v256h1408v-256z" />
</svg>
),
displayName: 'AlignHorizontalLeftIcon',
});
export default AlignHorizontalLeftIcon;
``` | /content/code_sandbox/packages/react-icons-mdl2/src/components/AlignHorizontalLeftIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 169 |
```xml
import { CreatePagesArgs } from "gatsby";
interface CategoriesQueryResult {
allMarkdownRemark: {
group: Array<{
fieldValue: string;
totalCount: number;
}>;
};
}
const categoriesQuery = async (graphql: CreatePagesArgs["graphql"]) => {
const result = await graphql<CategoriesQueryResult>(`
{
allMarkdownRemark(
filter: {
frontmatter: { template: { eq: "post" }, draft: { ne: true } }
}
sort: { order: DESC, fields: [frontmatter___date] }
) {
group(field: frontmatter___category) {
fieldValue
totalCount
}
}
}
`);
return result?.data?.allMarkdownRemark?.group ?? [];
};
export default categoriesQuery;
``` | /content/code_sandbox/internal/gatsby/queries/categories-query.ts | xml | 2016-03-11T21:02:37 | 2024-08-15T23:09:27 | gatsby-starter-lumen | alxshelepenok/gatsby-starter-lumen | 1,987 | 170 |
```xml
import { getGlobalClassNames } from '../../Styling';
import type { IGroupFooterStyleProps, IGroupFooterStyles } from './GroupFooter.types';
const GlobalClassNames = {
root: 'ms-groupFooter',
};
export const getStyles = (props: IGroupFooterStyleProps): IGroupFooterStyles => {
const { theme, className } = props;
const classNames = getGlobalClassNames(GlobalClassNames, theme!);
return {
root: [
theme.fonts.medium,
classNames.root,
{
position: 'relative',
padding: '5px 38px',
},
className,
],
};
};
``` | /content/code_sandbox/packages/react/src/components/GroupedList/GroupFooter.styles.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 138 |
```xml
import "@tsed/ajv";
import {Controller} from "@tsed/di";
import {MinLength, Patch, Post, Property, Put, Returns} from "@tsed/schema";
import {PlatformServerlessTest} from "@tsed/platform-serverless-testing";
import {PlatformExpress} from "@tsed/platform-express";
import {BodyParams} from "@tsed/platform-params";
import {PlatformServerlessHttp} from "../src/index.js";
import {Server} from "./integration/aws-basic/src/Server.js";
class Model {
@Property()
id: string;
@MinLength(3)
name: string;
}
@Controller("/")
class BodyLambda {
@Post("/scenario-1")
scenario1(@BodyParams("id") id: string) {
return {
id
};
}
@Put("/scenario-2").Name("scenario2")
@Returns(201, Model).Header("x-test", "test")
scenario2(@BodyParams() model: Model) {
return model;
}
@Patch("/scenario-3")
scenario3(@BodyParams() model: Model) {
return model;
}
}
describe("Body params", () => {
beforeEach(
PlatformServerlessTest.bootstrap(PlatformServerlessHttp, {
server: Server,
adapter: PlatformExpress,
mount: {
"/": [BodyLambda]
}
})
);
afterEach(() => PlatformServerlessTest.reset());
describe("scenario1: Post lambda with body", () => {
it("should map data with param", async () => {
const response = await PlatformServerlessTest.request.post("/scenario-1").body({
id: "1",
name: "Test"
});
expect(response.statusCode).toBe(200);
expect(JSON.parse(response.body)).toEqual({
id: "1"
});
});
});
describe("scenario2: Put lambda with body and model mapping", () => {
it("should map data with param", async () => {
const response = await PlatformServerlessTest.request.put("/scenario-2").body({
id: "1",
name: "Test"
});
expect(response.statusCode).toBe(201);
expect(JSON.parse(response.body)).toEqual({
id: "1",
name: "Test"
});
expect(response.headers).toEqual({
"content-length": "24",
"content-type": "application/json; charset=utf-8",
etag: 'W/"18-jfUwSIdR5OF14k0Z7ilBjfRuwwE"',
vary: "Accept-Encoding",
"x-powered-by": "Express",
"x-request-id": "requestId",
"x-test": "test"
});
});
it("should throw an error", async () => {
const response = await PlatformServerlessTest.request.put("/scenario-2").body({
id: "1",
name: "T"
});
expect(response.statusCode).toBe(400);
expect(JSON.parse(response.body)).toEqual({
errors: [
{
data: "T",
requestPath: "body",
dataPath: ".name",
instancePath: "/name",
keyword: "minLength",
message: "must NOT have fewer than 3 characters",
modelName: "Model",
params: {
limit: 3
},
schemaPath: "#/properties/name/minLength"
}
],
message: 'Bad request on parameter "request.body".\nModel.name must NOT have fewer than 3 characters. Given value: "T"',
name: "AJV_VALIDATION_ERROR",
status: 400
});
});
});
describe("scenario3: Patch lambda with body and model mapping", () => {
it("should map data with param", async () => {
const response = await PlatformServerlessTest.request.patch("/scenario-3").body({
id: "1",
name: "Test"
});
expect(response.statusCode).toBe(200);
expect(JSON.parse(response.body)).toEqual({
id: "1",
name: "Test"
});
});
});
});
``` | /content/code_sandbox/packages/platform/platform-serverless-http/test/body.integration.spec.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 888 |
```xml
import {
updateYFragment,
yDocToProsemirror,
yDocToProsemirrorJSON,
} from "@getoutline/y-prosemirror";
import { JSDOM } from "jsdom";
import { Node } from "prosemirror-model";
import * as Y from "yjs";
import textBetween from "@shared/editor/lib/textBetween";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
import { IconType, ProsemirrorData } from "@shared/types";
import { determineIconType } from "@shared/utils/icon";
import { parser, serializer, schema } from "@server/editor";
import { addTags } from "@server/logging/tracer";
import { trace } from "@server/logging/tracing";
import { Collection, Document, Revision } from "@server/models";
import diff from "@server/utils/diff";
import { ProsemirrorHelper } from "./ProsemirrorHelper";
import { TextHelper } from "./TextHelper";
type HTMLOptions = {
/** Whether to include the document title in the generated HTML (defaults to true) */
includeTitle?: boolean;
/** Whether to include style tags in the generated HTML (defaults to true) */
includeStyles?: boolean;
/** Whether to include the Mermaid script in the generated HTML (defaults to false) */
includeMermaid?: boolean;
/** Whether to include styles to center diff (defaults to true) */
centered?: boolean;
/**
* Whether to replace attachment urls with pre-signed versions. If set to a
* number then the urls will be signed for that many seconds. (defaults to false)
*/
signedUrls?: boolean | number;
/** The base URL to use for relative links */
baseUrl?: string;
};
@trace()
export class DocumentHelper {
/**
* Returns the document as a Prosemirror Node. This method uses the derived content if available
* then the collaborative state, otherwise it falls back to Markdown.
*
* @param document The document or revision to convert
* @returns The document content as a Prosemirror Node
*/
static toProsemirror(
document: Document | Revision | Collection | ProsemirrorData
) {
if ("type" in document && document.type === "doc") {
return Node.fromJSON(schema, document);
}
if ("content" in document && document.content) {
return Node.fromJSON(schema, document.content);
}
if ("state" in document && document.state) {
const ydoc = new Y.Doc();
Y.applyUpdate(ydoc, document.state);
return Node.fromJSON(schema, yDocToProsemirrorJSON(ydoc, "default"));
}
const text =
document instanceof Collection ? document.description : document.text;
return parser.parse(text ?? "") || Node.fromJSON(schema, {});
}
/**
* Returns the document as a plain JSON object. This method uses the derived content if available
* then the collaborative state, otherwise it falls back to Markdown.
*
* @param document The document or revision to convert
* @param options Options for the conversion
* @returns The document content as a plain JSON object
*/
static async toJSON(
document: Document | Revision | Collection,
options?: {
/** The team context */
teamId?: string;
/** Whether to sign attachment urls, and if so for how many seconds is the signature valid */
signedUrls?: number;
/** Marks to remove from the document */
removeMarks?: string[];
/** The base path to use for internal links (will replace /doc/) */
internalUrlBase?: string;
}
): Promise<ProsemirrorData> {
let doc: Node | null;
let json;
if ("content" in document && document.content) {
// Optimized path for documents with content available and no transformation required.
if (
!options?.removeMarks &&
!options?.signedUrls &&
!options?.internalUrlBase
) {
return document.content;
}
doc = Node.fromJSON(schema, document.content);
} else if ("state" in document && document.state) {
const ydoc = new Y.Doc();
Y.applyUpdate(ydoc, document.state);
doc = Node.fromJSON(schema, yDocToProsemirrorJSON(ydoc, "default"));
} else if (document instanceof Collection) {
doc = parser.parse(document.description ?? "");
} else {
doc = parser.parse(document.text);
}
if (doc && options?.signedUrls && options?.teamId) {
json = await ProsemirrorHelper.signAttachmentUrls(
doc,
options.teamId,
options.signedUrls
);
} else {
json = doc?.toJSON() ?? {};
}
if (options?.internalUrlBase) {
json = ProsemirrorHelper.replaceInternalUrls(
json,
options.internalUrlBase
);
}
if (options?.removeMarks) {
json = ProsemirrorHelper.removeMarks(json, options.removeMarks);
}
return json;
}
/**
* Returns the document as plain text. This method uses the
* collaborative state if available, otherwise it falls back to Markdown.
*
* @param document The document or revision to convert
* @returns The document content as plain text without formatting.
*/
static toPlainText(document: Document | Revision) {
const node = DocumentHelper.toProsemirror(document);
const textSerializers = Object.fromEntries(
Object.entries(schema.nodes)
.filter(([, n]) => n.spec.toPlainText)
.map(([name, n]) => [name, n.spec.toPlainText])
);
return textBetween(node, 0, node.content.size, textSerializers);
}
/**
* Returns the document as Markdown. This is a lossy conversion and should only be used for export.
*
* @param document The document or revision to convert
* @returns The document title and content as a Markdown string
*/
static toMarkdown(
document: Document | Revision | Collection | ProsemirrorData
) {
const text = serializer
.serialize(DocumentHelper.toProsemirror(document))
.replace(/(^|\n)\\(\n|$)/g, "\n\n")
.replace(//g, '"')
.replace(//g, '"')
.replace(//g, "'")
.replace(//g, "'")
.trim();
if (document instanceof Collection) {
return text;
}
if (document instanceof Document || document instanceof Revision) {
const iconType = determineIconType(document.icon);
const title = `${iconType === IconType.Emoji ? document.icon + " " : ""}${
document.title
}`;
return `# ${title}\n\n${text}`;
}
return text;
}
/**
* Returns the document as plain HTML. This is a lossy conversion and should only be used for export.
*
* @param document The document or revision to convert
* @param options Options for the HTML output
* @returns The document title and content as a HTML string
*/
static async toHTML(document: Document | Revision, options?: HTMLOptions) {
const node = DocumentHelper.toProsemirror(document);
let output = ProsemirrorHelper.toHTML(node, {
title: options?.includeTitle !== false ? document.title : undefined,
includeStyles: options?.includeStyles,
includeMermaid: options?.includeMermaid,
centered: options?.centered,
baseUrl: options?.baseUrl,
});
addTags({
documentId: document.id,
options,
});
if (options?.signedUrls) {
const teamId =
document instanceof Document
? document.teamId
: (await document.$get("document"))?.teamId;
if (!teamId) {
return output;
}
output = await TextHelper.attachmentsToSignedUrls(
output,
teamId,
typeof options.signedUrls === "number" ? options.signedUrls : undefined
);
}
return output;
}
/**
* Parse a list of mentions contained in a document or revision
*
* @param document Document or Revision
* @returns An array of mentions in passed document or revision
*/
static parseMentions(document: Document | Revision) {
const node = DocumentHelper.toProsemirror(document);
return ProsemirrorHelper.parseMentions(node);
}
/**
* Generates a HTML diff between documents or revisions.
*
* @param before The before document
* @param after The after document
* @param options Options passed to HTML generation
* @returns The diff as a HTML string
*/
static async diff(
before: Document | Revision | null,
after: Revision,
{ signedUrls, ...options }: HTMLOptions = {}
) {
addTags({
beforeId: before?.id,
documentId: after.documentId,
options,
});
if (!before) {
return await DocumentHelper.toHTML(after, { ...options, signedUrls });
}
const beforeHTML = await DocumentHelper.toHTML(before, options);
const afterHTML = await DocumentHelper.toHTML(after, options);
const beforeDOM = new JSDOM(beforeHTML);
const afterDOM = new JSDOM(afterHTML);
// Extract the content from the article tag and diff the HTML, we don't
// care about the surrounding layout and stylesheets.
let diffedContentAsHTML = diff(
beforeDOM.window.document.getElementsByTagName("article")[0].innerHTML,
afterDOM.window.document.getElementsByTagName("article")[0].innerHTML
);
// Sign only the URLS in the diffed content
if (signedUrls) {
const teamId =
before instanceof Document
? before.teamId
: (await before.$get("document"))?.teamId;
if (teamId) {
diffedContentAsHTML = await TextHelper.attachmentsToSignedUrls(
diffedContentAsHTML,
teamId,
typeof signedUrls === "number" ? signedUrls : undefined
);
}
}
// Inject the diffed content into the original document with styling and
// serialize back to a string.
const article = beforeDOM.window.document.querySelector("article");
if (article) {
article.innerHTML = diffedContentAsHTML;
}
return beforeDOM.serialize();
}
/**
* Generates a compact HTML diff between documents or revisions, the
* diff is reduced up to show only the parts of the document that changed and
* the immediate context. Breaks in the diff are denoted with
* "div.diff-context-break" nodes.
*
* @param before The before document
* @param after The after document
* @param options Options passed to HTML generation
* @returns The diff as a HTML string
*/
static async toEmailDiff(
before: Document | Revision | null,
after: Revision,
options?: HTMLOptions
) {
if (!before) {
return "";
}
const html = await DocumentHelper.diff(before, after, options);
const dom = new JSDOM(html);
const doc = dom.window.document;
const containsDiffElement = (node: Element | null) =>
node && node.innerHTML.includes("data-operation-index");
// The diffing lib isn't able to catch all changes currently, e.g. changing
// the type of a mark will result in an empty diff.
// see: path_to_url
if (!containsDiffElement(doc.querySelector("#content"))) {
return;
}
// We use querySelectorAll to get a static NodeList as we'll be modifying
// it as we iterate, rather than getting content.childNodes.
const contents = doc.querySelectorAll("#content > *");
let previousNodeRemoved = false;
let previousDiffClipped = false;
const br = doc.createElement("div");
br.innerHTML = "";
br.className = "diff-context-break";
for (const childNode of contents) {
// If the block node contains a diff tag then we want to keep it
if (containsDiffElement(childNode as Element)) {
if (previousNodeRemoved && previousDiffClipped) {
childNode.parentElement?.insertBefore(br.cloneNode(true), childNode);
}
previousNodeRemoved = false;
previousDiffClipped = true;
// Special case for largetables, as this block can get very large we
// want to clip it to only the changed rows and surrounding context.
if (childNode.classList.contains(EditorStyleHelper.table)) {
const rows = childNode.querySelectorAll("tr");
if (rows.length < 3) {
continue;
}
let previousRowRemoved = false;
let previousRowDiffClipped = false;
for (const row of rows) {
if (containsDiffElement(row)) {
const cells = row.querySelectorAll("td");
if (previousRowRemoved && previousRowDiffClipped) {
const tr = doc.createElement("tr");
const br = doc.createElement("td");
br.colSpan = cells.length;
br.innerHTML = "";
br.className = "diff-context-break";
tr.appendChild(br);
childNode.parentElement?.insertBefore(tr, childNode);
}
previousRowRemoved = false;
previousRowDiffClipped = true;
continue;
}
if (containsDiffElement(row.nextElementSibling)) {
previousRowRemoved = false;
continue;
}
if (containsDiffElement(row.previousElementSibling)) {
previousRowRemoved = false;
continue;
}
previousRowRemoved = true;
row.remove();
}
}
continue;
}
// If the block node does not contain a diff tag and the previous
// block node did not contain a diff tag then remove the previous.
if (
childNode.nodeName === "P" &&
childNode.textContent &&
childNode.nextElementSibling?.nodeName === "P" &&
containsDiffElement(childNode.nextElementSibling)
) {
if (previousDiffClipped) {
childNode.parentElement?.insertBefore(br.cloneNode(true), childNode);
}
previousNodeRemoved = false;
continue;
}
if (
childNode.nodeName === "P" &&
childNode.textContent &&
childNode.previousElementSibling?.nodeName === "P" &&
containsDiffElement(childNode.previousElementSibling)
) {
previousNodeRemoved = false;
continue;
}
previousNodeRemoved = true;
childNode.remove();
}
const head = doc.querySelector("head");
const body = doc.querySelector("body");
return `${head?.innerHTML} ${body?.innerHTML}`;
}
/**
* Applies the given Markdown to the document, this essentially creates a
* single change in the collaborative state that makes all the edits to get
* to the provided Markdown.
*
* @param document The document to apply the changes to
* @param text The markdown to apply
* @param append If true appends the markdown instead of replacing existing
* content
* @returns The document
*/
static applyMarkdownToDocument(
document: Document,
text: string,
append = false
) {
document.text = append ? document.text + text : text;
const doc = parser.parse(document.text);
if (document.state) {
const ydoc = new Y.Doc();
Y.applyUpdate(ydoc, document.state);
const type = ydoc.get("default", Y.XmlFragment) as Y.XmlFragment;
if (!type.doc) {
throw new Error("type.doc not found");
}
// apply new document to existing ydoc
updateYFragment(type.doc, type, doc, new Map());
const state = Y.encodeStateAsUpdate(ydoc);
const node = yDocToProsemirror(schema, ydoc);
document.content = node.toJSON();
document.state = Buffer.from(state);
document.changed("state", true);
} else if (doc) {
document.content = doc.toJSON();
}
return document;
}
/**
* Compares two documents and returns true if the text content is equal. This does not take into account
* changes to other properties such as table column widths, other visual settings.
*
* @param document The document to compare
* @param other The other document to compare
* @returns True if the text content is equal
*/
public static isTextContentEqual(
before: Document | Revision | null,
after: Document | Revision | null
) {
if (!before || !after) {
return false;
}
return (
before.title === after.title &&
this.toMarkdown(before) === this.toMarkdown(after)
);
}
}
``` | /content/code_sandbox/server/models/helpers/DocumentHelper.tsx | xml | 2016-05-22T21:31:47 | 2024-08-16T19:57:22 | outline | outline/outline | 26,751 | 3,618 |
```xml
export const COMPODOC_CONSTANTS = {
navTabDefinitions: [
{
id: 'info',
href: '#info',
'data-link': 'info',
label: 'Info',
depTypes: ['all']
},
{
id: 'readme',
href: '#readme',
'data-link': 'readme',
label: 'README',
depTypes: ['all']
},
{
id: 'source',
href: '#source',
'data-link': 'source',
label: 'Source',
depTypes: ['all']
},
{
id: 'templateData',
href: '#templateData',
'data-link': 'template',
label: 'Template',
depTypes: ['component']
},
{
id: 'styleData',
href: '#styleData',
'data-link': 'style',
label: 'Styles',
depTypes: ['component']
},
{
id: 'tree',
href: '#tree',
'data-link': 'dom-tree',
label: 'DOM Tree',
depTypes: ['component']
},
{
id: 'example',
href: '#example',
'data-link': 'example',
label: 'Examples',
depTypes: ['component', 'directive', 'injectable', 'pipe']
}
]
};
/**
* Max length for the string of a file during Lunr search engine indexing.
* Prevent stack size exceeded
*/
export const MAX_SIZE_FILE_SEARCH_INDEX = 50000;
/**
* Max length for the string of a file during cheerio parsing.
* Prevent stack size exceeded
*/
export const MAX_SIZE_FILE_CHEERIO_PARSING = 400000000;
``` | /content/code_sandbox/src/utils/constants.ts | xml | 2016-10-17T07:09:28 | 2024-08-14T16:30:10 | compodoc | compodoc/compodoc | 3,980 | 373 |
```xml
import { nextTestSetup } from 'e2e-utils'
describe('app-routes-trailing-slash', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it.each(['edge', 'node'])(
'should handle trailing slash for %s runtime',
async (runtime) => {
let res = await next.fetch(`/runtime/${runtime}`, {
redirect: 'manual',
})
expect(res.status).toEqual(308)
expect(res.headers.get('location')).toEndWith(`/runtime/${runtime}/`)
res = await next.fetch(`/runtime/${runtime}/`, {
redirect: 'manual',
})
expect(res.status).toEqual(200)
await expect(res.json()).resolves.toEqual({
url: `/runtime/${runtime}/`,
nextUrl: `/runtime/${runtime}/`,
})
}
)
})
``` | /content/code_sandbox/test/e2e/app-dir/app-routes-trailing-slash/app-routes-trailing-slash.test.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 188 |
```xml
import * as React from 'react';
import cx from 'classnames';
import { createSvgIcon } from '../utils/createSvgIcon';
import { iconClassNames } from '../utils/iconClassNames';
export const ReplyIcon = createSvgIcon({
svg: ({ classes }) => (
<svg role="presentation" focusable="false" viewBox="2 2 16 16" className={classes.svg}>
<path
className={cx(iconClassNames.outline, classes.outlinePart)}
d="M3.707 10.998L7.09619 7.60827C7.29146 7.41301 7.29146 7.09643 7.09619 6.90116C6.92263 6.7276 6.6532 6.70831 6.45834 6.84331L6.38909 6.90116L2.14645 11.1438C1.97288 11.3174 1.9536 11.5868 2.08859 11.7817L2.14645 11.8509L6.38909 16.0936C6.58435 16.2888 6.90093 16.2888 7.09619 16.0936C7.26976 15.92 7.28905 15.6506 7.15405 15.4557L7.09619 15.3864L3.707 11.998L10 11.9974C14.0609 11.9974 17.368 8.76988 17.4961 4.74009L17.5 4.49736C17.5 4.22122 17.2761 3.99736 17 3.99736C16.7239 3.99736 16.5 4.22122 16.5 4.49736C16.5 8.00917 13.715 10.8705 10.2331 10.9933L10 10.9974L3.707 10.998L7.09619 7.60827L3.707 10.998Z"
/>
<path
className={cx(iconClassNames.filled, classes.filledPart)}
d="M4.31 10.498L7.27297 7.53505C7.56586 7.24215 7.56586 6.76728 7.27297 6.47439C7.0067 6.20812 6.59004 6.18391 6.29643 6.40177L6.21231 6.47439L1.96967 10.717C1.7034 10.9833 1.6792 11.4 1.89705 11.6936L1.96967 11.7777L6.21231 16.0203C6.5052 16.3132 6.98008 16.3132 7.27297 16.0203C7.53924 15.7541 7.56344 15.3374 7.34559 15.0438L7.27297 14.9597L4.31 11.998L10 11.9974C14.1979 11.9974 17.6162 8.65973 17.7462 4.49337L17.75 4.24736C17.75 3.83314 17.4142 3.49736 17 3.49736C16.5858 3.49736 16.25 3.83314 16.25 4.24736C16.25 7.62243 13.5748 10.3727 10.2291 10.4932L10 10.4974L4.31 10.498L7.27297 7.53505L4.31 10.498Z"
/>
</svg>
),
displayName: 'ReplyIcon',
});
``` | /content/code_sandbox/packages/fluentui/react-icons-northstar/src/components/ReplyIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 922 |
```xml
<schemalist>
<schema id="bad-type" path="/tests/">
<key name="test" type="-%$#*(a!">
<default></default>
</key>
</schema>
</schemalist>
``` | /content/code_sandbox/utilities/glib/gio/tests/schema-tests/bad-type.gschema.xml | xml | 2016-10-27T09:31:28 | 2024-08-16T19:00:35 | nexmon | seemoo-lab/nexmon | 2,381 | 53 |
```xml
declare const selfref: {
a: number;
b: string;
self: any;
};
``` | /content/code_sandbox/baselines/expr-selfref.d.ts | xml | 2016-08-25T21:07:14 | 2024-07-29T17:30:13 | dts-gen | microsoft/dts-gen | 2,431 | 23 |
```xml
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import type { MixedOutput, Module, ReadOnlyGraph } from 'metro';
// path_to_url
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[])[];
}
``` | /content/code_sandbox/src/js/tools/vendor/expo/expoconfig.ts | xml | 2016-11-30T14:45:57 | 2024-08-16T13:21:38 | sentry-react-native | getsentry/sentry-react-native | 1,558 | 420 |
```xml
import markdownStyles from "./markdown-styles.module.css";
type Props = {
content: string;
};
export function PostBody({ content }: Props) {
return (
<div className="max-w-2xl mx-auto">
<div
className={markdownStyles["markdown"]}
dangerouslySetInnerHTML={{ __html: content }}
/>
</div>
);
}
``` | /content/code_sandbox/examples/blog-starter/src/app/_components/post-body.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 79 |
```xml
import { Document, Schema } from 'mongoose';
import { ILink, attachmentSchema } from '@erxes/api-utils/src/types';
import { field, schemaWrapper } from './utils';
import { STRUCTURE_STATUSES } from '../../../constants';
const commonSchemaFields = {
_id: field({ pkey: true }),
title: field({ type: String }),
code: field({ type: String, unique: true }),
updatedBy: field({ type: String }),
updatedAt: field({ type: Date }),
createdBy: field({ type: String }),
createdAt: field({ type: Date, default: Date.now }),
};
const CoordinateSchame = new Schema({
longitude: field({ type: String, optional: true }),
latitude: field({ type: String, optional: true }),
});
const contactInfoSchema = {
website: field({ type: String, optional: true }),
phoneNumber: field({ type: String, optional: true }),
email: field({ type: String, optional: true }),
address: field({ type: String, optional: true }),
links: field({ type: Object, default: {}, label: 'Links' }),
coordinate: field({
type: CoordinateSchame,
optional: true,
label: 'Longitude and latitude',
}),
image: field({ type: attachmentSchema, optional: true }),
};
interface ICommonTypes {
title: string;
description?: string;
supervisorId?: string;
parentId?: string;
code: string;
}
export interface IStructure extends ICommonTypes {
links?: ILink;
}
export interface IStructureDocument extends IStructure, Document {
_id: string;
}
export const structureSchema = schemaWrapper(
new Schema({
description: field({ type: String, optional: true }),
supervisorId: field({ type: String, optional: true }),
...contactInfoSchema,
...commonSchemaFields,
}),
);
export interface IDepartment extends ICommonTypes {
parentId?: string;
userIds?: string[];
order: string;
}
export interface IDepartmentDocument extends IDepartment, Document {
_id: string;
}
export const departmentSchema = schemaWrapper(
new Schema({
description: field({ type: String, optional: true }),
supervisorId: field({ type: String, optional: true }),
parentId: field({ type: String }),
order: field({ type: String, unique: true }),
status: field({
type: String,
label: 'Status',
default: STRUCTURE_STATUSES.ACTIVE,
}),
...commonSchemaFields,
}),
);
export interface IUnit extends ICommonTypes {
departmentId?: string;
userIds?: string[];
order: string;
}
export interface IUnitDocument extends IUnit, Document {
_id: string;
}
export const unitSchema = schemaWrapper(
new Schema({
description: field({ type: String, optional: true }),
departmentId: field({ type: String, optional: true }),
supervisorId: field({ type: String, optional: true }),
userIds: field({ type: [String], label: 'Related users' }),
...commonSchemaFields,
}),
);
export interface IBranch extends ICommonTypes {
address?: string;
userIds?: string[];
radius?: number;
order: string;
}
export interface IBranchDocument extends IBranch, Document {
_id: string;
}
export interface IPosition extends ICommonTypes {
userIds?: string[];
order: string;
status: string;
}
export interface IPositionDocument extends IPosition, Document {
_id: string;
}
export const branchSchema = schemaWrapper(
new Schema({
parentId: field({ type: String, optional: true }),
...contactInfoSchema,
...commonSchemaFields,
order: field({ type: String, unique: true }),
status: field({
type: String,
label: 'Status',
default: STRUCTURE_STATUSES.ACTIVE,
}),
supervisorId: field({ type: String, optional: true }),
radius: field({ type: Number, label: 'Coordinate radius /M/' }),
}),
);
export const positionSchema = schemaWrapper(
new Schema({
...commonSchemaFields,
parentId: field({ type: String, optional: true }),
order: field({ type: String, unique: true }),
userIds: field({ type: [String], label: 'Related users' }),
status: field({
type: String,
label: 'Status',
default: STRUCTURE_STATUSES.ACTIVE,
}),
}),
);
``` | /content/code_sandbox/packages/core/src/db/models/definitions/structures.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 974 |
```xml
import { LogContexts, type Logger } from 'bs-logger'
import type { Arguments } from 'yargs'
import yargsParser from 'yargs-parser'
import type { TsJestTransformerOptions } from '../types'
import { rootLogger } from '../utils'
const VALID_COMMANDS = ['help', 'config:migrate', 'config:init']
const logger = rootLogger.child({ [LogContexts.namespace]: 'cli', [LogContexts.application]: 'ts-jest' })
/**
* @internal
*/
export type CliCommandArgs = Omit<Arguments, '$0'> & { _: Array<string | number> } & {
jestPreset?: boolean
force?: boolean
tsconfig?: TsJestTransformerOptions['tsconfig']
babel?: boolean
jsdom?: boolean
js?: 'ts' | 'babel'
}
/**
* @internal
*/
export type CliCommand = (argv: CliCommandArgs, logger: Logger) => Promise<void>
async function cli(args: string[]): Promise<void> {
const parsedArgv = yargsParser(args, {
boolean: ['dry-run', 'jest-preset', 'allow-js', 'diff', 'babel', 'force', 'jsdom'],
string: ['tsconfig', 'js'],
count: ['verbose'],
alias: { verbose: ['v'] },
default: { jestPreset: true, verbose: 0 },
coerce: {
js(val: string) {
const res = val.trim().toLowerCase()
if (!['babel', 'ts'].includes(res)) throw new Error(`The 'js' option must be 'babel' or 'ts', given: '${val}'.`)
return res
},
},
})
// deprecated
if (parsedArgv.allowJs != null) {
if (parsedArgv.js) throw new Error("The 'allowJs' and 'js' options cannot be set together.")
parsedArgv.js = parsedArgv.allowJs ? 'ts' : undefined
}
let command = parsedArgv._.shift() as string
const isHelp = command === 'help'
if (isHelp) command = parsedArgv._.shift() as string
if (!VALID_COMMANDS.includes(command)) command = 'help'
const { run, help }: { run: CliCommand; help: CliCommand } = require(`./${command.replace(/:/g, '/')}`)
const cmd = isHelp && command !== 'help' ? help : run
return cmd(parsedArgv, logger)
}
const errorHasMessage = (err: unknown): err is { message: string } => {
if (typeof err !== 'object' || err === null) return false
return 'message' in err
}
/**
* @internal
*/
export async function processArgv(): Promise<void> {
try {
await cli(process.argv.slice(2))
process.exit(0)
} catch (err) {
if (errorHasMessage(err)) {
logger.fatal(err.message)
process.exit(1)
}
}
}
``` | /content/code_sandbox/src/cli/index.ts | xml | 2016-08-30T13:47:17 | 2024-08-16T15:05:40 | ts-jest | kulshekhar/ts-jest | 6,902 | 659 |
```xml
import React from 'react';
import { storiesOf } from '@storybook/react-native';
import { withKnobs } from '@storybook/addon-knobs';
import Wrapper from './../../Wrapper';
import { Example as Playground } from './playground';
import { Example as Disabled } from './disabled';
import { Example as Basic } from './basic';
import { Example as CustomColor } from './customColor';
import { Example as Size } from './size';
import { Example as CustomIcon } from './customIcon';
import { Example as Invalid } from './invalid';
import { Example as WithRef } from './withRef';
import { Example as FormControlled } from './FormControlled';
import { Example as CheckboxGroup } from './checkboxGroup';
import { Example as ControlledCheckbox } from './controlledCheckbox';
import { Example as UnControlledCheckbox } from './uncontrolledCheckbox';
storiesOf('Checkbox', module)
.addDecorator(withKnobs)
.addDecorator((getStory: any) => <Wrapper>{getStory()}</Wrapper>)
.add('Basic', () => <Basic />)
.add('Playground', () => <Playground />)
.add('Controlled checkbox', () => <ControlledCheckbox />)
.add('Uncontrolled checkbox', () => <UnControlledCheckbox />)
.add('Disabled', () => <Disabled />)
.add('Invalid', () => <Invalid />)
.add('Size', () => <Size />)
.add('Custom Color', () => <CustomColor />)
.add('Custom Icon', () => <CustomIcon />)
.add('Checkbox Group', () => <CheckboxGroup />)
.add('Form Controlled', () => <FormControlled />)
.add('With Ref', () => <WithRef />);
``` | /content/code_sandbox/example/storybook/stories/components/primitives/Checkbox/index.tsx | xml | 2016-04-15T11:37:23 | 2024-08-14T16:16:44 | NativeBase | GeekyAnts/NativeBase | 20,132 | 364 |
```xml
import angular from 'angular';
import { r2a } from '@/react-tools/react2angular';
import { CustomTemplatesVariablesDefinitionField } from '@/react/portainer/custom-templates/components/CustomTemplatesVariablesDefinitionField';
import { CustomTemplatesVariablesField } from '@/react/portainer/custom-templates/components/CustomTemplatesVariablesField';
import { withControlledInput } from '@/react-tools/withControlledInput';
import { VariablesFieldAngular } from './variables-field';
export const ngModule = angular
.module('portainer.app.react.components.custom-templates', [])
.component(
'customTemplatesVariablesFieldReact',
r2a(withControlledInput(CustomTemplatesVariablesField), [
'value',
'onChange',
'definitions',
'errors',
])
)
.component('customTemplatesVariablesField', VariablesFieldAngular)
.component(
'customTemplatesVariablesDefinitionField',
r2a(withControlledInput(CustomTemplatesVariablesDefinitionField), [
'onChange',
'value',
'errors',
'isVariablesNamesFromParent',
])
);
export const customTemplatesModule = ngModule.name;
``` | /content/code_sandbox/app/portainer/react/components/custom-templates/index.ts | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 238 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
tools:ignore="MissingDefaultResource">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/smoke"/>
</FrameLayout>
``` | /content/code_sandbox/demo/src/main/res/layout/lay_test.xml | xml | 2016-03-28T09:07:07 | 2024-08-15T05:22:18 | SpringView | liaoinstan/SpringView | 1,935 | 113 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="path_to_url">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<ProjectGuid>{28C6451E-B336-4FAA-9903-99BAF7E38D89}</ProjectGuid>
<OutputType>AppContainerExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>AppUIBasics</RootNamespace>
<AssemblyName>AppUIBasics</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.14393.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.14393.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<PackageCertificateThumbprint>0CA738D6E3AA015B7E3CFB902333F76791E1E082</PackageCertificateThumbprint>
<PackageCertificateKeyFile>..\..\WinAppDriver.pfx</PackageCertificateKeyFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_APP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
<OutputPath>bin\ARM\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_APP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_APP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_APP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_APP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_APP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<ItemGroup>
<None Include="project.json" />
</ItemGroup>
<ItemGroup>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
<Compile Include="Common\BooleanNegationConverter.cs" />
<Compile Include="Common\BooleanToVisibilityConverter.cs" />
<Compile Include="Common\ColorStringConverter.cs" />
<Compile Include="Common\ComboBoxItemToStringConverter.cs" />
<Compile Include="Common\DoubleToIntConverter.cs" />
<Compile Include="Common\NavigationHelper.cs" />
<Compile Include="Common\NullableBooleanToBooleanConverter.cs" />
<Compile Include="Common\ObservableDictionary.cs" />
<Compile Include="Common\OrientedSize.cs" />
<Compile Include="Common\RelayCommand.cs" />
<Compile Include="Common\StringToBrushConverter.cs" />
<Compile Include="Common\SuspensionManager.cs" />
<Compile Include="Common\ValueToFontFamilyConverter.cs" />
<Compile Include="Common\ValueToStringConverter.cs" />
<Compile Include="Common\WrapPanel.cs" />
<Compile Include="ControlExample.xaml.cs">
<DependentUpon>ControlExample.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\AppBarButtonPage.xaml.cs">
<DependentUpon>AppBarButtonPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\AppBarPage.xaml.cs">
<DependentUpon>AppBarPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\AppBarSeparatorPage.xaml.cs">
<DependentUpon>AppBarSeparatorPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\AppBarToggleButtonPage.xaml.cs">
<DependentUpon>AppBarToggleButtonPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\AutoSuggestBoxPage.xaml.cs">
<DependentUpon>AutoSuggestBoxPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\BorderPage.xaml.cs">
<DependentUpon>BorderPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ButtonPage.xaml.cs">
<DependentUpon>ButtonPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\CalendarViewPage.xaml.cs">
<DependentUpon>CalendarViewPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\CanvasPage.xaml.cs">
<DependentUpon>CanvasPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\CheckBoxPage.xaml.cs">
<DependentUpon>CheckBoxPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ComboBoxPage.xaml.cs">
<DependentUpon>ComboBoxPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\CommandBarPage.xaml.cs">
<DependentUpon>CommandBarPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ContentDialogExample.xaml.cs">
<DependentUpon>ContentDialogExample.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ContentDialogPage.xaml.cs">
<DependentUpon>ContentDialogPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\DatePickerPage.xaml.cs">
<DependentUpon>DatePickerPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\FlipViewPage.xaml.cs">
<DependentUpon>FlipViewPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\FlyoutPage.xaml.cs">
<DependentUpon>FlyoutPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\GridPage.xaml.cs">
<DependentUpon>GridPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\GridViewPage.xaml.cs">
<DependentUpon>GridViewPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\HubPage.xaml.cs">
<DependentUpon>HubPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\HyperlinkButtonPage.xaml.cs">
<DependentUpon>HyperlinkButtonPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ImagePage.xaml.cs">
<DependentUpon>ImagePage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\InkCanvasPage.xaml.cs">
<DependentUpon>InkCanvasPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ListBoxPage.xaml.cs">
<DependentUpon>ListBoxPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ListViewPage.xaml.cs">
<DependentUpon>ListViewPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\MediaElementPage.xaml.cs">
<DependentUpon>MediaElementPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\MenuFlyoutPage.xaml.cs">
<DependentUpon>MenuFlyoutPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\PasswordBoxPage.xaml.cs">
<DependentUpon>PasswordBoxPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\PivotPage.xaml.cs">
<DependentUpon>PivotPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ProgressBarPage.xaml.cs">
<DependentUpon>ProgressBarPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ProgressRingPage.xaml.cs">
<DependentUpon>ProgressRingPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\RadioButtonPage.xaml.cs">
<DependentUpon>RadioButtonPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\RelativePanelPage.xaml.cs">
<DependentUpon>RelativePanelPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\RepeatButtonPage.xaml.cs">
<DependentUpon>RepeatButtonPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\RichEditBoxPage.xaml.cs">
<DependentUpon>RichEditBoxPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\RichTextBlockPage.xaml.cs">
<DependentUpon>RichTextBlockPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ScrollViewerPage.xaml.cs">
<DependentUpon>ScrollViewerPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\SemanticZoomPage.xaml.cs">
<DependentUpon>SemanticZoomPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\SliderPage.xaml.cs">
<DependentUpon>SliderPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\SplitViewPage.xaml.cs">
<DependentUpon>SplitViewPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\StackPanelPage.xaml.cs">
<DependentUpon>StackPanelPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\TextBlockPage.xaml.cs">
<DependentUpon>TextBlockPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\TextBoxPage.xaml.cs">
<DependentUpon>TextBoxPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\TimePickerPage.xaml.cs">
<DependentUpon>TimePickerPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ToggleButtonPage.xaml.cs">
<DependentUpon>ToggleButtonPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ToggleSwitchPage.xaml.cs">
<DependentUpon>ToggleSwitchPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ToolTipPage.xaml.cs">
<DependentUpon>ToolTipPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\VariableSizedWrapGridPage.xaml.cs">
<DependentUpon>VariableSizedWrapGridPage.xaml</DependentUpon>
</Compile>
<Compile Include="ControlPages\ViewBoxPage.xaml.cs">
<DependentUpon>ViewBoxPage.xaml</DependentUpon>
</Compile>
<Compile Include="DataModel\ControlInfoDataSource.cs" />
<Compile Include="ItemPage.xaml.cs">
<DependentUpon>ItemPage.xaml</DependentUpon>
</Compile>
<Compile Include="MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon>
</Compile>
<Compile Include="Navigation\NavigationRootPage.xaml.cs">
<DependentUpon>NavigationRootPage.xaml</DependentUpon>
</Compile>
<Compile Include="PageHeader.xaml.cs">
<DependentUpon>PageHeader.xaml</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SearchResultsPage.xaml.cs">
<DependentUpon>SearchResultsPage.xaml</DependentUpon>
</Compile>
<Compile Include="SectionPage.xaml.cs">
<DependentUpon>SectionPage.xaml</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
<Content Include="Properties\Default.rd.xml" />
<Content Include="Assets\AutoSuggestBox.png" />
<Content Include="Assets\CalendarView.png" />
<Content Include="Assets\ContentDialog.png" />
<Content Include="Assets\fishes.wmv" />
<Content Include="Assets\Image.png" />
<Content Include="Assets\InkCanvas.png" />
<Content Include="Assets\ladybug.wmv" />
<Content Include="Assets\MediaElement.png" />
<Content Include="Assets\ninegrid.gif" />
<Content Include="Assets\Pivot.png" />
<Content Include="Assets\RelativePanel.png" />
<Content Include="Assets\splash-sdk.png" />
<Content Include="Assets\smalltile-sdk.png" />
<Content Include="Assets\squaretile-sdk.png" />
<Content Include="Assets\SplitView.png" />
<Content Include="Assets\treetops.jpg" />
<Content Include="Assets\storelogo-sdk.png" />
<Content Include="DataModel\ControlInfoData.json" />
<PRIResource Include="Strings\en-US\Resources.resw" />
</ItemGroup>
<ItemGroup>
<Content Include="Assets\AppBar.png" />
<Content Include="Assets\AppBarButton.png" />
<Content Include="Assets\AppBarSeparator.png" />
<Content Include="Assets\AppBarToggleButton.png" />
<Content Include="Assets\badgelogo.scale-100.png" />
<Content Include="Assets\badgelogo.scale-140.png" />
<Content Include="Assets\badgelogo.scale-180.png" />
<Content Include="Assets\Border.png" />
<Content Include="Assets\Button.png" />
<Content Include="Assets\Canvas.png" />
<Content Include="Assets\CheckBox.png" />
<Content Include="Assets\cliff.jpg" />
<Content Include="Assets\ComboBox.png" />
<Content Include="Assets\CommandBar.png" />
<Content Include="Assets\DarkGray.png" />
<Content Include="Assets\DatePicker.png" />
<Content Include="Assets\FlipView.png" />
<Content Include="Assets\Flyout.png" />
<Content Include="Assets\grapes.jpg" />
<Content Include="Assets\Grid.png" />
<Content Include="Assets\GridView.png" />
<Content Include="Assets\HeroImage.png" />
<Content Include="Assets\Hub.png" />
<Content Include="Assets\HyperlinkButton.png" />
<Content Include="Assets\LightGray.png" />
<Content Include="Assets\ListBox.png" />
<Content Include="Assets\ListView.png" />
<Content Include="Assets\MediumGray.png" />
<Content Include="Assets\MenuFlyout.png" />
<Content Include="Assets\PasswordBox.png" />
<Content Include="Assets\ProgressBar.png" />
<Content Include="Assets\ProgressRing.png" />
<Content Include="Assets\RadioButton.png" />
<Content Include="Assets\rainier.jpg" />
<Content Include="Assets\RichEditBox.png" />
<Content Include="Assets\RichTextBlock.png" />
<Content Include="Assets\ScrollViewer.png" />
<Content Include="Assets\SemanticZoom.png" />
<Content Include="Assets\SettingsFlyout.png" />
<Content Include="Assets\Slices.png" />
<Content Include="Assets\Slices2.png" />
<Content Include="Assets\Slider.png" />
<Content Include="Assets\StackPanel.png" />
<Content Include="Assets\sunset.jpg" />
<Content Include="Assets\TextBlock.png" />
<Content Include="Assets\TextBox.png" />
<Content Include="Assets\TimePicker.png" />
<Content Include="Assets\ToggleButton.png" />
<Content Include="Assets\ToggleSwitch.png" />
<Content Include="Assets\ToolTip.png" />
<Content Include="Assets\valley.jpg" />
<Content Include="Assets\VariableSizedWrapGrid.png" />
<Content Include="Assets\ViewBox.png" />
<Content Include="Assets\widelogo.scale-100.png" />
<Content Include="Assets\widelogo.scale-140.png" />
<Content Include="Assets\widelogo.scale-180.png" />
<Content Include="Assets\WideLogo.scale-80.png" />
<Content Include="Common\ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="ControlExample.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\AppBarButtonPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\AppBarPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\AppBarSeparatorPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\AppBarToggleButtonPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\AutoSuggestBoxPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\BorderPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ButtonPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\CalendarViewPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\CanvasPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\CheckBoxPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ComboBoxPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\CommandBarPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ContentDialogExample.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\ContentDialogPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\DatePickerPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\FlipViewPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\FlyoutPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\GridPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\GridViewPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\HubPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\HyperlinkButtonPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ImagePage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\InkCanvasPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\ListBoxPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ListViewPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\MediaElementPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\MenuFlyoutPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\PasswordBoxPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\PivotPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\ProgressBarPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ProgressRingPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\RadioButtonPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\RelativePanelPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\RepeatButtonPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\RichEditBoxPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\RichTextBlockPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ScrollViewerPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\SemanticZoomPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\SliderPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\SplitViewPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="ControlPages\StackPanelPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\TextBlockPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\TextBoxPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\TimePickerPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ToggleButtonPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ToggleSwitchPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ToolTipPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\VariableSizedWrapGridPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ControlPages\ViewBoxPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="ItemPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="MainPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Navigation\NavigationRootPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="PageHeader.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="SearchResultsPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="SectionPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' < '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
``` | /content/code_sandbox/ApplicationUnderTests/AppUIBasics/AppUIBasics.csproj | xml | 2016-03-20T08:48:45 | 2024-08-16T07:55:40 | WinAppDriver | microsoft/WinAppDriver | 3,626 | 6,646 |
```xml
export * from './Funnel'
export * from './ResponsiveFunnel'
export * from './hooks'
export * from './props'
export * from './types'
``` | /content/code_sandbox/packages/funnel/src/index.ts | xml | 2016-04-16T03:27:56 | 2024-08-16T03:38:37 | nivo | plouc/nivo | 13,010 | 34 |
```xml
import React from "react";
import { ImportFromModheader } from "./ModheaderImporter";
export const ImportFromModheaderWrapperView: React.FC = () => {
return (
<div className="importer-wrapper">
<ImportFromModheader />
</div>
);
};
``` | /content/code_sandbox/app/src/features/rules/screens/rulesList/components/RulesList/components/ImporterComponents/ModheaderImporter/ImportFromModheaderScreen.tsx | xml | 2016-12-01T04:36:06 | 2024-08-16T19:12:19 | requestly | requestly/requestly | 2,121 | 61 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="path_to_url"
android:color="@color/gray_dark" />
``` | /content/code_sandbox/app/src/main/res/drawable/transparent_round_ripple_dark.xml | xml | 2016-10-18T15:38:44 | 2024-08-16T19:19:31 | libretorrent | proninyaroslav/libretorrent | 1,973 | 36 |
```xml
import React from 'react';
import { CircularProgress, Heading, Center } from 'native-base';
export const Example = () => {
return (
<Center>
<Heading mb={6}>Adding label</Heading>
<CircularProgress value={60}>60%</CircularProgress>
</Center>
);
};
``` | /content/code_sandbox/example/storybook/stories/components/composites/CircularProgress/Label.tsx | xml | 2016-04-15T11:37:23 | 2024-08-14T16:16:44 | NativeBase | GeekyAnts/NativeBase | 20,132 | 66 |
```xml
import gql from "graphql-tag";
import { ApolloLink } from "../../core";
import { Observable } from "../../../utilities/observables/Observable";
import { execute } from "../../core/execute";
import { setContext } from "../index";
import { itAsync } from "../../../testing";
const sleep = (ms: number) => new Promise((s) => setTimeout(s, ms));
const query = gql`
query Test {
foo {
bar
}
}
`;
const data = {
foo: { bar: true },
};
itAsync(
"can be used to set the context with a simple function",
(resolve, reject) => {
const withContext = setContext(() => ({ dynamicallySet: true }));
const mockLink = new ApolloLink((operation) => {
expect(operation.getContext().dynamicallySet).toBe(true);
return Observable.of({ data });
});
const link = withContext.concat(mockLink);
execute(link, { query }).subscribe((result) => {
expect(result.data).toEqual(data);
resolve();
});
}
);
itAsync(
"can be used to set the context with a function returning a promise",
(resolve, reject) => {
const withContext = setContext(() =>
Promise.resolve({ dynamicallySet: true })
);
const mockLink = new ApolloLink((operation) => {
expect(operation.getContext().dynamicallySet).toBe(true);
return Observable.of({ data });
});
const link = withContext.concat(mockLink);
execute(link, { query }).subscribe((result) => {
expect(result.data).toEqual(data);
resolve();
});
}
);
itAsync(
"can be used to set the context with a function returning a promise that is delayed",
(resolve, reject) => {
const withContext = setContext(() =>
sleep(25).then(() => ({ dynamicallySet: true }))
);
const mockLink = new ApolloLink((operation) => {
expect(operation.getContext().dynamicallySet).toBe(true);
return Observable.of({ data });
});
const link = withContext.concat(mockLink);
execute(link, { query }).subscribe((result) => {
expect(result.data).toEqual(data);
resolve();
});
}
);
itAsync("handles errors in the lookup correclty", (resolve, reject) => {
const withContext = setContext(() =>
sleep(5).then(() => {
throw new Error("dang");
})
);
const mockLink = new ApolloLink((operation) => {
return Observable.of({ data });
});
const link = withContext.concat(mockLink);
execute(link, { query }).subscribe(reject, (e) => {
expect(e.message).toBe("dang");
resolve();
});
});
itAsync(
"handles errors in the lookup correclty with a normal function",
(resolve, reject) => {
const withContext = setContext(() => {
throw new Error("dang");
});
const mockLink = new ApolloLink((operation) => {
return Observable.of({ data });
});
const link = withContext.concat(mockLink);
execute(link, { query }).subscribe(reject, (e) => {
expect(e.message).toBe("dang");
resolve();
});
}
);
itAsync("has access to the request information", (resolve, reject) => {
const withContext = setContext(({ operationName, query, variables }) =>
sleep(1).then(() =>
Promise.resolve({
variables: variables ? true : false,
operation: query ? true : false,
operationName: operationName!.toUpperCase(),
})
)
);
const mockLink = new ApolloLink((op) => {
const { variables, operation, operationName } = op.getContext();
expect(variables).toBe(true);
expect(operation).toBe(true);
expect(operationName).toBe("TEST");
return Observable.of({ data });
});
const link = withContext.concat(mockLink);
execute(link, { query, variables: { id: 1 } }).subscribe((result) => {
expect(result.data).toEqual(data);
resolve();
});
});
itAsync("has access to the context at execution time", (resolve, reject) => {
const withContext = setContext((_, { count }) =>
sleep(1).then(() => ({ count: count + 1 }))
);
const mockLink = new ApolloLink((operation) => {
const { count } = operation.getContext();
expect(count).toEqual(2);
return Observable.of({ data });
});
const link = withContext.concat(mockLink);
execute(link, { query, context: { count: 1 } }).subscribe((result) => {
expect(result.data).toEqual(data);
resolve();
});
});
itAsync("unsubscribes correctly", (resolve, reject) => {
const withContext = setContext((_, { count }) =>
sleep(1).then(() => ({ count: count + 1 }))
);
const mockLink = new ApolloLink((operation) => {
const { count } = operation.getContext();
expect(count).toEqual(2);
return Observable.of({ data });
});
const link = withContext.concat(mockLink);
let handle = execute(link, {
query,
context: { count: 1 },
}).subscribe((result) => {
expect(result.data).toEqual(data);
handle.unsubscribe();
resolve();
});
});
itAsync("unsubscribes without throwing before data", (resolve, reject) => {
let called: boolean;
const withContext = setContext((_, { count }) => {
called = true;
return sleep(1).then(() => ({ count: count + 1 }));
});
const mockLink = new ApolloLink((operation) => {
const { count } = operation.getContext();
expect(count).toEqual(2);
return new Observable((obs) => {
setTimeout(() => {
obs.next({ data });
obs.complete();
}, 25);
});
});
const link = withContext.concat(mockLink);
let handle = execute(link, {
query,
context: { count: 1 },
}).subscribe((result) => {
reject("should have unsubscribed");
});
setTimeout(() => {
handle.unsubscribe();
expect(called).toBe(true);
resolve();
}, 10);
});
itAsync(
"does not start the next link subscription if the upstream subscription is already closed",
(resolve, reject) => {
let promiseResolved = false;
const withContext = setContext(() =>
sleep(5).then(() => {
promiseResolved = true;
return { dynamicallySet: true };
})
);
let mockLinkCalled = false;
const mockLink = new ApolloLink(() => {
mockLinkCalled = true;
reject("link should not be called");
return new Observable((observer) => {
observer.error("link should not have been observed");
});
});
const link = withContext.concat(mockLink);
let subscriptionReturnedData = false;
let handle = execute(link, { query }).subscribe((result) => {
subscriptionReturnedData = true;
reject("subscription should not return data");
});
handle.unsubscribe();
setTimeout(() => {
expect(promiseResolved).toBe(true);
expect(mockLinkCalled).toBe(false);
expect(subscriptionReturnedData).toBe(false);
resolve();
}, 10);
}
);
``` | /content/code_sandbox/src/link/context/__tests__/index.ts | xml | 2016-02-26T20:25:00 | 2024-08-16T10:56:57 | apollo-client | apollographql/apollo-client | 19,304 | 1,590 |
```xml
import * as secondary from './base';
/* Import singleton constructors */
import styled from './constructors/styled';
/**
* eliminates the need to do styled.default since the other APIs
* are directly assigned as properties to the main function
* */
for (const key in secondary) {
// @ts-expect-error shush
styled[key] = secondary[key];
}
export default styled;
``` | /content/code_sandbox/packages/styled-components/src/index-standalone.ts | xml | 2016-08-16T06:41:32 | 2024-08-16T12:59:53 | styled-components | styled-components/styled-components | 40,332 | 81 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<manifest xmlns:android="path_to_url"
xmlns:tools="path_to_url"
package="com.google.android.material.ripple">
<uses-sdk
tools:overrideLibrary="androidx.test.core"/>
<application/>
</manifest>
``` | /content/code_sandbox/lib/javatests/com/google/android/material/ripple/AndroidManifest.xml | xml | 2016-12-05T16:11:29 | 2024-08-16T17:51:42 | material-components-android | material-components/material-components-android | 16,176 | 104 |
```xml
/*
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
import { codec, Schema } from '@liskhq/lisk-codec';
import { Dealer } from 'zeromq';
import {
ABI,
IPCResponse,
initRequestSchema,
initResponseSchema,
InitRequest,
InitResponse,
InitStateMachineRequest,
InitStateMachineResponse,
InitGenesisStateRequest,
InitGenesisStateResponse,
InsertAssetsRequest,
InsertAssetsResponse,
VerifyAssetsRequest,
VerifyAssetsResponse,
BeforeTransactionsExecuteRequest,
BeforeTransactionsExecuteResponse,
AfterTransactionsExecuteRequest,
AfterTransactionsExecuteResponse,
VerifyTransactionRequest,
VerifyTransactionResponse,
ExecuteTransactionRequest,
ExecuteTransactionResponse,
CommitRequest,
CommitResponse,
RevertRequest,
RevertResponse,
ClearRequest,
ClearResponse,
FinalizeRequest,
FinalizeResponse,
MetadataRequest,
MetadataResponse,
QueryRequest,
QueryResponse,
ProveRequest,
ProveResponse,
afterTransactionsExecuteRequestSchema,
afterTransactionsExecuteResponseSchema,
beforeTransactionsExecuteRequestSchema,
beforeTransactionsExecuteResponseSchema,
clearRequestSchema,
clearResponseSchema,
commitRequestSchema,
commitResponseSchema,
executeTransactionRequestSchema,
executeTransactionResponseSchema,
finalizeRequestSchema,
finalizeResponseSchema,
initGenesisStateRequestSchema,
initGenesisStateResponseSchema,
initStateMachineRequestSchema,
initStateMachineResponseSchema,
insertAssetsRequestSchema,
insertAssetsResponseSchema,
ipcRequestSchema,
ipcResponseSchema,
metadataRequestSchema,
metadataResponseSchema,
proveRequestSchema,
proveResponseSchema,
queryRequestSchema,
queryResponseSchema,
revertRequestSchema,
revertResponseSchema,
verifyAssetsRequestSchema,
verifyAssetsResponseSchema,
verifyTransactionRequestSchema,
verifyTransactionResponseSchema,
} from '../abi';
import { Logger } from '../logger';
const DEFAULT_TIMEOUT = 3000;
const MAX_UINT64 = BigInt(2) ** BigInt(64) - BigInt(1);
interface Defer<T> {
promise: Promise<T>;
resolve: (result: T) => void;
reject: (error?: Error) => void;
}
const defer = <T>(): Defer<T> => {
let resolve!: (res: T) => void;
let reject!: (error?: Error) => void;
const promise = new Promise<T>((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return { promise, resolve, reject };
};
const timeout = async (ms: number, message?: string): Promise<never> =>
new Promise((_, reject) => {
const id = setTimeout(() => {
clearTimeout(id);
reject(new Error(message ?? `Timed out in ${ms}ms.`));
}, ms);
});
export class ABIClient implements ABI {
private readonly _socketPath: string;
private readonly _dealer: Dealer;
private readonly _logger: Logger;
private _pendingRequests: {
[key: string]: Defer<unknown>;
} = {};
private _globalID = BigInt(0);
public constructor(logger: Logger, socketPath: string) {
this._logger = logger;
this._socketPath = socketPath;
this._dealer = new Dealer();
}
public async start(): Promise<void> {
await new Promise((resolve, reject) => {
const connectionTimeout = setTimeout(() => {
reject(
new Error('IPC Socket client connection timeout. Please check if IPC server is running.'),
);
}, DEFAULT_TIMEOUT);
this._dealer.events.on('connect', () => {
clearTimeout(connectionTimeout);
resolve(undefined);
});
this._dealer.events.on('bind:error', reject);
this._dealer.connect(this._socketPath);
});
this._listenToRPCResponse().catch(err => {
this._logger.debug({ err: err as Error }, 'Failed to listen to the ABI response');
});
}
public stop(): void {
this._dealer.disconnect(this._socketPath);
this._pendingRequests = {};
this._globalID = BigInt(0);
}
public async init(req: InitRequest): Promise<InitResponse> {
return this._call<InitResponse>('init', req, initRequestSchema, initResponseSchema);
}
public async initStateMachine(req: InitStateMachineRequest): Promise<InitStateMachineResponse> {
return this._call<InitStateMachineResponse>(
'initStateMachine',
req,
initStateMachineRequestSchema,
initStateMachineResponseSchema,
);
}
public async initGenesisState(req: InitGenesisStateRequest): Promise<InitGenesisStateResponse> {
return this._call<InitGenesisStateResponse>(
'initGenesisState',
req,
initGenesisStateRequestSchema,
initGenesisStateResponseSchema,
);
}
public async insertAssets(req: InsertAssetsRequest): Promise<InsertAssetsResponse> {
return this._call<InsertAssetsResponse>(
'insertAssets',
req,
insertAssetsRequestSchema,
insertAssetsResponseSchema,
);
}
public async verifyAssets(req: VerifyAssetsRequest): Promise<VerifyAssetsResponse> {
return this._call<VerifyAssetsResponse>(
'verifyAssets',
req,
verifyAssetsRequestSchema,
verifyAssetsResponseSchema,
);
}
public async beforeTransactionsExecute(
req: BeforeTransactionsExecuteRequest,
): Promise<BeforeTransactionsExecuteResponse> {
return this._call<BeforeTransactionsExecuteResponse>(
'beforeTransactionsExecute',
req,
beforeTransactionsExecuteRequestSchema,
beforeTransactionsExecuteResponseSchema,
);
}
public async afterTransactionsExecute(
req: AfterTransactionsExecuteRequest,
): Promise<AfterTransactionsExecuteResponse> {
return this._call<AfterTransactionsExecuteResponse>(
'afterTransactionsExecute',
req,
afterTransactionsExecuteRequestSchema,
afterTransactionsExecuteResponseSchema,
);
}
public async verifyTransaction(
req: VerifyTransactionRequest,
): Promise<VerifyTransactionResponse> {
return this._call<VerifyTransactionResponse>(
'verifyTransaction',
req,
verifyTransactionRequestSchema,
verifyTransactionResponseSchema,
);
}
public async executeTransaction(
req: ExecuteTransactionRequest,
): Promise<ExecuteTransactionResponse> {
return this._call<ExecuteTransactionResponse>(
'executeTransaction',
req,
executeTransactionRequestSchema,
executeTransactionResponseSchema,
);
}
public async commit(req: CommitRequest): Promise<CommitResponse> {
return this._call<CommitResponse>('commit', req, commitRequestSchema, commitResponseSchema);
}
public async revert(req: RevertRequest): Promise<RevertResponse> {
return this._call<RevertResponse>('revert', req, revertRequestSchema, revertResponseSchema);
}
public async clear(req: ClearRequest): Promise<ClearResponse> {
return this._call<ClearResponse>('clear', req, clearRequestSchema, clearResponseSchema);
}
public async finalize(req: FinalizeRequest): Promise<FinalizeResponse> {
return this._call<FinalizeResponse>(
'finalize',
req,
finalizeRequestSchema,
finalizeResponseSchema,
);
}
public async getMetadata(req: MetadataRequest): Promise<MetadataResponse> {
return this._call<MetadataResponse>(
'getMetadata',
req,
metadataRequestSchema,
metadataResponseSchema,
);
}
public async query(req: QueryRequest): Promise<QueryResponse> {
return this._call<QueryResponse>('query', req, queryRequestSchema, queryResponseSchema);
}
public async prove(req: ProveRequest): Promise<ProveResponse> {
return this._call<ProveResponse>('prove', req, proveRequestSchema, proveResponseSchema);
}
// eslint-disable-next-line @typescript-eslint/ban-types
private async _call<T>(
method: string,
req: object,
requestSchema: Schema,
respSchema: Schema,
): Promise<T> {
const params =
Object.keys(requestSchema.properties).length > 0
? codec.encode(requestSchema, req)
: Buffer.alloc(0);
const requestBody = {
id: this._globalID,
method,
params,
};
this._logger.debug(
{ method: requestBody.method, id: requestBody.id, file: 'abi_client' },
'Requesting ABI server',
);
const encodedRequest = codec.encode(ipcRequestSchema, requestBody);
await this._dealer.send([encodedRequest]);
const response = defer<Buffer>();
this._pendingRequests[this._globalID.toString()] = response as Defer<unknown>;
// Increment ID before async task, reset to zero at MAX uint64
this._globalID += BigInt(1);
if (this._globalID >= MAX_UINT64) {
this._globalID = BigInt(0);
}
const resp = await Promise.race([
response.promise,
timeout(DEFAULT_TIMEOUT, `Response not received in ${DEFAULT_TIMEOUT}ms`),
]);
this._logger.debug(
{ method: requestBody.method, id: requestBody.id, file: 'abi_client' },
'Received response from ABI server',
);
const decodedResp =
Object.keys(respSchema.properties).length > 0 ? codec.decode<T>(respSchema, resp) : ({} as T);
return decodedResp;
}
private async _listenToRPCResponse() {
for await (const [message] of this._dealer) {
let response: IPCResponse;
try {
response = codec.decode<IPCResponse>(ipcResponseSchema, message);
} catch (error) {
this._logger.debug({ err: error as Error }, 'Failed to decode ABI response');
continue;
}
const deferred = this._pendingRequests[response.id.toString()];
if (!deferred) {
continue;
}
if (!response.success) {
deferred.reject(new Error(response.error.message));
} else {
deferred.resolve(response.result);
}
delete this._pendingRequests[response.id.toString()];
}
}
}
``` | /content/code_sandbox/framework/src/abi_handler/abi_client.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 2,239 |
```xml
import type { Maybe, MaybePromise } from '@proton/pass/types';
import { logger } from '@proton/pass/utils/logger';
import type { Subscriber } from '@proton/pass/utils/pubsub/factory';
import { createPubSub } from '@proton/pass/utils/pubsub/factory';
import { DEFAULT_LOCALE } from '@proton/shared/lib/constants';
import { localeCode } from '@proton/shared/lib/i18n';
import { getClosestLocaleCode, getLanguageCode } from '@proton/shared/lib/i18n/helper';
import { loadDateLocale, loadLocale } from '@proton/shared/lib/i18n/loadLocale';
import { setTtagLocales } from '@proton/shared/lib/i18n/locales';
import { type TtagLocaleMap } from '@proton/shared/lib/interfaces/Locale';
import noop from '@proton/utils/noop';
type I18nServiceOptions = {
locales: TtagLocaleMap;
loadDateLocale: boolean;
getLocale: () => MaybePromise<Maybe<string>>;
onLocaleChange?: (locale: string) => void;
};
type LocaleEvent = { locale: string };
export const createI18nService = (options: I18nServiceOptions) => {
setTtagLocales(options.locales);
const pubsub = createPubSub<LocaleEvent>();
const hasRegion = (locale: string) => /[_-]/.test(locale);
const getFallbackLocale = (): string => {
const [fst, snd] = navigator.languages;
if (!fst && !snd) return DEFAULT_LOCALE;
return !hasRegion(fst) && hasRegion(snd) && getLanguageCode(fst) === getLanguageCode(snd) ? snd : fst;
};
const getLocale = async () => (await options.getLocale()) ?? getFallbackLocale();
const setLocale = async (locale?: string) => {
try {
const nextLocale = getClosestLocaleCode(locale ?? (await getLocale()), options.locales);
if (options.loadDateLocale) await loadDateLocale(nextLocale).catch(noop);
await loadLocale(nextLocale, options.locales);
options.onLocaleChange?.(nextLocale);
pubsub.publish({ locale: nextLocale });
if (nextLocale !== localeCode) logger.info(`[I18nService] changing locale to ${locale}`);
} catch {}
};
return {
setLocale,
getLocale,
getFallbackLocale,
subscribe: (fn: Subscriber<LocaleEvent>) => pubsub.subscribe(fn),
unsubscribe: () => pubsub.unsubscribe(),
};
};
export type I18nService = ReturnType<typeof createI18nService>;
``` | /content/code_sandbox/packages/pass/lib/i18n/service.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 565 |
```xml
// luma.gl
import type {ShaderUniformType} from '../gpu-type-utils/shader-types';
import type {UniformValue} from '../adapter/types/uniforms';
import type {Device} from '../adapter/device';
import {Buffer} from '../adapter/resources/buffer';
import {log} from '../utils/log';
import {UniformBlock} from './uniform-block';
import {UniformBufferLayout} from './uniform-buffer-layout';
export type ShaderModuleInputs = {
uniformTypes?: Record<string, ShaderUniformType>;
defaultProps?: Record<string, unknown>;
defaultUniforms?: Record<string, UniformValue>;
};
/**
* A uniform store holds a uniform values for one or more uniform blocks,
* - It can generate binary data for any uniform buffer
* - It can manage a uniform buffer for each block
* - It can update managed uniform buffers with a single call
* - It performs some book keeping on what has changed to minimize unnecessary writes to uniform buffers.
*/
export class UniformStore<
TPropGroups extends Record<string, Record<string, unknown>> = Record<
string,
Record<string, unknown>
>
> {
/** Stores the uniform values for each uniform block */
uniformBlocks = new Map<keyof TPropGroups, UniformBlock>();
/** Can generate data for a uniform buffer for each block from data */
uniformBufferLayouts = new Map<keyof TPropGroups, UniformBufferLayout>();
/** Actual buffer for the blocks */
uniformBuffers = new Map<keyof TPropGroups, Buffer>();
/**
* Create a new UniformStore instance
* @param blocks
*/
constructor(
blocks: Record<
keyof TPropGroups,
{
uniformTypes?: Record<string, ShaderUniformType>;
defaultProps?: Record<string, unknown>;
defaultUniforms?: Record<string, UniformValue>;
}
>
) {
for (const [bufferName, block] of Object.entries(blocks)) {
const uniformBufferName = bufferName as keyof TPropGroups;
// Create a layout object to help us generate correctly formatted binary uniform buffers
const uniformBufferLayout = new UniformBufferLayout(block.uniformTypes || {});
this.uniformBufferLayouts.set(uniformBufferName, uniformBufferLayout);
// Create a Uniform block to store the uniforms for each buffer.
const uniformBlock = new UniformBlock({name: bufferName});
uniformBlock.setUniforms(block.defaultUniforms || {});
this.uniformBlocks.set(uniformBufferName, uniformBlock);
}
}
/** Destroy any managed uniform buffers */
destroy(): void {
for (const uniformBuffer of this.uniformBuffers.values()) {
uniformBuffer.destroy();
}
}
/**
* Set uniforms
* Makes all properties partial
*/
setUniforms(
uniforms: Partial<{[group in keyof TPropGroups]: Partial<TPropGroups[group]>}>
): void {
for (const [blockName, uniformValues] of Object.entries(uniforms)) {
this.uniformBlocks.get(blockName)?.setUniforms(uniformValues);
// We leverage logging in updateUniformBuffers(), even though slightly less efficient
// this.updateUniformBuffer(blockName);
}
this.updateUniformBuffers();
}
/** Get the required minimum length of the uniform buffer */
getUniformBufferByteLength(uniformBufferName: keyof TPropGroups): number {
return this.uniformBufferLayouts.get(uniformBufferName)?.byteLength || 0;
}
/** Get formatted binary memory that can be uploaded to a buffer */
getUniformBufferData(uniformBufferName: keyof TPropGroups): Uint8Array {
const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms() || {};
// @ts-ignore
return this.uniformBufferLayouts.get(uniformBufferName)?.getData(uniformValues);
}
/**
* Creates an unmanaged uniform buffer (umnanaged means that application is responsible for destroying it)
* The new buffer is initialized with current / supplied values
*/
createUniformBuffer(
device: Device,
uniformBufferName: keyof TPropGroups,
uniforms?: Partial<{[group in keyof TPropGroups]: Partial<TPropGroups[group]>}>
): Buffer {
if (uniforms) {
this.setUniforms(uniforms);
}
const byteLength = this.getUniformBufferByteLength(uniformBufferName);
const uniformBuffer = device.createBuffer({
usage: Buffer.UNIFORM | Buffer.COPY_DST,
byteLength
});
// Note that this clears the needs redraw flag
const uniformBufferData = this.getUniformBufferData(uniformBufferName);
uniformBuffer.write(uniformBufferData);
return uniformBuffer;
}
/** Get the managed uniform buffer. "managed" resources are destroyed when the uniformStore is destroyed. */
getManagedUniformBuffer(device: Device, uniformBufferName: keyof TPropGroups): Buffer {
if (!this.uniformBuffers.get(uniformBufferName)) {
const byteLength = this.getUniformBufferByteLength(uniformBufferName);
const uniformBuffer = device.createBuffer({
usage: Buffer.UNIFORM | Buffer.COPY_DST,
byteLength
});
this.uniformBuffers.set(uniformBufferName, uniformBuffer);
}
// this.updateUniformBuffers();
// @ts-ignore
return this.uniformBuffers.get(uniformBufferName);
}
/** Updates all uniform buffers where values have changed */
updateUniformBuffers(): false | string {
let reason: false | string = false;
for (const uniformBufferName of this.uniformBlocks.keys()) {
const bufferReason = this.updateUniformBuffer(uniformBufferName);
reason ||= bufferReason;
}
if (reason) {
log.log(3, `UniformStore.updateUniformBuffers(): ${reason}`)();
}
return reason;
}
/** Update one uniform buffer. Only updates if values have changed */
updateUniformBuffer(uniformBufferName: keyof TPropGroups): false | string {
const uniformBlock = this.uniformBlocks.get(uniformBufferName);
let uniformBuffer = this.uniformBuffers.get(uniformBufferName);
let reason: false | string = false;
if (uniformBuffer && uniformBlock?.needsRedraw) {
reason ||= uniformBlock.needsRedraw;
// This clears the needs redraw flag
const uniformBufferData = this.getUniformBufferData(uniformBufferName);
uniformBuffer = this.uniformBuffers.get(uniformBufferName);
uniformBuffer?.write(uniformBufferData);
// logging - TODO - don't query the values unnecessarily
const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms();
log.log(
4,
`Writing to uniform buffer ${String(uniformBufferName)}`,
uniformBufferData,
uniformValues
)();
}
return reason;
}
}
``` | /content/code_sandbox/modules/core/src/portable/uniform-store.ts | xml | 2016-01-25T09:41:59 | 2024-08-16T10:03:05 | luma.gl | visgl/luma.gl | 2,280 | 1,432 |
```xml
import {Component} from '@angular/core';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Listbox with custom keyboard navigation options. */
@Component({
selector: 'cdk-listbox-custom-navigation-example',
exportAs: 'cdkListboxCustomNavigationExample',
templateUrl: 'cdk-listbox-custom-navigation-example.html',
styleUrl: 'cdk-listbox-custom-navigation-example.css',
standalone: true,
imports: [CdkListbox, CdkOption],
})
export class CdkListboxCustomNavigationExample {}
``` | /content/code_sandbox/src/components-examples/cdk/listbox/cdk-listbox-custom-navigation/cdk-listbox-custom-navigation-example.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 124 |
```xml
/// <reference path="../../../__typings__/index.d.ts" />
import fs from 'fs'
import path from 'path'
import { assertProject } from '@pnpm/assert-project'
import { hashObject } from '@pnpm/crypto.object-hasher'
import { getFilePathInCafs } from '@pnpm/store.cafs'
import { ENGINE_NAME, WANTED_LOCKFILE } from '@pnpm/constants'
import {
type PackageManifestLog,
type RootLog,
type StageLog,
type StatsLog,
} from '@pnpm/core-loggers'
import { headlessInstall } from '@pnpm/headless'
import { readWantedLockfile } from '@pnpm/lockfile.fs'
import { readModulesManifest } from '@pnpm/modules-yaml'
import { tempDir } from '@pnpm/prepare'
import { type DepPath } from '@pnpm/types'
import { getIntegrity } from '@pnpm/registry-mock'
import { fixtures } from '@pnpm/test-fixtures'
import { createTestIpcServer } from '@pnpm/test-ipc-server'
import { sync as rimraf } from '@zkochan/rimraf'
import loadJsonFile from 'load-json-file'
import sinon from 'sinon'
import writeJsonFile from 'write-json-file'
import { testDefaults } from './utils/testDefaults'
const f = fixtures(__dirname)
test('installing a simple project', async () => {
const prefix = f.prepare('simple')
const reporter = sinon.spy()
await headlessInstall(await testDefaults({
lockfileDir: prefix,
reporter,
}))
const project = assertProject(prefix)
expect(project.requireModule('is-positive')).toBeTruthy()
expect(project.requireModule('rimraf')).toBeTruthy()
expect(project.requireModule('is-negative')).toBeTruthy()
expect(project.requireModule('colors')).toBeTruthy()
project.has('.pnpm/colors@1.2.0')
project.isExecutable('.bin/rimraf')
expect(project.readCurrentLockfile()).toBeTruthy()
expect(project.readModulesManifest()).toBeTruthy()
expect(reporter.calledWithMatch({
level: 'debug',
name: 'pnpm:package-manifest',
updated: loadJsonFile.sync(path.join(prefix, 'package.json')),
} as PackageManifestLog)).toBeTruthy()
expect(reporter.calledWithMatch({
added: 15,
level: 'debug',
name: 'pnpm:stats',
prefix,
} as StatsLog)).toBeTruthy()
expect(reporter.calledWithMatch({
level: 'debug',
name: 'pnpm:stats',
prefix,
removed: 0,
} as StatsLog)).toBeTruthy()
expect(reporter.calledWithMatch({
level: 'debug',
name: 'pnpm:stage',
prefix,
stage: 'importing_done',
} as StageLog)).toBeTruthy()
expect(reporter.calledWithMatch({
level: 'debug',
packageId: 'is-negative@2.1.0',
requester: prefix,
status: 'resolved',
})).toBeTruthy()
reporter.resetHistory()
await headlessInstall(await testDefaults({
lockfileDir: prefix,
reporter,
}))
// On repeat install no new packages should be added
// covers path_to_url
expect(reporter.calledWithMatch({
added: 0,
level: 'debug',
name: 'pnpm:stats',
prefix,
} as StatsLog)).toBeTruthy()
})
test('installing only prod deps', async () => {
const prefix = f.prepare('simple')
await headlessInstall(await testDefaults({
include: {
dependencies: true,
devDependencies: false,
optionalDependencies: false,
},
lockfileDir: prefix,
}))
const project = assertProject(prefix)
project.has('is-positive')
project.has('rimraf')
project.hasNot('is-negative')
project.hasNot('colors')
project.isExecutable('.bin/rimraf')
})
test('installing only dev deps', async () => {
const prefix = f.prepare('simple')
await headlessInstall(await testDefaults({
include: {
dependencies: false,
devDependencies: true,
optionalDependencies: false,
},
lockfileDir: prefix,
}))
const project = assertProject(prefix)
project.hasNot('is-positive')
project.hasNot('rimraf')
project.has('is-negative')
project.hasNot('colors')
})
test('installing with package manifest ignored', async () => {
const prefix = f.prepare('ignore-package-manifest')
const opt = await testDefaults({
projects: [],
include: {
dependencies: true,
devDependencies: true,
optionalDependencies: true,
},
lockfileDir: prefix,
})
await headlessInstall({ ...opt, ignorePackageManifest: true })
const project = assertProject(prefix)
const currentLockfile = project.readCurrentLockfile()
expect(currentLockfile.packages).toHaveProperty(['is-positive@1.0.0'])
expect(currentLockfile.packages).toHaveProperty(['is-negative@2.1.0'])
project.storeHas('is-negative')
project.storeHas('is-positive')
project.hasNot('is-negative')
project.hasNot('is-positive')
})
test('installing only prod package with package manifest ignored', async () => {
const prefix = f.prepare('ignore-package-manifest')
const opt = await testDefaults({
projects: [],
include: {
dependencies: true,
devDependencies: false,
optionalDependencies: true,
},
lockfileDir: prefix,
})
await headlessInstall({ ...opt, ignorePackageManifest: true })
const project = assertProject(prefix)
const currentLockfile = project.readCurrentLockfile()
expect(currentLockfile.packages).not.toHaveProperty(['is-negative@2.1.0'])
expect(currentLockfile.packages).toHaveProperty(['is-positive@1.0.0'])
project.storeHasNot('is-negative')
project.storeHas('is-positive')
project.hasNot('is-negative')
project.hasNot('is-positive')
})
test('installing only dev package with package manifest ignored', async () => {
const prefix = f.prepare('ignore-package-manifest')
const opt = await testDefaults({
projects: [],
include: {
dependencies: false,
devDependencies: true,
optionalDependencies: false,
},
lockfileDir: prefix,
})
await headlessInstall({ ...opt, ignorePackageManifest: true })
const project = assertProject(prefix)
const currentLockfile = project.readCurrentLockfile()
expect(currentLockfile.packages).toHaveProperty(['is-negative@2.1.0'])
expect(currentLockfile.packages).not.toHaveProperty(['is-positive@1.0.0'])
project.storeHasNot('is-negative')
project.storeHas('is-positive')
project.hasNot('is-negative')
project.hasNot('is-positive')
})
test('installing non-prod deps then all deps', async () => {
const prefix = f.prepare('prod-dep-is-dev-subdep')
await headlessInstall(await testDefaults({
include: {
dependencies: false,
devDependencies: true,
optionalDependencies: true,
},
lockfileDir: prefix,
}))
const project = assertProject(prefix)
const inflight = project.requireModule('inflight')
expect(typeof inflight).toBe('function')
project.hasNot('once')
{
const currentLockfile = project.readCurrentLockfile()
expect(currentLockfile.packages).not.toHaveProperty(['is-positive@1.0.0'])
}
const reporter = sinon.spy()
// Repeat normal installation adds missing deps to node_modules
await headlessInstall(await testDefaults({
include: {
dependencies: true,
devDependencies: true,
optionalDependencies: true,
},
lockfileDir: prefix,
reporter,
}))
expect(reporter.calledWithMatch({
added: {
dependencyType: 'prod',
name: 'once',
realName: 'once',
},
level: 'debug',
name: 'pnpm:root',
} as RootLog)).toBeTruthy()
expect(reporter.calledWithMatch({
added: {
dependencyType: 'dev',
name: 'inflight',
realName: 'inflight',
},
level: 'debug',
name: 'pnpm:root',
} as RootLog)).toBeFalsy()
project.has('once')
{
const currentLockfile = project.readCurrentLockfile()
expect(currentLockfile.packages).toHaveProperty(['is-positive@1.0.0'])
}
})
test('installing only optional deps', async () => {
const prefix = f.prepare('simple')
await headlessInstall(await testDefaults({
development: false,
include: {
dependencies: false,
devDependencies: false,
optionalDependencies: true,
},
lockfileDir: prefix,
optional: true,
production: false,
}))
const project = assertProject(prefix)
project.hasNot('is-positive')
project.hasNot('rimraf')
project.hasNot('is-negative')
project.has('colors')
})
// Covers path_to_url
test('not installing optional deps', async () => {
const prefix = f.prepare('simple-with-optional-dep')
await headlessInstall(await testDefaults({
include: {
dependencies: true,
devDependencies: true,
optionalDependencies: false,
},
lockfileDir: prefix,
}))
const project = assertProject(prefix)
project.hasNot('is-positive')
project.has('@pnpm.e2e/pkg-with-good-optional')
})
test('skipping optional dependency if it cannot be fetched', async () => {
const prefix = f.prepare('has-nonexistent-optional-dep')
const reporter = sinon.spy()
await headlessInstall(await testDefaults({
lockfileDir: prefix,
reporter,
}, {
retry: {
retries: 0,
},
}))
const project = assertProject(prefix)
expect(project.requireModule('is-positive')).toBeTruthy()
expect(project.requireModule('rimraf')).toBeTruthy()
expect(project.requireModule('is-negative')).toBeTruthy()
expect(project.readCurrentLockfile()).toBeTruthy()
expect(project.readModulesManifest()).toBeTruthy()
})
test('run pre/postinstall scripts', async () => {
let prefix = f.prepare('deps-have-lifecycle-scripts')
await using server = await createTestIpcServer(path.join(prefix, 'test.sock'))
await headlessInstall(await testDefaults({ lockfileDir: prefix }))
const project = assertProject(prefix)
const generatedByPreinstall = project.requireModule('@pnpm.e2e/pre-and-postinstall-scripts-example/generated-by-preinstall')
expect(typeof generatedByPreinstall).toBe('function')
const generatedByPostinstall = project.requireModule('@pnpm.e2e/pre-and-postinstall-scripts-example/generated-by-postinstall')
expect(typeof generatedByPostinstall).toBe('function')
expect(server.getLines()).toStrictEqual(['install', 'postinstall'])
prefix = f.prepare('deps-have-lifecycle-scripts')
server.clear()
await headlessInstall(await testDefaults({ lockfileDir: prefix, ignoreScripts: true }))
expect(server.getLines()).toStrictEqual([])
const nmPath = path.join(prefix, 'node_modules')
const modulesYaml = await readModulesManifest(nmPath)
expect(modulesYaml).toBeTruthy()
expect(modulesYaml!.pendingBuilds).toStrictEqual(['.', '@pnpm.e2e/pre-and-postinstall-scripts-example@2.0.0'])
})
test('orphan packages are removed', async () => {
const projectDir = f.prepare('simple-with-more-deps')
await headlessInstall(await testDefaults({
lockfileDir: projectDir,
}))
const simpleDir = f.find('simple')
fs.copyFileSync(
path.join(simpleDir, 'package.json'),
path.join(projectDir, 'package.json')
)
fs.copyFileSync(
path.join(simpleDir, WANTED_LOCKFILE),
path.join(projectDir, WANTED_LOCKFILE)
)
const reporter = sinon.spy()
await headlessInstall(await testDefaults({
lockfileDir: projectDir,
reporter,
}))
expect(reporter.calledWithMatch({
level: 'debug',
name: 'pnpm:stats',
prefix: projectDir,
removed: 1,
} as StatsLog)).toBeTruthy()
const project = assertProject(projectDir)
project.hasNot('resolve-from')
project.has('rimraf')
project.has('is-negative')
project.has('colors')
})
test('available packages are used when node_modules is not clean', async () => {
const projectDir = tempDir()
const destPackageJsonPath = path.join(projectDir, 'package.json')
const destLockfileYamlPath = path.join(projectDir, WANTED_LOCKFILE)
const hasGlobDir = f.find('has-glob')
fs.copyFileSync(path.join(hasGlobDir, 'package.json'), destPackageJsonPath)
fs.copyFileSync(path.join(hasGlobDir, WANTED_LOCKFILE), destLockfileYamlPath)
await headlessInstall(await testDefaults({ lockfileDir: projectDir }))
const hasGlobAndRimrafDir = f.find('has-glob-and-rimraf')
fs.copyFileSync(path.join(hasGlobAndRimrafDir, 'package.json'), destPackageJsonPath)
fs.copyFileSync(path.join(hasGlobAndRimrafDir, WANTED_LOCKFILE), destLockfileYamlPath)
const reporter = sinon.spy()
await headlessInstall(await testDefaults({ lockfileDir: projectDir, reporter }))
const project = assertProject(projectDir)
project.has('rimraf')
project.has('glob')
expect(reporter.calledWithMatch({
level: 'debug',
packageId: 'balanced-match@1.0.2',
requester: projectDir,
status: 'resolved',
})).toBeFalsy()
expect(reporter.calledWithMatch({
level: 'debug',
packageId: 'rimraf@2.7.1',
requester: projectDir,
status: 'resolved',
})).toBeTruthy()
})
test('available packages are relinked during forced install', async () => {
const projectDir = tempDir()
const destPackageJsonPath = path.join(projectDir, 'package.json')
const destLockfileYamlPath = path.join(projectDir, WANTED_LOCKFILE)
const hasGlobDir = f.find('has-glob')
fs.copyFileSync(path.join(hasGlobDir, 'package.json'), destPackageJsonPath)
fs.copyFileSync(path.join(hasGlobDir, WANTED_LOCKFILE), destLockfileYamlPath)
await headlessInstall(await testDefaults({ lockfileDir: projectDir }))
const hasGlobAndRimrafDir = f.find('has-glob-and-rimraf')
fs.copyFileSync(path.join(hasGlobAndRimrafDir, 'package.json'), destPackageJsonPath)
fs.copyFileSync(path.join(hasGlobAndRimrafDir, WANTED_LOCKFILE), destLockfileYamlPath)
const reporter = sinon.spy()
await headlessInstall(await testDefaults({ lockfileDir: projectDir, reporter, force: true }))
const project = assertProject(projectDir)
project.has('rimraf')
project.has('glob')
expect(reporter.calledWithMatch({
level: 'debug',
packageId: 'balanced-match@1.0.2',
requester: projectDir,
status: 'resolved',
})).toBeTruthy()
expect(reporter.calledWithMatch({
level: 'debug',
packageId: 'rimraf@2.7.1',
requester: projectDir,
status: 'resolved',
})).toBeTruthy()
})
test('installing local dependency', async () => {
let prefix = f.prepare('has-local-dep')
prefix = path.join(prefix, 'pkg')
const reporter = sinon.spy()
await headlessInstall(await testDefaults({ lockfileDir: prefix, reporter }))
const project = assertProject(prefix)
expect(project.requireModule('tar-pkg'))
})
test('installing local directory dependency', async () => {
const prefix = f.prepare('has-local-dir-dep')
const reporter = sinon.spy()
await headlessInstall(await testDefaults({ lockfileDir: prefix, reporter }))
const project = assertProject(prefix)
expect(project.requireModule('example/package.json')).toBeTruthy()
})
test('installing using passed in lockfile files', async () => {
const prefix = tempDir()
const simplePkgPath = f.find('simple')
fs.copyFileSync(path.join(simplePkgPath, 'package.json'), path.join(prefix, 'package.json'))
fs.copyFileSync(path.join(simplePkgPath, WANTED_LOCKFILE), path.join(prefix, WANTED_LOCKFILE))
const wantedLockfile = await readWantedLockfile(simplePkgPath, { ignoreIncompatible: false })
await headlessInstall(await testDefaults({
lockfileDir: prefix,
wantedLockfile,
}))
const project = assertProject(prefix)
expect(project.requireModule('is-positive')).toBeTruthy()
expect(project.requireModule('rimraf')).toBeTruthy()
expect(project.requireModule('is-negative')).toBeTruthy()
expect(project.requireModule('colors')).toBeTruthy()
})
test('installation of a dependency that has a resolved peer in subdeps', async () => {
const prefix = f.prepare('resolved-peer-deps-in-subdeps')
await headlessInstall(await testDefaults({ lockfileDir: prefix }))
const project = assertProject(prefix)
expect(project.requireModule('pnpm-default-reporter')).toBeTruthy()
})
test('install peer dependencies that are in prod dependencies', async () => {
const prefix = f.prepare('reinstall-peer-deps')
await headlessInstall(await testDefaults({ lockfileDir: prefix }))
const project = assertProject(prefix)
project.has('.pnpm/@pnpm.e2e+peer-a@1.0.1/node_modules/@pnpm.e2e/peer-a')
})
test('installing with hoistPattern=*', async () => {
const prefix = f.prepare('simple-shamefully-flatten')
const reporter = jest.fn()
await headlessInstall(await testDefaults({ lockfileDir: prefix, reporter, hoistPattern: '*' }))
const project = assertProject(prefix)
expect(project.requireModule('is-positive')).toBeTruthy()
expect(project.requireModule('rimraf')).toBeTruthy()
expect(project.requireModule('.pnpm/node_modules/glob')).toBeTruthy()
expect(project.requireModule('is-negative')).toBeTruthy()
expect(project.requireModule('colors')).toBeTruthy()
project.has('.pnpm/colors@1.2.0')
project.isExecutable('.bin/rimraf')
project.isExecutable('.pnpm/node_modules/.bin/hello-world-js-bin')
expect(project.readCurrentLockfile()).toBeTruthy()
expect(project.readModulesManifest()).toBeTruthy()
expect(reporter).toHaveBeenCalledWith(expect.objectContaining({
level: 'debug',
name: 'pnpm:package-manifest',
updated: expect.objectContaining({
name: 'simple-shamefully-flatten',
version: '1.0.0',
}),
} as PackageManifestLog))
expect(reporter).toHaveBeenCalledWith(expect.objectContaining({
added: 17,
level: 'debug',
name: 'pnpm:stats',
prefix,
} as StatsLog))
expect(reporter).toHaveBeenCalledWith(expect.objectContaining({
level: 'debug',
name: 'pnpm:stats',
prefix,
removed: 0,
} as StatsLog))
expect(reporter).toHaveBeenCalledWith(expect.objectContaining({
level: 'debug',
name: 'pnpm:stage',
prefix,
stage: 'importing_done',
} as StageLog))
expect(reporter).toHaveBeenCalledWith(expect.objectContaining({
level: 'debug',
packageId: 'is-negative@2.1.0',
requester: prefix,
status: 'resolved',
}))
const modules = project.readModulesManifest()
expect(modules!.hoistedDependencies['balanced-match@1.0.2' as DepPath]).toStrictEqual({ 'balanced-match': 'private' })
})
test('installing with publicHoistPattern=*', async () => {
const prefix = f.prepare('simple-shamefully-flatten')
const reporter = sinon.spy()
await headlessInstall(await testDefaults({ lockfileDir: prefix, reporter, publicHoistPattern: '*' }))
const project = assertProject(prefix)
expect(project.requireModule('is-positive')).toBeTruthy()
expect(project.requireModule('rimraf')).toBeTruthy()
expect(project.requireModule('glob')).toBeTruthy()
expect(project.requireModule('is-negative')).toBeTruthy()
expect(project.requireModule('colors')).toBeTruthy()
project.has('.pnpm/colors@1.2.0')
project.isExecutable('.bin/rimraf')
project.isExecutable('.bin/hello-world-js-bin')
expect(project.readCurrentLockfile()).toBeTruthy()
expect(project.readModulesManifest()).toBeTruthy()
expect(reporter.calledWithMatch({
level: 'debug',
name: 'pnpm:package-manifest',
updated: loadJsonFile.sync(path.join(prefix, 'package.json')),
} as PackageManifestLog)).toBeTruthy()
expect(reporter.calledWithMatch({
added: 17,
level: 'debug',
name: 'pnpm:stats',
prefix,
} as StatsLog)).toBeTruthy()
expect(reporter.calledWithMatch({
level: 'debug',
name: 'pnpm:stats',
prefix,
removed: 0,
} as StatsLog)).toBeTruthy()
expect(reporter.calledWithMatch({
level: 'debug',
name: 'pnpm:stage',
prefix,
stage: 'importing_done',
} as StageLog)).toBeTruthy()
expect(reporter.calledWithMatch({
level: 'debug',
packageId: 'is-negative@2.1.0',
requester: prefix,
status: 'resolved',
})).toBeTruthy()
const modules = project.readModulesManifest()
expect(modules!.hoistedDependencies['balanced-match@1.0.2' as DepPath]).toStrictEqual({ 'balanced-match': 'public' })
})
test('installing with publicHoistPattern=* in a project with external lockfile', async () => {
const lockfileDir = f.prepare('pkg-with-external-lockfile')
const prefix = path.join(lockfileDir, 'pkg')
await headlessInstall(await testDefaults({
lockfileDir,
projects: [prefix],
publicHoistPattern: '*',
}))
const project = assertProject(lockfileDir)
expect(project.requireModule('accepts')).toBeTruthy()
})
const ENGINE_DIR = `${process.platform}-${process.arch}-node-${process.version.split('.')[0]}`
test.each([['isolated'], ['hoisted']])('using side effects cache with nodeLinker=%s', async (nodeLinker) => {
let prefix = f.prepare('side-effects')
// Right now, hardlink does not work with side effects, so we specify copy as the packageImportMethod
// We disable verifyStoreIntegrity because we are going to change the cache
const opts = await testDefaults({
lockfileDir: prefix,
nodeLinker,
sideEffectsCacheRead: true,
sideEffectsCacheWrite: true,
verifyStoreIntegrity: false,
}, {}, {}, { packageImportMethod: 'copy' })
await headlessInstall(opts)
const cafsDir = path.join(opts.storeDir, 'files')
const cacheIntegrityPath = getFilePathInCafs(cafsDir, getIntegrity('@pnpm.e2e/pre-and-postinstall-scripts-example', '1.0.0'), 'index')
const cacheIntegrity = loadJsonFile.sync<any>(cacheIntegrityPath) // eslint-disable-line @typescript-eslint/no-explicit-any
expect(cacheIntegrity!.sideEffects).toBeTruthy()
const sideEffectsKey = `${ENGINE_NAME}-${hashObject({ '@pnpm.e2e/hello-world-js-bin@1.0.0': {} })}`
expect(cacheIntegrity).toHaveProperty(['sideEffects', sideEffectsKey, 'generated-by-postinstall.js'])
delete cacheIntegrity!.sideEffects[sideEffectsKey]['generated-by-postinstall.js']
expect(cacheIntegrity).toHaveProperty(['sideEffects', sideEffectsKey, 'generated-by-preinstall.js'])
writeJsonFile.sync(cacheIntegrityPath, cacheIntegrity)
prefix = f.prepare('side-effects')
const opts2 = await testDefaults({
lockfileDir: prefix,
nodeLinker,
sideEffectsCacheRead: true,
sideEffectsCacheWrite: true,
storeDir: opts.storeDir,
verifyStoreIntegrity: false,
}, {}, {}, { packageImportMethod: 'copy' })
await headlessInstall(opts2)
expect(fs.existsSync(path.join(prefix, 'node_modules/@pnpm.e2e/pre-and-postinstall-scripts-example/generated-by-postinstall.js'))).toBeFalsy()
expect(fs.existsSync(path.join(prefix, 'node_modules/@pnpm.e2e/pre-and-postinstall-scripts-example/generated-by-preinstall.js'))).toBeTruthy()
})
test.skip('using side effects cache and hoistPattern=*', async () => {
const lockfileDir = f.prepare('side-effects-of-subdep')
// Right now, hardlink does not work with side effects, so we specify copy as the packageImportMethod
// We disable verifyStoreIntegrity because we are going to change the cache
const opts = await testDefaults({
hoistPattern: '*',
lockfileDir,
sideEffectsCacheRead: true,
sideEffectsCacheWrite: true,
verifyStoreIntegrity: false,
}, {}, {}, { packageImportMethod: 'copy' })
await headlessInstall(opts)
const project = assertProject(lockfileDir)
project.has('.pnpm/node_modules/es6-promise') // verifying that a flat node_modules was created
const cacheBuildDir = path.join(opts.storeDir, `diskusage@1.1.3/side_effects/${ENGINE_DIR}/package/build`)
fs.writeFileSync(path.join(cacheBuildDir, 'new-file.txt'), 'some new content')
rimraf(path.join(lockfileDir, 'node_modules'))
await headlessInstall(opts)
expect(fs.existsSync(path.join(lockfileDir, 'node_modules/.pnpm/node_modules/diskusage/build/new-file.txt'))).toBeTruthy()
project.has('.pnpm/node_modules/es6-promise') // verifying that a flat node_modules was created
})
test('installing in a workspace', async () => {
const workspaceFixture = f.prepare('workspace')
const projects = [
path.join(workspaceFixture, 'foo'),
path.join(workspaceFixture, 'bar'),
]
await headlessInstall(await testDefaults({
lockfileDir: workspaceFixture,
projects,
}))
const projectBar = assertProject(path.join(workspaceFixture, 'bar'))
projectBar.has('foo')
await headlessInstall(await testDefaults({
lockfileDir: workspaceFixture,
projects: [projects[0]],
}))
const rootModules = assertProject(workspaceFixture)
const lockfile = rootModules.readCurrentLockfile()
expect(Object.keys(lockfile.packages)).toStrictEqual([
'is-negative@1.0.0',
'is-positive@1.0.0',
])
})
test('installing with no symlinks but with PnP', async () => {
const prefix = f.prepare('simple')
await headlessInstall(await testDefaults({
enablePnp: true,
lockfileDir: prefix,
symlink: false,
}))
expect([...fs.readdirSync(path.join(prefix, 'node_modules'))]).toStrictEqual(['.bin', '.modules.yaml', '.pnpm'])
expect([...fs.readdirSync(path.join(prefix, 'node_modules/.pnpm/rimraf@2.7.1/node_modules'))]).toStrictEqual(['rimraf'])
const project = assertProject(prefix)
expect(project.readCurrentLockfile()).toBeTruthy()
expect(project.readModulesManifest()).toBeTruthy()
expect(fs.existsSync(path.join(prefix, '.pnp.cjs'))).toBeTruthy()
})
test('installing with no modules directory', async () => {
const prefix = f.prepare('simple')
await headlessInstall(await testDefaults({
enableModulesDir: false,
lockfileDir: prefix,
}))
expect(fs.existsSync(path.join(prefix, 'node_modules'))).toBeFalsy()
})
test('installing with node-linker=hoisted', async () => {
const prefix = f.prepare('has-several-versions-of-same-pkg')
await headlessInstall(await testDefaults({
enableModulesDir: false,
lockfileDir: prefix,
nodeLinker: 'hoisted',
}))
expect(fs.realpathSync('node_modules/ms')).toBe(path.resolve('node_modules/ms'))
expect(fs.realpathSync('node_modules/send')).toBe(path.resolve('node_modules/send'))
expect(fs.existsSync('node_modules/send/node_modules/ms')).toBeTruthy()
})
test('installing in a workspace with node-linker=hoisted', async () => {
const prefix = f.prepare('workspace2')
await headlessInstall(await testDefaults({
lockfileDir: prefix,
nodeLinker: 'hoisted',
projects: [
path.join(prefix, 'foo'),
path.join(prefix, 'bar'),
],
}))
expect(fs.realpathSync('bar/node_modules/foo')).toBe(path.resolve('foo'))
expect(readPkgVersion(path.join(prefix, 'foo/node_modules/webpack'))).toBe('2.7.0')
expect(fs.realpathSync('foo/node_modules/express')).toBe(path.resolve('foo/node_modules/express'))
expect(readPkgVersion(path.join(prefix, 'foo/node_modules/express'))).toBe('4.17.2')
expect(readPkgVersion(path.join(prefix, 'node_modules/webpack'))).toBe('5.65.0')
expect(readPkgVersion(path.join(prefix, 'node_modules/express'))).toBe('2.5.11')
})
function readPkgVersion (dir: string): string {
return loadJsonFile.sync<{ version: string }>(path.join(dir, 'package.json')).version
}
test('installing a package deeply installs all required dependencies', async () => {
const workspaceFixture = f.prepare('workspace-external-depends-deep')
const projects = [
path.join(workspaceFixture),
path.join(workspaceFixture, 'packages/f'),
path.join(workspaceFixture, 'packages/g'),
workspaceFixture,
]
await headlessInstall(
await testDefaults({
lockfileDir: workspaceFixture,
projects,
selectedProjectDirs: [projects[2]],
})
)
for (const projectDir of projects) {
if (projectDir === workspaceFixture) {
continue
}
const projectAssertion = assertProject(projectDir)
expect(projectAssertion.requireModule('is-positive')).toBeTruthy()
}
})
``` | /content/code_sandbox/pkg-manager/headless/test/index.ts | xml | 2016-01-28T07:40:43 | 2024-08-16T12:38:47 | pnpm | pnpm/pnpm | 28,869 | 6,660 |
```xml
import { Plugin, Menu, Buffer } from "oni-api"
import { readdir, stat, pathExists } from "fs-extra"
import { homedir } from "os"
import { Event, IEvent } from "oni-types"
import * as path from "path"
import { IAsyncSearch, QuickOpenResult } from "./QuickOpen"
import { QuickOpenItem, QuickOpenType } from "./QuickOpenItem"
export interface IBookmarkItem {
fullPath: string
type: string
}
export default class BookmarkSearch implements IAsyncSearch {
private _onSearchResults = new Event<QuickOpenResult>()
private _bookmarkItems: QuickOpenItem[]
constructor(private _oni: Plugin.Api) {
const bookmarks = this._oni.configuration.getValue<string[]>("oni.bookmarks", [])
// TODO: Consider adding folders as well (recursive async with ignores/excludes)
this._bookmarkItems = [
new QuickOpenItem("Open Folder", "", QuickOpenType.folderHelp),
...bookmarks.map(
folder => new QuickOpenItem(folder, "", QuickOpenType.bookmark, folder),
),
new QuickOpenItem(
"Open configuration",
"For adding a bookmark",
QuickOpenType.bookmarkHelp,
),
]
}
private _getBookmarkPath = (bookmark: string) => {
if (path.isAbsolute(bookmark)) {
return bookmark
}
const userBaseDir = this._oni.configuration.getValue<string>("oni.bookmarks.baseDirectory")
const baseDir = userBaseDir || homedir()
return path.join(baseDir, bookmark)
}
public handleBookmark = async ({ metadata }: Menu.MenuOption) => {
const bookmarkPath = this._getBookmarkPath(metadata.path)
await this._handleItem(bookmarkPath)
}
// deliberately throw errors as a means of clarifying if a path exists
// i.e. if isDir => true, else => false, if does not exist => new Error(err)
public isDir = async (path: string) => {
const stats = await stat(path)
return stats.isDirectory()
}
private _handleItem = async (bookmarkPath: string) => {
try {
const isDirectory = await this.isDir(bookmarkPath)
return isDirectory
? this._oni.workspace.changeDirectory(bookmarkPath)
: this._oni.editors.openFile(bookmarkPath)
} catch (error) {
this._oni.log.warn(
`[Oni Bookmarks Menu Error]: The Bookmark path ${bookmarkPath} does not exist: \n ${
error.message
}`,
)
}
}
public cancel(): void {}
public changeQueryText(newText) {
this._onSearchResults.dispatch({
items: this._bookmarkItems,
isComplete: true,
})
}
public get onSearchResults(): IEvent<QuickOpenResult> {
return this._onSearchResults
}
}
``` | /content/code_sandbox/extensions/oni-plugin-quickopen/src/BookmarksSearch.ts | xml | 2016-11-16T14:42:55 | 2024-08-14T11:48:05 | oni | onivim/oni | 11,355 | 623 |
```xml
import { getSingleParam, isEmpty } from './utils';
const lengthValidator = (value: unknown, params: [number | string] | { length: string | number }) => {
if (isEmpty(value)) {
return true;
}
// Normalize the length value
const length = getSingleParam(params, 'length');
if (typeof value === 'number') {
value = String(value);
}
if (!(value as ArrayLike<unknown>).length) {
value = Array.from(value as ArrayLike<unknown>);
}
return (value as ArrayLike<unknown>).length === Number(length);
};
export default lengthValidator;
``` | /content/code_sandbox/packages/rules/src/length.ts | xml | 2016-07-30T01:10:44 | 2024-08-16T10:19:58 | vee-validate | logaretm/vee-validate | 10,699 | 137 |
```xml
import { PLANS } from '@proton/shared/lib/constants';
import { isTrial } from '@proton/shared/lib/helpers/subscription';
import type { Subscription } from '@proton/shared/lib/interfaces';
interface Props {
subscription?: Subscription;
}
const isEligible = ({ subscription }: Props) => {
return isTrial(subscription, PLANS.MAIL);
};
export default isEligible;
``` | /content/code_sandbox/packages/components/containers/offers/operations/mailTrial2023/eligibility.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 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>#DisableDrivers</key>
<array>
<string>CsmVideoDxe</string>
<string>VBoxExt4</string>
</array>
<key>ACPI</key>
<dict>
<key>#DropMCFG</key>
<false/>
<key>#PatchAPIC</key>
<false/>
<key>#ResetAddress</key>
<string>0x64</string>
<key>#ResetValue</key>
<string>0xFE</string>
<key>#SortedOrder</key>
<array>
<string>SSDT-3.aml</string>
<string>SSDT-1.aml</string>
<string>SSDT-2.aml</string>
</array>
<key>#smartUPS</key>
<false/>
<key>DSDT</key>
<dict>
<key>#DropOEM_DSM</key>
<dict>
<key>ATI</key>
<true/>
<key>Firewire</key>
<true/>
<key>HDA</key>
<true/>
<key>HDMI</key>
<true/>
<key>IDE</key>
<true/>
<key>IntelGFX</key>
<true/>
<key>LAN</key>
<true/>
<key>LPC</key>
<false/>
<key>NVidia</key>
<true/>
<key>SATA</key>
<true/>
<key>SmBUS</key>
<false/>
<key>USB</key>
<true/>
<key>WIFI</key>
<true/>
</dict>
<key>#Patches</key>
<array>
<dict>
<key>Comment</key>
<string>Remove battery device from desktop</string>
<key>Find</key>
<data>W4IeQkFUMQhfSElEDEHQDAoIX1VJRAEUCF9TVEEApAA=</data>
<key>Replace</key>
<data></data>
</dict>
<dict>
<key>Comment</key>
<string>Add _SUN property for GIGE</string>
<key>Find</key>
<data>UFhTWAhfQURSAAhfUFJXEgYC</data>
<key>Replace</key>
<data>UFhTWAhfQURSAAhfU1VOCgQIX1BSVxIGAg==</data>
</dict>
<dict>
<key>Comment</key>
<string>Rename GFX0 to IGPU</string>
<key>Find</key>
<data>R0ZYMA==</data>
<key>Replace</key>
<data>SUdQVQ==</data>
</dict>
<dict>
<key>Comment</key>
<string>Rename HDEF to AZAL</string>
<key>Find</key>
<data>SERFRg==</data>
<key>Replace</key>
<data>QVpBTA==</data>
</dict>
</array>
<key>#Rtc8Allowed</key>
<false/>
<key>#SuspendOverride</key>
<false/>
<key>Debug</key>
<false/>
<key>Fixes</key>
<dict>
<key>AddDTGP_0001</key>
<true/>
<key>AddHDMI_8000000</key>
<true/>
<key>AddIMEI_80000</key>
<false/>
<key>AddMCHC_0008</key>
<false/>
<key>AddPNLF_1000000</key>
<true/>
<key>DeleteUnused_400000</key>
<true/>
<key>FIX_ACST_4000000</key>
<true/>
<key>FIX_ADP1_800000</key>
<true/>
<key>FIX_INTELGFX_100000</key>
<false/>
<key>FIX_RTC_20000</key>
<true/>
<key>FIX_S3D_2000000</key>
<true/>
<key>FIX_TMR_40000</key>
<true/>
<key>FIX_WAK_200000</key>
<true/>
<key>FakeLPC_0020</key>
<false/>
<key>FixAirport_4000</key>
<false/>
<key>FixDarwin_0002</key>
<false/>
<key>FixDarwin7_10000</key>
<true/>
<key>FixDisplay_0100</key>
<true/>
<key>FixFirewire_0800</key>
<false/>
<key>FixHDA_8000</key>
<true/>
<key>FixHPET_0010</key>
<true/>
<key>FixHeaders_20000000</key>
<true/>
<key>FixIDE_0200</key>
<false/>
<key>FixIPIC_0040</key>
<true/>
<key>FixLAN_2000</key>
<true/>
<key>FixRegions_10000000</key>
<true/>
<key>FixSATA_0400</key>
<false/>
<key>FixSBUS_0080</key>
<true/>
<key>FixShutdown_0004</key>
<true/>
<key>FixUSB_1000</key>
<true/>
</dict>
<key>Name</key>
<string>DSDT.aml</string>
<key>ReuseFFFF</key>
<false/>
</dict>
<key>DisableASPM</key>
<false/>
<key>DropTables</key>
<array>
<dict>
<key>Signature</key>
<string>DMAR</string>
</dict>
<dict>
<key>Signature</key>
<string>SSDT</string>
<key>TableId</key>
<string>CpuPm</string>
</dict>
<dict>
<key>#Length</key>
<integer>720</integer>
<key>Signature</key>
<string>SSDT</string>
<key>TableId</key>
<string>Cpu0Ist</string>
</dict>
</array>
<key>HaltEnabler</key>
<true/>
<key>SSDT</key>
<dict>
<key>#C3Latency</key>
<string>0x03E7</string>
<key>#DoubleFirstState</key>
<true/>
<key>#DropOem</key>
<true/>
<key>#EnableC2</key>
<false/>
<key>#EnableC4</key>
<false/>
<key>#EnableC6</key>
<true/>
<key>#EnableC7</key>
<false/>
<key>#MaxMultiplier</key>
<integer>12</integer>
<key>#MinMultiplier</key>
<integer>8</integer>
<key>#PLimitDict</key>
<integer>1</integer>
<key>#PluginType</key>
<integer>0</integer>
<key>#UnderVoltStep</key>
<integer>1</integer>
<key>#UseSystemIO</key>
<false/>
<key>Generate</key>
<dict>
<key>CStates</key>
<true/>
<key>PStates</key>
<true/>
</dict>
</dict>
</dict>
<key>Boot</key>
<dict>
<key>##Arguments</key>
<string>kext-dev-mode=1 rootless=0</string>
<key>#Arguments</key>
<string>-v arch=x86_64 slide=0 darkwake=0</string>
<key>#LegacyBiosDefaultEntry</key>
<integer>0</integer>
<key>#XMPDetection</key>
<string>-1</string>
<key>Debug</key>
<false/>
<key>DefaultLoader</key>
<string>boot.efi</string>
<key>DefaultVolume</key>
<string>LastBootedVolume</string>
<key>DisableCloverHotkeys</key>
<false/>
<key>Fast</key>
<false/>
<key>Legacy</key>
<string>PBR</string>
<key>NeverDoRecovery</key>
<true/>
<key>NeverHibernate</key>
<false/>
<key>SkipHibernateTimeout</key>
<false/>
<key>StrictHibernate</key>
<false/>
<key>Timeout</key>
<integer>5</integer>
</dict>
<key>BootGraphics</key>
<dict>
<key>#DefaultBackgroundColor</key>
<string>0xF0F0F0</string>
<key>EFILoginHiDPI</key>
<integer>1</integer>
<key>UIScale</key>
<integer>1</integer>
</dict>
<key>CPU</key>
<dict>
<key>#BusSpeedkHz</key>
<integer>133330</integer>
<key>#FrequencyMHz</key>
<integer>3140</integer>
<key>#HWPEnable</key>
<true/>
<key>#HWPValue</key>
<string>0x30002a01</string>
<key>#QPI</key>
<integer>4800</integer>
<key>#SavingMode</key>
<integer>7</integer>
<key>#TDP</key>
<integer>95</integer>
<key>#TurboDisable</key>
<true/>
<key>#Type</key>
<string>0x0201</string>
<key>#UseARTFrequency</key>
<true/>
</dict>
<key>Devices</key>
<dict>
<key>#AddProperties</key>
<array>
<dict>
<key>Device</key>
<string>NVidia</string>
<key>Key</key>
<string>AAPL,HasPanel</string>
<key>Value</key>
<data>AQAAAA==</data>
</dict>
<dict>
<key>Device</key>
<string>NVidia</string>
<key>Key</key>
<string>AAPL,Haslid</string>
<key>Value</key>
<data>AQAAAA==</data>
</dict>
</array>
<key>#FakeID</key>
<dict>
<key>#ATI</key>
<string>0x67501002</string>
<key>#IMEI</key>
<string>0x1e208086</string>
<key>#IntelGFX</key>
<string>0x01268086</string>
<key>#LAN</key>
<string>0x100E8086</string>
<key>#NVidia</key>
<string>0x11de10de</string>
<key>#SATA</key>
<string>0x25628086</string>
<key>#WIFI</key>
<string>0x431214e4</string>
<key>#XHCI</key>
<string>0x0</string>
</dict>
<key>#ForceHPET</key>
<false/>
<key>#Inject</key>
<false/>
<key>#Properties</key>
<string>your_sha256_hashyour_sha256_hashyour_sha256_hash610079006f00750074002d00690064000000080000000c000000</string>
<key>#SetIntelBacklight</key>
<false/>
<key>#SetIntelMaxBacklight</key>
<true/>
<key>#IntelMaxValue</key>
<integer>1808</integer>
<key>Audio</key>
<dict>
<key>#Inject</key>
<string>0x0887</string>
<key>ResetHDA</key>
<true/>
</dict>
<key>NoDefaultProperties</key>
<false/>
<key>USB</key>
<dict>
<key>AddClockID</key>
<true/>
<key>FixOwnership</key>
<true/>
<key>HighCurrent</key>
<false/>
<key>Inject</key>
<true/>
</dict>
<key>UseIntelHDMI</key>
<false/>
</dict>
<key>GUI</key>
<dict>
<key>#ConsoleMode</key>
<string>0</string>
<key>#Custom</key>
<dict>
<key>Entries</key>
<array>
<dict>
<key>AddArguments</key>
<string>-v</string>
<key>Arguments</key>
<string>Kernel=mach_kernel</string>
<key>Disabled</key>
<true/>
<key>Hidden</key>
<false/>
<key>Hotkey</key>
<string>M</string>
<key>InjectKexts</key>
<false/>
<key>NoCaches</key>
<false/>
<key>Path</key>
<string>\EFI\BOOT\BOOTX64.efi</string>
<key>Title</key>
<string>MyCustomEntry</string>
<key>Type</key>
<string>OSXRecovery</string>
<key>Volume</key>
<string>D68F1885-571C-4441-8DD5-F14803EFEF54</string>
</dict>
<dict>
<key>Hidden</key>
<false/>
<key>InjectKexts</key>
<false/>
<key>NoCaches</key>
<false/>
<key>SubEntries</key>
<array>
<dict>
<key>AddArguments</key>
<string>-v</string>
<key>Title</key>
<string>Boot OS X 10.8.5 (12F36) Mountain Lion in Verbose Mode</string>
</dict>
</array>
<key>Title</key>
<string>OS X 10.8.5 (12F36) Mountain Lion</string>
<key>Type</key>
<string>OSX</string>
<key>Volume</key>
<string>454794AC-760D-46E8-8F77-D6EB23D2FD32</string>
</dict>
</array>
<key>Legacy</key>
<array>
<dict>
<key>Disabled</key>
<true/>
<key>Hidden</key>
<false/>
<key>Hotkey</key>
<string>L</string>
<key>Title</key>
<string>MyLegacyEntry</string>
<key>Type</key>
<string>Windows</string>
<key>Volume</key>
<string>89433CD3-21F2-4D3C-95FC-722C48066D3A</string>
</dict>
</array>
<key>Tool</key>
<array>
<dict>
<key>Arguments</key>
<string>-b</string>
<key>Disabled</key>
<false/>
<key>Hidden</key>
<false/>
<key>Hotkey</key>
<string>S</string>
<key>Path</key>
<string>\EFI\CLOVER\TOOLS\Shell64-v1.efi</string>
<key>Title</key>
<string>MyCustomShell</string>
<key>Volume</key>
<string>D68F1885-571C-4441-8DD5-F14803EFEF54</string>
</dict>
</array>
</dict>
<key>#CustomIcons</key>
<false/>
<key>#Hide</key>
<array>
<string>Windows</string>
<string>BOOTX64.EFI</string>
</array>
<key>#Language</key>
<string>ru:0</string>
<key>#Mouse</key>
<dict>
<key>Enabled</key>
<true/>
<key>Mirror</key>
<false/>
<key>Speed</key>
<integer>2</integer>
</dict>
<key>#Scan</key>
<dict>
<key>Entries</key>
<true/>
<key>Legacy</key>
<false/>
<key>Tool</key>
<true/>
</dict>
<key>#TextOnly</key>
<false/>
<key>ScreenResolution</key>
<string>1280x1024</string>
<key>Theme</key>
<string>metal</string>
</dict>
<key>Graphics</key>
<dict>
<key>#Connectors</key>
<array/>
<key>#DualLink</key>
<integer>0</integer>
<key>#FBName</key>
<string>Makakakakala</string>
<key>#Inject</key>
<dict>
<key>ATI</key>
<true/>
<key>Intel</key>
<false/>
<key>NVidia</key>
<false/>
</dict>
<key>#LoadVBios</key>
<false/>
<key>#NVCAP</key>
<string>04000000000003000C0000000000000A00000000</string>
<key>#NvidiaGeneric</key>
<true/>
<key>#NvidiaNoEFI</key>
<false/>
<key>#NvidiaSingle</key>
<false/>
<key>#PatchVBios</key>
<false/>
<key>#PatchVBiosBytes</key>
<array>
<dict>
<key>Find</key>
<data>gAeoAqAF</data>
<key>Replace</key>
<data>gAeoAjgE</data>
</dict>
</array>
<key>#VRAM</key>
<integer>1024</integer>
<key>#VideoPorts</key>
<integer>2</integer>
<key>#display-cfg</key>
<string>03010300FFFF0001</string>
<key>#ig-platform-id</key>
<string>0x01620005</string>
<key>EDID</key>
<dict>
<key>#Custom</key>
<data>AP///////your_sha256_hashiGgcFCEHzAgIFYAS88QAAAY3iGgcFCEHzAgIFYAS88QAAAAAAAA/gBXNjU3RwAxNTRXUDEKAAAA/gAjMz1IZYSq/wIBCiAgAJo=</data>
<key>#Inject</key>
<true/>
<key>#ProductID</key>
<string>0x9221</string>
<key>#VendorID</key>
<string>0x1006</string>
</dict>
</dict>
<key>KernelAndKextPatches</key>
<dict>
<key>#ATIConnectorsController</key>
<string>6000</string>
<key>#ATIConnectorsData</key>
<string>your_sha256_hash10000000100000000001000000000001</string>
<key>#ATIConnectorsPatch</key>
<string>your_sha256_hash00000000000000000000000000000000</string>
<key>#BootPatches</key>
<array>
<dict>
<key>Comment</key>
<string>Example</string>
<key>Disabled</key>
<true/>
<key>Find</key>
<data>RXh0ZXJuYWw=</data>
<key>MatchOS</key>
<string>All</string>
<key>Replace</key>
<data>SW50ZXJuYWw=</data>
</dict>
</array>
<key>#FakeCPUID</key>
<string>0x010676</string>
<key>#KextsToPatch</key>
<array>
<dict>
<key>Disabled</key>
<true/>
<key>Find</key>
<data>SGVhZHBob25lcwA=</data>
<key>Name</key>
<string>VoodooHDA</string>
<key>Replace</key>
<data>VGVsZXBob25lcwA=</data>
</dict>
<dict>
<key>Comment</key>
<string>Patch_to_not_load_this_driver</string>
<key>Find</key>
<string>0x04020000</string>
<key>InfoPlistPatch</key>
<true/>
<key>Name</key>
<string>AppleHDAController</string>
<key>Replace</key>
<string>0x44220000</string>
</dict>
<dict>
<key>Comment</key>
<string>Make all drives to be internal</string>
<key>Find</key>
<data>RXh0ZXJuYWw=</data>
<key>Name</key>
<string>AppleAHCIPort</string>
<key>Replace</key>
<data>SW50ZXJuYWw=</data>
</dict>
<dict>
<key>Comment</key>
<string>TRIM function for non-Apple SSDs</string>
<key>Find</key>
<data>QVBQTEUgU1NEAA==</data>
<key>Name</key>
<string>IOAHCIBlockStorage</string>
<key>Replace</key>
<data>AAAAAAAAAAAAAA==</data>
</dict>
<dict>
<key>Comment</key>
<string>ATI Connector patch new way</string>
<key>Disabled</key>
<false/>
<key>Find</key>
<data>your_sha256_hash</data>
<key>MatchOS</key>
<string>10.9,10.10,10.11</string>
<key>Name</key>
<string>AMD6000Controller</string>
<key>Replace</key>
<data>your_sha256_hash</data>
</dict>
</array>
<key>AppleIntelCPUPM</key>
<false/>
<key>AppleRTC</key>
<true/>
<key>AsusAICPUPM</key>
<false/>
<key>Debug</key>
<false/>
<key>DellSMBIOSPatch</key>
<false/>
<key>KernelCpu</key>
<false/>
<key>KernelIvyXCPM</key>
<false/>
<key>KernelLapic</key>
<false/>
<key>KernelPm</key>
<false/>
</dict>
<key>RtVariables</key>
<dict>
<key>BooterConfig</key>
<string>0x28</string>
<key>CsrActiveConfig</key>
<string>0x3E7</string>
<key>MLB</key>
<string>C02032109R5DC771H</string>
<key>ROM</key>
<string>UseMacAddr0</string>
</dict>
<key>SMBIOS</key>
<dict>
<key>#BiosReleaseDate</key>
<string>05/03/10</string>
<key>#BiosVendor</key>
<string>Apple Inc.</string>
<key>#BiosVersion</key>
<string>MB11.88Z.0061.B03.0809221748</string>
<key>#Board-ID</key>
<string>Mac-F4208CC8</string>
<key>#BoardManufacturer</key>
<string>Apple Inc.</string>
<key>#BoardSerialNumber</key>
<string>C02032101R5DC771H</string>
<key>#BoardType</key>
<integer>10</integer>
<key>#BoardVersion</key>
<string>Proto1</string>
<key>#ChassisAssetTag</key>
<string>LatitudeD420</string>
<key>#ChassisManufacturer</key>
<string>Apple Inc.</string>
<key>#ChassisType</key>
<integer>16</integer>
<key>#Family</key>
<string>MacBook</string>
<key>#FirmwareFeatures</key>
<string>0xC0001403</string>
<key>#FirmwareFeaturesMask</key>
<string>0xFFFFFFFF</string>
<key>#LocationInChassis</key>
<string>MLB</string>
<key>#Memory</key>
<dict>
<key>Channels</key>
<integer>2</integer>
<key>Modules</key>
<array>
<dict>
<key>Frequency</key>
<integer>1333</integer>
<key>Part</key>
<string>C0001403</string>
<key>Serial</key>
<string>00001001</string>
<key>Size</key>
<integer>4096</integer>
<key>Slot</key>
<integer>0</integer>
<key>Type</key>
<string>DDR3</string>
<key>Vendor</key>
<string>Kingston</string>
</dict>
<dict>
<key>Frequency</key>
<integer>1333</integer>
<key>Part</key>
<string>C0001404</string>
<key>Serial</key>
<string>00001002</string>
<key>Size</key>
<integer>4096</integer>
<key>Slot</key>
<integer>2</integer>
<key>Type</key>
<string>DDR3</string>
<key>Vendor</key>
<string>Kingston</string>
</dict>
</array>
<key>SlotCount</key>
<integer>4</integer>
</dict>
<key>#Mobile</key>
<true/>
<key>#PlatformFeature</key>
<string>0x03</string>
<key>#ProductName</key>
<string>MacBook1,1</string>
<key>#SerialNumber</key>
<string>4H629LYAU9C</string>
<key>#Slots</key>
<array>
<dict>
<key>Device</key>
<string>ATI</string>
<key>ID</key>
<integer>1</integer>
<key>Name</key>
<string>PCIe Slot 0</string>
<key>Type</key>
<integer>16</integer>
</dict>
<dict>
<key>Device</key>
<string>WIFI</string>
<key>ID</key>
<integer>0</integer>
<key>Name</key>
<string>Airport</string>
<key>Type</key>
<integer>1</integer>
</dict>
</array>
<key>#SmUUID</key>
<string>00000000-0000-1000-8000-010203040506</string>
<key>#Trust</key>
<true/>
<key>#Version</key>
<string>1.0</string>
<key>Manufacturer</key>
<string>Apple Inc.</string>
</dict>
<key>SystemParameters</key>
<dict>
<key>#BacklightLevel</key>
<string>0x0501</string>
<key>#CustomUUID</key>
<string>511CE201-1000-4000-9999-010203040506</string>
<key>#NvidiaWeb</key>
<false/>
<key>InjectKexts</key>
<string>Detect</string>
<key>InjectSystemID</key>
<true/>
</dict>
</dict>
</plist>
``` | /content/code_sandbox/Clover-Configs/Dell/Dell Inspiron 7520/CLOVER/config-Slice.plist | xml | 2016-11-05T04:22:54 | 2024-08-12T19:25:53 | Hackintosh-Installer-University | huangyz0918/Hackintosh-Installer-University | 3,937 | 7,181 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\..\configureawait.props" />
<Import Project="..\..\..\common.props" />
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None Remove="Volo.Abp.BlobStoring.Database.SourceCode.zip" />
<Content Include="Volo.Abp.BlobStoring.Database.SourceCode.zip">
<Pack>true</Pack>
<PackagePath>content\</PackagePath>
</Content>
</ItemGroup>
</Project>
``` | /content/code_sandbox/studio/source-codes/Volo.Abp.BlobStoring.Database.SourceCode/Volo.Abp.BlobStoring.Database.SourceCode.csproj | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 129 |
```xml
import { Note } from "./Note";
import { Fraction } from "../../Common/DataObjects/Fraction";
import { PlacementEnum } from "./Expressions/AbstractExpression";
import { Beam } from "./Beam";
/**
* Tuplets create irregular rhythms; e.g. triplets, quadruplets, quintuplets, etc.
*/
export class Tuplet {
constructor(tupletLabelNumber: number, bracket: boolean = false) {
this.tupletLabelNumber = tupletLabelNumber;
this.bracket = bracket;
}
private tupletLabelNumber: number;
public PlacementFromXml: boolean = false;
public tupletLabelNumberPlacement: PlacementEnum;
public RenderTupletNumber: boolean = true;
/** Notes contained in the tuplet, per VoiceEntry (list of VoiceEntries, which has a list of notes). */
private notes: Note[][] = []; // TODO should probably be VoiceEntry[], not Note[][].
private fractions: Fraction[] = [];
/** Whether this tuplet has a bracket. (e.g. showing |--3--| or just 3 for a triplet) */
private bracket: boolean;
/** Boolean if 'bracket="no"' or "yes" was explicitly requested in the XML, otherwise undefined. */
public BracketedXmlValue: boolean;
/** Whether <tuplet show-number="none"> was given in the XML, indicating the tuplet number should not be rendered. */
public ShowNumberNoneGivenInXml: boolean;
/** Determines whether the tuplet should be bracketed (arguments are EngravingRules). */
public shouldBeBracketed(useXmlValue: boolean,
tupletsBracketed: boolean,
tripletsBracketed: boolean,
isTabMeasure: boolean = false,
tabTupletsBracketed: boolean = false,
): boolean {
if (isTabMeasure) {
return tabTupletsBracketed;
}
if (useXmlValue && this.BracketedXmlValue !== undefined) {
return this.BracketedXmlValue;
}
// Gould: tuplets need bracket if they're not on one single beam (see #1400)
const startingBeam: Beam = this.Notes[0][0].NoteBeam;
// const startingVFBeam: VF.Beam = (tupletStaveNotes[0] as any).beam; // alternative way to check. see for loop
if (!startingBeam) {
return true;
} else {
for (const tupletNotes of this.Notes) {
if (tupletNotes[0].NoteBeam !== startingBeam) {
return true;
}
}
}
return this.Bracket ||
(this.TupletLabelNumber === 3 && tripletsBracketed) ||
(this.TupletLabelNumber !== 3 && tupletsBracketed);
}
public get TupletLabelNumber(): number {
return this.tupletLabelNumber;
}
public set TupletLabelNumber(value: number) {
this.tupletLabelNumber = value;
}
public get Notes(): Note[][] {
return this.notes;
}
public set Notes(value: Note[][]) {
this.notes = value;
}
public get Fractions(): Fraction[] {
return this.fractions;
}
public set Fractions(value: Fraction[]) {
this.fractions = value;
}
public get Bracket(): boolean {
return this.bracket;
}
public set Bracket(value: boolean) {
this.bracket = value;
}
/**
* Returns the index of the given Note in the Tuplet List (notes[0], notes[1],...).
* @param note
* @returns {number}
*/
public getNoteIndex(note: Note): number {
for (let i: number = this.notes.length - 1; i >= 0; i--) {
for (let j: number = 0; j < this.notes[i].length; j++) {
if (note === this.notes[i][j]) {
return i;
}
}
}
return 0;
}
}
``` | /content/code_sandbox/src/MusicalScore/VoiceData/Tuplet.ts | xml | 2016-02-08T15:47:01 | 2024-08-16T17:49:53 | opensheetmusicdisplay | opensheetmusicdisplay/opensheetmusicdisplay | 1,416 | 884 |
```xml
/*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import { Component, type OnInit } from "@angular/core";
import { FormControl } from "@angular/forms";
import { MatDialog } from "@angular/material/dialog";
import { ActivatedRoute } from "@angular/router";
import { BehaviorSubject } from "rxjs";
import { ResponseCoordinate } from "trafficops-types";
import { CacheGroupService } from "src/app/api";
import { CurrentUserService } from "src/app/shared/current-user/current-user.service";
import { DecisionDialogComponent } from "src/app/shared/dialogs/decision-dialog/decision-dialog.component";
import type {
ContextMenuActionEvent,
ContextMenuItem,
DoubleClickLink
} from "src/app/shared/generic-table/generic-table.component";
import { NavigationService } from "src/app/shared/navigation/navigation.service";
/**
* CoordinatesTableComponent is the controller for the "Coordinates" table.
*/
@Component({
selector: "tp-coordinates",
styleUrls: ["./coordinates-table.component.scss"],
templateUrl: "./coordinates-table.component.html"
})
export class CoordinatesTableComponent implements OnInit {
/** List of coordinates */
public coordinates: Promise<Array<ResponseCoordinate>>;
/** Definitions of the table's columns according to the ag-grid API */
public columnDefs = [
{
field: "name",
headerName: "Name"
},
{
field: "latitude",
headerName: "Latitude"
},
{
field: "longitude",
headerName: "Longitude"
},
{
field: "id",
headerName:" ID",
hide: true
},
{
field: "lastUpdated",
headerName: "Last Updated"
}
];
/** Definitions for the context menu items (which act on augmented coordinate data). */
public contextMenuItems: Array<ContextMenuItem<ResponseCoordinate>> = [
{
href: (crd: ResponseCoordinate): string => `${crd.id}`,
name: "Edit"
},
{
href: (crd: ResponseCoordinate): string => `${crd.id}`,
name: "Open in New Tab",
newTab: true
},
{
action: "delete",
multiRow: false,
name: "Delete"
},
];
/** Defines what the table should do when a row is double-clicked. */
public doubleClickLink: DoubleClickLink<ResponseCoordinate> = {
href: (row: ResponseCoordinate): string => `/core/coordinates/${row.id}`
};
/** A subject that child components can subscribe to for access to the fuzzy search query text */
public fuzzySubject: BehaviorSubject<string>;
/** Form controller for the user search input. */
public fuzzControl = new FormControl<string>("", {nonNullable: true});
constructor(private readonly route: ActivatedRoute, private readonly navSvc: NavigationService,
private readonly api: CacheGroupService, private readonly dialog: MatDialog, public readonly auth: CurrentUserService) {
this.fuzzySubject = new BehaviorSubject<string>("");
this.coordinates = this.api.getCoordinates();
this.navSvc.headerTitle.next("Coordinates");
}
/** Initializes table data, loading it from Traffic Ops. */
public ngOnInit(): void {
this.route.queryParamMap.subscribe(
m => {
const search = m.get("search");
if (search) {
this.fuzzControl.setValue(decodeURIComponent(search));
this.updateURL();
}
}
);
}
/** Update the URL's 'search' query parameter for the user's search input. */
public updateURL(): void {
this.fuzzySubject.next(this.fuzzControl.value);
}
/**
* Handles a context menu event.
*
* @param evt The action selected from the context menu.
*/
public async handleContextMenu(evt: ContextMenuActionEvent<ResponseCoordinate>): Promise<void> {
const data = evt.data as ResponseCoordinate;
switch(evt.action) {
case "delete":
const ref = this.dialog.open(DecisionDialogComponent, {
data: {message: `Are you sure you want to delete coordinate ${data.name} with id ${data.id}`, title: "Confirm Delete"}
});
ref.afterClosed().subscribe(result => {
if(result) {
this.api.deleteCoordinate(data.id).then(async () => this.coordinates = this.api.getCoordinates());
}
});
break;
}
}
}
``` | /content/code_sandbox/experimental/traffic-portal/src/app/core/cache-groups/coordinates/table/coordinates-table.component.ts | xml | 2016-09-02T07:00:06 | 2024-08-16T03:50:21 | trafficcontrol | apache/trafficcontrol | 1,043 | 955 |
```xml
import classnames from 'classnames'
import React from 'react'
import { MdClose } from 'react-icons/md'
import { Panel, sidebarPanelChat, sidebarPanelSettings, sidebarPanelUsers } from '../actions/SidebarActions'
import { MinimizeTogglePayload } from '../actions/StreamActions'
import { Message } from '../reducers/messages'
import { Nicknames } from '../reducers/nicknames'
import Chat from './Chat'
import Settings from './Settings'
import Users from './Users'
export interface SidebarProps {
// Panel state
onHide: () => void
onShow: (panel: Panel) => void
visible: boolean
panel: Panel
// Chat
messages: Message[]
nicknames: Nicknames
sendFile: (file: File) => void
sendText: (message: string) => void
// Users
play: () => void
onMinimizeToggle: (payload: MinimizeTogglePayload) => void
}
export default class Sidebar extends React.PureComponent<SidebarProps> {
render () {
const { messages, nicknames, sendFile, sendText, panel } = this.props
const { onMinimizeToggle } = this.props
return (
<div className={classnames('sidebar', {
show: this.props.visible,
})}>
<div className='sidebar-header'>
<div className='sidebar-close' onClick={this.props.onHide}>
<MdClose />
</div>
<ul className='sidebar-menu'>
<SidebarButton
activePanel={panel}
className='sidebar-menu-chat'
label='Chat'
onClick={this.props.onShow}
panel={sidebarPanelChat}
/>
<SidebarButton
activePanel={panel}
className='sidebar-menu-users'
label='Users'
onClick={this.props.onShow}
panel={sidebarPanelUsers}
/>
<SidebarButton
activePanel={panel}
className='sidebar-menu-settings'
label='Settings'
onClick={this.props.onShow}
panel={sidebarPanelSettings}
/>
</ul>
</div>
<div className='sidebar-content'>
{panel === sidebarPanelChat && (
<Chat
nicknames={nicknames}
messages={messages}
sendFile={sendFile}
sendText={sendText}
visible={this.props.visible}
/>
)}
{panel === sidebarPanelUsers && (
<Users
onMinimizeToggle={onMinimizeToggle}
play={this.props.play}
/>
)}
{panel === sidebarPanelSettings && (
<Settings />
)}
</div>
</div>
)
}
}
interface SidebarButtonProps {
activePanel: Panel
className?: string
label: string
panel: Panel
onClick: (panel: Panel) => void
}
class SidebarButton extends React.PureComponent<SidebarButtonProps> {
handleClick = () => {
this.props.onClick(this.props.panel)
}
render() {
const { activePanel, label, panel } = this.props
const className = classnames(this.props.className, 'sidebar-button', {
active: activePanel === panel,
})
return (
<li
aria-label={label}
className={className}
onClick={this.handleClick}
role='button'
>
{label}
</li>
)
}
}
``` | /content/code_sandbox/src/client/components/Sidebar.tsx | xml | 2016-03-31T22:41:02 | 2024-08-12T19:22:09 | peer-calls | peer-calls/peer-calls | 1,365 | 726 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.