text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```xml import * as React from 'react'; import { makeStyles, Button, Menu, MenuTrigger, MenuPopover, MenuList, MenuItem, MenuButton, tokens, mergeClasses, Overflow, OverflowItem, OverflowItemProps, useIsOverflowItemVisible, useOverflowMenu, } from '@fluentui/react-components'; const useStyles = makeStyles({ container: { display: 'flex', flexWrap: 'nowrap', minWidth: 0, overflow: 'hidden', }, resizableArea: { minWidth: '200px', maxWidth: '800px', border: `2px solid ${tokens.colorBrandBackground}`, padding: '20px 10px 10px 10px', position: 'relative', resize: 'horizontal', '::after': { content: `'Resizable Area'`, position: 'absolute', padding: '1px 4px 1px', top: '-2px', left: '-2px', fontFamily: 'monospace', fontSize: '15px', fontWeight: 900, lineHeight: 1, letterSpacing: '1px', color: tokens.colorNeutralForegroundOnBrand, backgroundColor: tokens.colorBrandBackground, }, }, }); export const ReverseDomOrder = () => { const styles = useStyles(); const itemIds = new Array(8).fill(0).map((_, i) => i.toString()); return ( <Overflow overflowDirection="start"> <div className={mergeClasses(styles.container, styles.resizableArea)}> <OverflowMenu itemIds={itemIds} /> {itemIds.map(i => ( <OverflowItem key={i} id={i}> <Button>Item {i}</Button> </OverflowItem> ))} </div> </Overflow> ); }; const OverflowMenuItem: React.FC<Pick<OverflowItemProps, 'id'>> = props => { const { id } = props; const isVisible = useIsOverflowItemVisible(id); if (isVisible) { return null; } // As an union between button props and div props may be conflicting, casting is required return <MenuItem>Item {id}</MenuItem>; }; const OverflowMenu: React.FC<{ itemIds: string[] }> = ({ itemIds }) => { const { ref, overflowCount, isOverflowing } = useOverflowMenu<HTMLButtonElement>(); if (!isOverflowing) { return null; } return ( <Menu> <MenuTrigger disableButtonEnhancement> <MenuButton ref={ref}>+{overflowCount} items</MenuButton> </MenuTrigger> <MenuPopover> <MenuList> {itemIds.map(i => { return <OverflowMenuItem key={i} id={i} />; })} </MenuList> </MenuPopover> </Menu> ); }; ReverseDomOrder.parameters = { docs: { description: { story: ['Overflow can happen in reverse DOM order.'].join('\n'), }, }, }; ```
/content/code_sandbox/packages/react-components/react-overflow/stories/src/Overflow/ReverseDomOrder.stories.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
663
```xml <?xml version="1.0" encoding="UTF-8"?> <!-- ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <sql-cases> <sql-case id="set_password" value="SET PASSWORD = 'password'" db-types="MySQL" /> <sql-case id="set_password_for_user" value="SET PASSWORD FOR user1 = 'password'" db-types="MySQL" /> <sql-case id="set_password_for_local_user" value="SET PASSWORD FOR 'user1'@'localhost' = 'password'" db-types="MySQL" /> <sql-case id="replace_password" value="SET PASSWORD FOR user1 = 'password' REPLACE 'password'" db-types="MySQL" /> <sql-case id="set_password_and_retain" value="SET PASSWORD FOR user1 = 'password' RETAIN CURRENT PASSWORD" db-types="MySQL" /> </sql-cases> ```
/content/code_sandbox/test/it/parser/src/main/resources/sql/supported/dcl/set-password.xml
xml
2016-01-18T12:49:26
2024-08-16T15:48:11
shardingsphere
apache/shardingsphere
19,707
246
```xml import { ExportData } from "../../../src/importers/onepassword/types/onepassword-1pux-importer-types"; export const DatabaseData: ExportData = { accounts: [ { attrs: { accountName: "1Password Customer", name: "1Password Customer", avatar: "", email: "username123123123@gmail.com", uuid: "TRIZ3XV4JJFRXJ3BARILLTUA6E", domain: "path_to_url", }, vaults: [ { attrs: { uuid: "pqcgbqjxr4tng2hsqt5ffrgwju", desc: "Just test entries", avatar: "ke7i5rxnjrh3tj6uesstcosspu.png", name: "T's Test Vault", type: "U", }, items: [ { uuid: "ospvepl3ex2y6hjwwqwyvtf2sy", favIndex: 0, createdAt: 1619466193, updatedAt: 1619466276, trashed: false, categoryUuid: "102", details: { loginFields: [], notesPlain: "My Database", sections: [ { title: "", fields: [ { title: "type", id: "database_type", value: { menu: "postgresql", }, indexAtSource: 0, guarded: false, multiline: false, dontGenerate: false, inputTraits: { keyboard: "default", correction: "default", capitalization: "default", }, }, { title: "server", id: "hostname", value: { string: "my.secret.db.server", }, indexAtSource: 1, guarded: false, multiline: false, dontGenerate: false, inputTraits: { keyboard: "uRL", correction: "default", capitalization: "default", }, }, { title: "port", id: "port", value: { string: "1337", }, indexAtSource: 2, guarded: false, multiline: false, dontGenerate: false, inputTraits: { keyboard: "numberPad", correction: "default", capitalization: "default", }, }, { title: "database", id: "database", value: { string: "user_database", }, indexAtSource: 3, guarded: false, multiline: false, dontGenerate: false, inputTraits: { keyboard: "default", correction: "no", capitalization: "none", }, }, { title: "username", id: "username", value: { string: "cooldbuser", }, indexAtSource: 4, guarded: false, multiline: false, dontGenerate: false, inputTraits: { keyboard: "default", correction: "no", capitalization: "none", }, }, { title: "password", id: "password", value: { concealed: "^+kTjhLaN7wVPAhGU)*J", }, indexAtSource: 5, guarded: false, multiline: false, dontGenerate: false, inputTraits: { keyboard: "default", correction: "default", capitalization: "default", }, }, { title: "SID", id: "sid", value: { string: "ASDIUFU-283234", }, indexAtSource: 6, guarded: false, multiline: false, dontGenerate: false, inputTraits: { keyboard: "default", correction: "default", capitalization: "default", }, }, { title: "alias", id: "alias", value: { string: "cdbu", }, indexAtSource: 7, guarded: false, multiline: false, dontGenerate: false, inputTraits: { keyboard: "default", correction: "default", capitalization: "default", }, }, { title: "connection options", id: "options", value: { string: "ssh", }, indexAtSource: 8, guarded: false, multiline: false, dontGenerate: false, inputTraits: { keyboard: "default", correction: "default", capitalization: "default", }, }, ], }, ], passwordHistory: [], }, overview: { subtitle: "my.secret.db.server", title: "Database", url: "", ps: 0, pbe: 0.0, pgrng: false, }, }, ], }, ], }, ], }; ```
/content/code_sandbox/libs/importer/spec/test-data/onepassword-1pux/database.ts
xml
2016-03-09T23:14:01
2024-08-16T15:07:51
clients
bitwarden/clients
8,877
1,093
```xml import AthenaClient from "../AthenaClient"; import Base, { ConfigSchemasType, TableSummary } from "./Base"; import { DataSourceKeys } from "../../renderer/pages/DataSource/DataSourceStore"; export default class Athena extends Base { client: AthenaClient; static override get key(): DataSourceKeys { return "athena"; } static override get label(): string { return "Amazon Athena"; } static override get configSchema(): ConfigSchemasType { return [ { name: "region", label: "Region", type: "string", placeholder: "us-east-1", required: true, }, { name: "accessKeyId", label: "Access key ID", type: "string", }, { name: "secretAccessKey", label: "Secret access key", type: "string", }, { name: "database", label: "Database", type: "string", required: true, }, { name: "outputLocation", label: "Query result location", type: "string", placeholder: "s3://query-results-bucket/prefix/", required: true, }, ]; } constructor(config) { super(config); this.client = new AthenaClient(this.config); } async execute(query: string): Promise<{ fields: any; rows: any }> { const rows = await this.client.execute(query); const fields = rows.shift(); return { fields, rows }; } cancel(): void { this.client.cancel(); } async connectionTest(): Promise<void> { await this.client.execute("select 1"); } async fetchTables(): Promise<{ name: string; type: string; schema?: string }[]> { const rows = await this.client.execute("show tables"); return rows.map((row) => ({ name: row[0]!, type: "table" })); } async fetchTableSummary({ name }: { name: string }): Promise<TableSummary> { const rows = await this.client.execute(`describe ${name}`); const defs = { fields: ["name", "type"], rows: rows .map((row) => row[0]) .filter((v) => v !== null && v[0] !== "#" && v.trim() !== "") .map((v) => (v || "").split("\t").map((c) => c.trim())), }; return { name, defs }; } dataSourceInfo(): Record<string, any> { return { type: Athena.label, region: this.config.region, database: this.config.database, }; } } ```
/content/code_sandbox/src/lib/DataSourceDefinition/Athena.ts
xml
2016-08-23T12:20:03
2024-08-14T08:26:34
bdash
bdash-app/bdash
1,488
577
```xml <?xml version="1.0" encoding="UTF-8"?> <testsuites> <testsuite name="tensorflow/python/kernel_tests/dense_update_ops_no_tsan_test" tests="1" failures="0" errors="0"> <testcase name="tensorflow/python/kernel_tests/dense_update_ops_no_tsan_test" status="run"></testcase> </testsuite> </testsuites> ```
/content/code_sandbox/testlogs/python27/2016_07_17/tensorflow/python/kernel_tests/dense_update_ops_no_tsan_test/test.xml
xml
2016-03-12T06:26:47
2024-08-12T19:21:52
tensorflow-on-raspberry-pi
samjabrahams/tensorflow-on-raspberry-pi
2,242
87
```xml <Project Sdk="Microsoft.NET.Sdk.Worker"> <PropertyGroup> <Title>AsmDude2 Language Server Protocol (LSP)</Title> <Version>1.0.0.4</Version> <Authors>Henk-Jan Lebbink</Authors> <Description>AsmDude2 Language Server Protocol (LSP) for assembly language</Description> <AssemblyName>AsmDude2.LSP</AssemblyName> <Company></Company> <TargetFramework>net7.0-windows</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <UserSecretsId>dotnet-WindowsService-7b46c878-2e29-4de0-b355-fe97116ed91a</UserSecretsId> <PlatformTarget>x64</PlatformTarget> <ApplicationIcon>AsmDudePackage.ico</ApplicationIcon> <GeneratePackageOnBuild>False</GeneratePackageOnBuild> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <SourceRevisionId>build$([System.DateTime]::UtcNow.ToString("yyyyMMddHHmmss"))</SourceRevisionId> <EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild> <RootNamespace>AsmDude2LS</RootNamespace> <RepositoryType>git</RepositoryType> <RepositoryUrl>path_to_url </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <WarningLevel>7</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <WarningLevel>7</WarningLevel> </PropertyGroup> <ItemGroup> <Content Include="AsmDudePackage.ico" /> <Content Include="lsp-version.txt"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </Content> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\asm-dude2-ls-lib\asm-dude2-ls-lib.csproj" /> </ItemGroup> <ItemGroup> <None Update="LICENSE.txt"> <Pack>True</Pack> <PackagePath>\</PackagePath> </None> </ItemGroup> </Project> ```
/content/code_sandbox/VS/CSHARP/asm-dude2-ls/asm-dude2-ls.csproj
xml
2016-02-19T15:43:23
2024-08-16T10:20:31
asm-dude
HJLebbink/asm-dude
4,118
551
```xml <!-- ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <dataset update-count="2"> <metadata data-nodes="db.t_shadow"> <column name="order_id" type="long" /> <column name="user_id" type="int" /> <column name="order_name" type="varchar" /> <column name="type_char" type="char" /> <column name="type_boolean" type="boolean" /> <column name="type_smallint" type="smallint" /> <column name="type_enum" type="enum#season" /> <column name="type_decimal" type="decimal" /> <column name="type_date" type="Date" /> <column name="type_time" type="time" /> <column name="type_timestamp" type="timestamp" /> </metadata> <row data-node="db.t_shadow" values="1, 1, pro_order, S, true, 5, summer, 10.00, 2017-08-08, 18:30:30, 2017-08-08 18:30:30.0" /> <row data-node="db.t_shadow" values="2, 1, pro_order, S, true, 5, summer, 10.00, 2017-08-08, 18:30:30, 2017-08-08 18:30:30.0" /> <row data-node="db.t_shadow" values="3, 1, pro_order, S, true, 5, summer, 10.00, 2017-08-08, 18:30:30, 2017-08-08 18:30:30.0" /> <row data-node="db.t_shadow" values="4, 1, pro_order, S, true, 5, summer, 10.00, 2017-08-08, 18:30:30, 2017-08-08 18:30:30.0" /> <row data-node="db.t_shadow" values="5, 1, pro_order, S, true, 5, summer, 10.00, 2017-08-08, 18:30:30, 2017-08-08 18:30:30.0" /> <row data-node="db.t_shadow" values="7, 1, pro_order, S, true, 50, summer, 100.00, 2021-01-01, 12:30:30, 2021-01-01 12:30:30.0" /> <row data-node="db.t_shadow" values="8, 1, pro_order, S, true, 50, summer, 100.00, 2021-01-01, 12:30:30, 2021-01-01 12:30:30.0" /> </dataset> ```
/content/code_sandbox/test/e2e/sql/src/test/resources/cases/dml/dataset/shadow/mysql/pro_insert_order_batch_value.xml
xml
2016-01-18T12:49:26
2024-08-16T15:48:11
shardingsphere
apache/shardingsphere
19,707
706
```xml <!-- ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <dataset> <metadata> <column name="oid" /> <column name="lomowner" /> <column name="lomacl" /> </metadata> </dataset> ```
/content/code_sandbox/test/e2e/sql/src/test/resources/cases/dql/dataset/empty_storage_units/postgresql/select_postgresql_pg_catalog_pg_largeobject_metadata.xml
xml
2016-01-18T12:49:26
2024-08-16T15:48:11
shardingsphere
apache/shardingsphere
19,707
113
```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-----------*/ import { VertexProgram } from '../raster/index' import { FragmentProgram } from '../raster/index' import { Vertex } from '../raster/index' import { Matrix, Vector4 } from '../math/index' import { Texture } from './texture' // ----------------------------------------------------------- // // Material // // ----------------------------------------------------------- export interface MaterialUniform { projection: Matrix, view: Matrix, matrix: Matrix, } export class Material<TUniform=any> { constructor(public vertexProgram: VertexProgram<TUniform>, public fragmentProgram: FragmentProgram<TUniform>, public uniforms: TUniform) { } } // ----------------------------------------------------------- // // TextureMaterial // // ----------------------------------------------------------- export interface TextureMaterialUniform { texture: Texture } export class TextureMaterialVertexShader implements VertexProgram { private matrix0: Matrix = Matrix.identity() private matrix1: Matrix = Matrix.identity() main(uniform: MaterialUniform & TextureMaterialUniform, vertex: Vertex, varying: Vertex, output: Vector4) { varying.position = vertex.position varying.normal = vertex.normal varying.uv = vertex.uv Matrix.fast_mul(uniform.view, uniform.projection, this.matrix0) Matrix.fast_mul(uniform.matrix, this.matrix0, this.matrix1) Vector4.fast_transform(vertex.position, this.matrix1, output) } } export class TextureMaterialFragmentShader implements FragmentProgram { main(uniform: TextureMaterialUniform, varying: Vertex, output: Vector4) { uniform.texture.fast_sample(varying.uv.x, varying.uv.y, output) } } export class TextureMaterial extends Material { constructor(public texture: Texture) { super(new TextureMaterialVertexShader(), new TextureMaterialFragmentShader(), { texture }) } } ```
/content/code_sandbox/src/engine/render/material.ts
xml
2016-10-10T11:59:07
2024-08-16T11:00:47
zero
sinclairzx81/zero
2,412
595
```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 fromBinaryString = require( './index' ); // TESTS // // The function returns a number... { fromBinaryString( your_sha256_hash ); // $ExpectType number } // The compiler throws an error if the function is provided a value other than a string... { fromBinaryString( true ); // $ExpectError fromBinaryString( false ); // $ExpectError fromBinaryString( 5 ); // $ExpectError fromBinaryString( [] ); // $ExpectError fromBinaryString( {} ); // $ExpectError fromBinaryString( ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided insufficient arguments... { fromBinaryString(); // $ExpectError } ```
/content/code_sandbox/lib/node_modules/@stdlib/number/float64/base/from-binary-string/docs/types/test.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
208
```xml <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net5.0</TargetFramework> <EnableDefaultContentItems>False</EnableDefaultContentItems> </PropertyGroup> <ItemGroup> <Content Include=".\SampleRequests\*"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup> <ItemGroup> <Content Include="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup> <ItemGroup> <PackageReference Include="Amazon.Lambda.Core" Version="2.1.0" /> <PackageReference Include="Amazon.Lambda.TestUtilities" Version="2.0.0" /> <PackageReference Include="Amazon.Lambda.APIGatewayEvents" Version="2.6.0" /> <PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="3.7.0.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" /> <PackageReference Include="xunit" Version="2.3.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\src\BlueprintBaseName.1\BlueprintBaseName.1.csproj" /> </ItemGroup> </Project> ```
/content/code_sandbox/Blueprints/BlueprintDefinitions/vs2019/AspNetCoreWebAPI-Image/template/test/BlueprintBaseName.1.Tests/BlueprintBaseName.1.Tests.csproj
xml
2016-11-11T20:43:34
2024-08-15T16:57:53
aws-lambda-dotnet
aws/aws-lambda-dotnet
1,558
322
```xml export * from "./RSSCalendarService"; ```
/content/code_sandbox/samples/react-calendar-feed/src/shared/services/CalendarService/RSSCalendarService/index.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
9
```xml import { trigger, state, style, keyframes, transition, animate, AnimationTriggerMetadata, AUTO_STYLE, query, animateChild, group, } from '@angular/animations'; import { IAnimationOptions } from '../common/interfaces'; /** * const tdPulseAnimation * * Parameter Options: * * duration: Duration the animation will run in milliseconds. Defaults to 500 ms. * * delay: Delay before the animation will run in milliseconds. Defaults to 0 ms. * * ease: Animation accelerate and decelerate style. Defaults to ease-out. * * Returns an [AnimationTriggerMetadata] object with boolean states for a pulse animation. * * usage: [@tdPulse]="{ value: true | false, params: { duration: 200 }}" */ export const tdPulseAnimation: AnimationTriggerMetadata = trigger('tdPulse', [ state( '0', style({ transform: 'scale3d(1, 1, 1)', }) ), state( '1', style({ transform: 'scale3d(1, 1, 1)', }) ), transition( '0 <=> 1', [ group([ query('@*', animateChild(), { optional: true }), animate( '{{ duration }}ms {{ delay }}ms {{ ease }}', keyframes([ style({ transform: 'scale3d(1, 1, 1)', offset: 0 }), style({ transform: 'scale3d(1.05, 1.05, 1.05)', offset: 0.5 }), style({ transform: 'scale3d(1, 1, 1)', offset: 1.0 }), ]) ), ]), ], { params: { duration: 500, delay: '0', ease: 'ease-out' } } ), ]); ```
/content/code_sandbox/libs/angular/common/src/animations/pulse/pulse.animation.ts
xml
2016-07-11T23:30:52
2024-08-15T15:20:45
covalent
Teradata/covalent
2,228
406
```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. --> <vector xmlns:android="path_to_url" android:width="24dp" android:height="24dp" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:fillColor="#FFFFFFFF" android:pathData="M17,12h-5v5h5v-5zM16,1v2L8,3L8,1L6,1v2L5,3c-1.11,0 -1.99,0.9 -1.99,2L3,19c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2L21,5c0,-1.1 -0.9,-2 -2,-2h-1L18,1h-2zM19,19L5,19L5,8h14v11z"/> </vector> ```
/content/code_sandbox/app/src/main/res/drawable/ic_calendar_white_24dp.xml
xml
2016-03-18T15:35:45
2024-08-16T06:43:09
PaperPlane
TonnyL/PaperPlane
1,141
260
```xml import { GraphQLFieldConfigMap, GraphQLObjectType, GraphQLSchema, Kind, OperationTypeNode, visit, } from 'graphql'; import { DelegationContext, Transform } from '@graphql-tools/delegate'; import { ExecutionRequest, ExecutionResult, getDefinedRootType, getRootTypeMap, MapperKind, mapSchema, } from '@graphql-tools/utils'; const defaultRootTypeNames = { query: 'Query', mutation: 'Mutation', subscription: 'Subscription', }; export class MoveRootField implements Transform { private to: Record<OperationTypeNode, Record<string, OperationTypeNode>> = { query: {}, mutation: {}, subscription: {}, }; constructor(private from: Record<OperationTypeNode, Record<string, OperationTypeNode>>) { for (const operation in this.from) { const removedFields = this.from[operation as OperationTypeNode]; for (const fieldName in removedFields) { const newOperation = removedFields[fieldName]; this.to[newOperation][fieldName] = operation as OperationTypeNode; } } } public transformSchema( schema: GraphQLSchema, _subschemaConfig: Record<string, any>, ): GraphQLSchema { const rootTypeMap = getRootTypeMap(schema); const newRootFieldsMap: Record<OperationTypeNode, GraphQLFieldConfigMap<any, any>> = { query: rootTypeMap.get('query' as OperationTypeNode)?.toConfig()?.fields || {}, mutation: rootTypeMap.get('mutation' as OperationTypeNode)?.toConfig()?.fields || {}, subscription: rootTypeMap.get('subscription' as OperationTypeNode)?.toConfig()?.fields || {}, }; for (const operation in this.from) { const removedFields = this.from[operation as OperationTypeNode]; for (const fieldName in removedFields) { const fieldConfig = newRootFieldsMap[operation as OperationTypeNode][fieldName]; delete newRootFieldsMap[operation]?.[fieldName]; const newOperation = removedFields[fieldName]; newRootFieldsMap[newOperation][fieldName] = fieldConfig; } } const schemaConfig = schema.toConfig(); for (const rootType in newRootFieldsMap) { const newRootFields = newRootFieldsMap[rootType as OperationTypeNode]; if (!schemaConfig[rootType] && Object.keys(newRootFields).length > 0) { schemaConfig[rootType] = new GraphQLObjectType({ name: defaultRootTypeNames[rootType], fields: newRootFields, }); } } return mapSchema(new GraphQLSchema(schemaConfig), { [MapperKind.QUERY]: type => { const queryConfig = type.toConfig(); queryConfig.fields = newRootFieldsMap.query; return new GraphQLObjectType(queryConfig); }, [MapperKind.MUTATION]: type => { const mutationConfig = type.toConfig(); mutationConfig.fields = newRootFieldsMap.mutation; return new GraphQLObjectType(mutationConfig); }, [MapperKind.SUBSCRIPTION]: type => { const subscriptionConfig = type.toConfig(); subscriptionConfig.fields = newRootFieldsMap.subscription; return new GraphQLObjectType(subscriptionConfig); }, }); } public transformRequest( originalRequest: ExecutionRequest, delegationContext: DelegationContext, ): ExecutionRequest { const newOperation = this.to[delegationContext.operation][delegationContext.fieldName]; if (newOperation && newOperation !== delegationContext.operation) { return { ...originalRequest, document: visit(originalRequest.document, { [Kind.OPERATION_DEFINITION]: node => { return { ...node, operation: newOperation, }; }, }), }; } return originalRequest; } public transformResult(result: ExecutionResult, delegationContext: DelegationContext) { if (result.data?.__typename) { const newOperation = this.to[delegationContext.operation][delegationContext.fieldName]; if (newOperation && newOperation !== delegationContext.operation) { result.data.__typename = getDefinedRootType( delegationContext.targetSchema, newOperation, )?.name; } } return result; } } ```
/content/code_sandbox/packages/wrap/src/transforms/MoveRootField.ts
xml
2016-03-22T00:14:38
2024-08-16T02:02:06
graphql-tools
ardatan/graphql-tools
5,331
901
```xml import { Row } from '@tanstack/react-table'; import { filterHOC } from '@/react/components/datatables/Filter'; import { Link } from '@@/Link'; import { SecretRowData } from '../types'; import { columnHelper } from './helper'; export const namespace = columnHelper.accessor( (row) => row.metadata?.namespace, { header: 'Namespace', id: 'namespace', cell: ({ getValue }) => { const namespace = getValue(); return ( <Link to="kubernetes.resourcePools.resourcePool" params={{ id: namespace, }} title={namespace} data-cy={`secret-namespace-link-${namespace}`} > {namespace} </Link> ); }, meta: { filter: filterHOC('Filter by namespace'), }, enableColumnFilter: true, filterFn: ( row: Row<SecretRowData>, _columnId: string, filterValue: string[] ) => filterValue.length === 0 || filterValue.includes(row.original.metadata?.namespace ?? ''), } ); ```
/content/code_sandbox/app/react/kubernetes/configs/ListView/SecretsDatatable/columns/namespace.tsx
xml
2016-05-19T20:15:28
2024-08-16T19:15:14
portainer
portainer/portainer
30,083
237
```xml <?xml version="1.0" encoding="UTF-8"?> <!-- ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ ~ path_to_url ~ ~ Unless required by applicable law or agreed to in writing, software ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> <project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-broadcast</artifactId> <version>5.5.1-SNAPSHOT</version> </parent> <artifactId>shardingsphere-broadcast-core</artifactId> <name>${project.artifactId}</name> <dependencies> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-broadcast-api</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-infra-route</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-mode-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-infra-expr-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-test-util</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-test-fixture-database</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-single-core</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-parser-sql-sql92</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-parser-sql-mysql</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-parser-sql-postgresql</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-parser-sql-oracle</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-parser-sql-sqlserver</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-test-it-yaml</artifactId> <version>${project.version}</version> <scope>test</scope> </dependency> </dependencies> </project> ```
/content/code_sandbox/features/broadcast/core/pom.xml
xml
2016-01-18T12:49:26
2024-08-16T15:48:11
shardingsphere
apache/shardingsphere
19,707
904
```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 { expect } from "chai"; import { Event } from "../../../src/v1"; import * as config from "../../../src/common/config"; import * as functions from "../../../src/v1"; import * as storage from "../../../src/v1/providers/storage"; import { MINIMAL_V1_ENDPOINT } from "../../fixtures"; describe("Storage Functions", () => { describe("ObjectBuilder", () => { function expectedTrigger(bucket: string, eventType: string) { return { eventTrigger: { resource: `projects/_/buckets/${bucket}`, eventType: `google.storage.object.${eventType}`, service: "storage.googleapis.com", }, }; } function expectedEndpoint(bucket: string, eventType: string) { return { ...MINIMAL_V1_ENDPOINT, platform: "gcfv1", eventTrigger: { eventFilters: { resource: `projects/_/buckets/${bucket}`, }, eventType: `google.storage.object.${eventType}`, retry: false, }, labels: {}, }; } const defaultBucket = "bucket"; before(() => { config.resetCache({ storageBucket: defaultBucket, }); }); after(() => { config.resetCache(); }); it("should allow both region and runtime options to be set", () => { const fn = functions .region("us-east1") .runWith({ timeoutSeconds: 90, memory: "256MB", }) .storage.object() .onArchive(() => null); expect(fn.__trigger.regions).to.deep.equal(["us-east1"]); expect(fn.__trigger.availableMemoryMb).to.deep.equal(256); expect(fn.__trigger.timeout).to.deep.equal("90s"); expect(fn.__endpoint.region).to.deep.equal(["us-east1"]); expect(fn.__endpoint.availableMemoryMb).to.deep.equal(256); expect(fn.__endpoint.timeoutSeconds).to.deep.equal(90); }); describe("#onArchive", () => { it("should return a TriggerDefinition with appropriate values", () => { const cloudFunction = storage .bucket("bucky") .object() .onArchive(() => null); expect(cloudFunction.__trigger).to.deep.equal(expectedTrigger("bucky", "archive")); expect(cloudFunction.__endpoint).to.deep.equal(expectedEndpoint("bucky", "archive")); }); it("should use the default bucket when none is provided", () => { const cloudFunction = storage.object().onArchive(() => null); expect(cloudFunction.__trigger).to.deep.equal(expectedTrigger(defaultBucket, "archive")); expect(cloudFunction.__endpoint).to.deep.equal(expectedEndpoint(defaultBucket, "archive")); }); it("should allow fully qualified bucket names", () => { const subjectQualified = new storage.ObjectBuilder(() => "projects/_/buckets/bucky", {}); const result = subjectQualified.onArchive(() => null); expect(result.__trigger).to.deep.equal(expectedTrigger("bucky", "archive")); expect(result.__endpoint).to.deep.equal(expectedEndpoint("bucky", "archive")); }); it("should throw with improperly formatted buckets", () => { expect( () => storage .bucket("bad/bucket/format") .object() .onArchive(() => null).__trigger ).to.throw(Error); expect( () => storage .bucket("bad/bucket/format") .object() .onArchive(() => null).__endpoint ).to.throw(Error); }); it("should not mess with media links using non-literal slashes", () => { const cloudFunction = storage.object().onArchive((data) => { return data.mediaLink; }); const goodMediaLinkEvent: Event = { data: { mediaLink: "path_to_url" + "/o/nestedfolder%2Fanotherfolder%2Fmyobject.file?generation=12345&alt=media", }, context: { eventId: "70172329041928", timestamp: "2018-04-09T07:56:12.975Z", eventType: "google.storage.object.archive", resource: { service: "storage.googleapis.com", name: "projects/_/buckets/bucky", }, }, }; return cloudFunction(goodMediaLinkEvent.data, goodMediaLinkEvent.context).then( (result: any) => { expect(result).equals(goodMediaLinkEvent.data.mediaLink); } ); }); }); describe("#onDelete", () => { it("should return a TriggerDefinition with appropriate values", () => { const cloudFunction = storage .bucket("bucky") .object() .onDelete(() => null); expect(cloudFunction.__trigger).to.deep.equal(expectedTrigger("bucky", "delete")); expect(cloudFunction.__endpoint).to.deep.equal(expectedEndpoint("bucky", "delete")); }); it("should use the default bucket when none is provided", () => { const cloudFunction = storage.object().onDelete(() => null); expect(cloudFunction.__trigger).to.deep.equal(expectedTrigger(defaultBucket, "delete")); expect(cloudFunction.__endpoint).to.deep.equal(expectedEndpoint(defaultBucket, "delete")); }); it("should allow fully qualified bucket names", () => { const subjectQualified = new storage.ObjectBuilder(() => "projects/_/buckets/bucky", {}); const result = subjectQualified.onDelete(() => null); expect(result.__trigger).to.deep.equal(expectedTrigger("bucky", "delete")); expect(result.__endpoint).to.deep.equal(expectedEndpoint("bucky", "delete")); }); it("should throw with improperly formatted buckets", () => { const fn = storage .bucket("bad/bucket/format") .object() .onDelete(() => null); expect(() => fn.__trigger).to.throw(Error); expect(() => fn.__endpoint).to.throw(Error); }); it("should not mess with media links using non-literal slashes", () => { const cloudFunction = storage.object().onDelete((data) => { return data.mediaLink; }); const goodMediaLinkEvent = { data: { mediaLink: "path_to_url" + "/o/nestedfolder%2Fanotherfolder%2Fmyobject.file?generation=12345&alt=media", }, context: { eventId: "70172329041928", timestamp: "2018-04-09T07:56:12.975Z", eventType: "google.storage.object.delete", resource: { service: "storage.googleapis.com", name: "projects/_/buckets/bucky", }, }, }; return cloudFunction(goodMediaLinkEvent.data, goodMediaLinkEvent.context).then( (result: any) => { expect(result).equals(goodMediaLinkEvent.data.mediaLink); } ); }); }); describe("#onFinalize", () => { it("should return a TriggerDefinition with appropriate values", () => { const cloudFunction = storage .bucket("bucky") .object() .onFinalize(() => null); expect(cloudFunction.__trigger).to.deep.equal(expectedTrigger("bucky", "finalize")); expect(cloudFunction.__endpoint).to.deep.equal(expectedEndpoint("bucky", "finalize")); }); it("should use the default bucket when none is provided", () => { const cloudFunction = storage.object().onFinalize(() => null); expect(cloudFunction.__trigger).to.deep.equal(expectedTrigger(defaultBucket, "finalize")); expect(cloudFunction.__endpoint).to.deep.equal(expectedEndpoint(defaultBucket, "finalize")); }); it("should allow fully qualified bucket names", () => { const subjectQualified = new storage.ObjectBuilder(() => "projects/_/buckets/bucky", {}); const result = subjectQualified.onFinalize(() => null); expect(result.__trigger).to.deep.equal(expectedTrigger("bucky", "finalize")); expect(result.__endpoint).to.deep.equal(expectedEndpoint("bucky", "finalize")); }); it("should throw with improperly formatted buckets", () => { const fn = storage .bucket("bad/bucket/format") .object() .onFinalize(() => null); expect(() => fn.__trigger).to.throw(Error); expect(() => fn.__endpoint).to.throw(Error); }); it("should not mess with media links using non-literal slashes", () => { const cloudFunction = storage.object().onFinalize((data) => { return data.mediaLink; }); const goodMediaLinkEvent = { data: { mediaLink: "path_to_url" + "/o/nestedfolder%2Fanotherfolder%2Fmyobject.file?generation=12345&alt=media", }, context: { eventId: "70172329041928", timestamp: "2018-04-09T07:56:12.975Z", eventType: "google.storage.object.finalize", resource: { service: "storage.googleapis.com", name: "projects/_/buckets/bucky", }, }, }; return cloudFunction(goodMediaLinkEvent.data, goodMediaLinkEvent.context).then( (result: any) => { expect(result).equals(goodMediaLinkEvent.data.mediaLink); } ); }); }); describe("#onMetadataUpdate", () => { it("should return a TriggerDefinition with appropriate values", () => { const cloudFunction = storage .bucket("bucky") .object() .onMetadataUpdate(() => null); expect(cloudFunction.__trigger).to.deep.equal(expectedTrigger("bucky", "metadataUpdate")); expect(cloudFunction.__endpoint).to.deep.equal(expectedEndpoint("bucky", "metadataUpdate")); }); it("should use the default bucket when none is provided", () => { const cloudFunction = storage.object().onMetadataUpdate(() => null); expect(cloudFunction.__trigger).to.deep.equal( expectedTrigger(defaultBucket, "metadataUpdate") ); expect(cloudFunction.__endpoint).to.deep.equal( expectedEndpoint(defaultBucket, "metadataUpdate") ); }); it("should allow fully qualified bucket names", () => { const subjectQualified = new storage.ObjectBuilder(() => "projects/_/buckets/bucky", {}); const result = subjectQualified.onMetadataUpdate(() => null); expect(result.__trigger).to.deep.equal(expectedTrigger("bucky", "metadataUpdate")); expect(result.__endpoint).to.deep.equal(expectedEndpoint("bucky", "metadataUpdate")); }); it("should throw with improperly formatted buckets", () => { const fn = storage .bucket("bad/bucket/format") .object() .onMetadataUpdate(() => null); expect(() => fn.__trigger).to.throw(Error); expect(() => fn.__endpoint).to.throw(Error); }); it("should not mess with media links using non-literal slashes", () => { const cloudFunction = storage.object().onMetadataUpdate((data) => { return data.mediaLink; }); const goodMediaLinkEvent = { data: { mediaLink: "path_to_url" + "/o/nestedfolder%2Fanotherfolder%2Fmyobject.file?generation=12345&alt=media", }, context: { eventId: "70172329041928", timestamp: "2018-04-09T07:56:12.975Z", eventType: "google.storage.object.metadataUpdate", resource: { service: "storage.googleapis.com", name: "projects/_/buckets/bucky", }, }, }; return cloudFunction(goodMediaLinkEvent.data, goodMediaLinkEvent.context).then( (result: any) => { expect(result).equals(goodMediaLinkEvent.data.mediaLink); } ); }); }); }); describe("process.env.FIREBASE_CONFIG not set", () => { beforeEach(() => { (config as any).firebaseConfigCache = null; delete process.env.FIREBASE_CONFIG; }); it("should not throw if __trigger is not accessed", () => { expect(() => storage.object().onArchive(() => null)).to.not.throw(Error); }); it("should throw when trigger is accessed", () => { expect(() => storage.object().onArchive(() => null).__trigger).to.throw(Error); }); it("should throw when endpoint is accessed", () => { expect(() => storage.object().onArchive(() => null).__endpoint).to.throw(Error); }); it("should not throw when #run is called", () => { const cf = storage.object().onArchive(() => null); expect(cf.run).to.not.throw(Error); }); }); }); ```
/content/code_sandbox/spec/v1/providers/storage.spec.ts
xml
2016-09-22T23:13:54
2024-08-16T17:59:09
firebase-functions
firebase/firebase-functions
1,015
2,977
```xml export default interface ITourStep { selector: string; content: string; } ```
/content/code_sandbox/samples/react-tour-pnpjs/src/webparts/tour/model/ITourStep.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
19
```xml <?xml version="1.0" encoding="UTF-8"?> <definitions id="taskAssigneeExample" xmlns="path_to_url" xmlns:activiti="path_to_url" targetNamespace="Examples"> <signal id="alertSignal" name="alert" /> <process id="boundaryEventProcess" name="Boundary event process"> <startEvent id="theStart" /> <sequenceFlow id="flow1" sourceRef="theStart" targetRef="theTask" /> <userTask id="theTask" name="Schedule meeting"> </userTask> <boundaryEvent id="boundary" attachedToRef="theTask" cancelActivity="true"> <signalEventDefinition signalRef="alertSignal"/> </boundaryEvent> <sequenceFlow id="flow2" sourceRef="boundary" targetRef="boundaryEnd" /> <endEvent id="boundaryEnd" /> <sequenceFlow id="flow3" sourceRef="theTask" targetRef="theEnd" /> <endEvent id="theEnd" /> </process> </definitions> ```
/content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/engine/test/history/HistoricActivityInstanceTest.testBoundaryEvent.bpmn20.xml
xml
2016-10-13T07:21:43
2024-08-16T15:23:14
flowable-engine
flowable/flowable-engine
7,715
251
```xml /* * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * * path_to_url * * Unless required by applicable law or agreed to in writing, * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * specific language governing permissions and limitations */ import { browser } from 'protractor'; import { LoginPage } from '../PageObjects/LoginPage.po'; import { TopNavigationPage } from '../PageObjects/TopNavigationPage.po'; import { api } from "../config"; import { TopologiesPage } from '../PageObjects/TopologiesPage.po'; import { topologies } from "../Data/topologies"; const loginPage = new LoginPage(); const topologiesPage = new TopologiesPage(); const topNavigation = new TopNavigationPage(); describe('Setup API for Topologies Test', () => { it('Setup', async () => { await api.UseAPI(topologies.setup); }); }); topologies.tests.forEach(async topologiesData =>{ topologiesData.logins.forEach(login =>{ describe(`Traffic Portal - Topologies - ${login.description}`, () => { it('can login', async () => { browser.get(browser.params.baseUrl); await loginPage.Login(login); expect(await loginPage.CheckUserName(login)).toBeTruthy(); }); it('can open topologies page', async () => { await topologiesPage.OpenTopologyMenu(); await topologiesPage.OpenTopologiesPage(); }); topologiesData.add.forEach(add => { it(add.description, async () => { expect(await topologiesPage.CreateTopologies(add)).toBeTruthy(); await topologiesPage.OpenTopologiesPage(); }) }) it('can logout', async function(){ expect(await topNavigation.Logout()).toBeTruthy(); }) }) }) }) describe('Clean Up API for Topologies Test', () => { it('Cleanup', async () => { await api.UseAPI(topologies.cleanup); }); }); ```
/content/code_sandbox/traffic_portal/test/integration/specs/Topologies.spec.ts
xml
2016-09-02T07:00:06
2024-08-16T03:50:21
trafficcontrol
apache/trafficcontrol
1,043
421
```xml import { render } from "@testing-library/react"; import Home from "@/pages/index"; it("renders homepage unchanged", () => { const { container } = render(<Home />); expect(container).toMatchSnapshot(); }); ```
/content/code_sandbox/examples/with-jest-babel/__tests__/snapshot.tsx
xml
2016-10-05T23:32:51
2024-08-16T19:44:30
next.js
vercel/next.js
124,056
44
```xml import { Box, EmptyState, Icon, ModalTrigger, MainStyleButtonRelated as ButtonRelated, __, SectionBodyItem } from "@erxes/ui/src"; import GetConformity from "@erxes/ui-sales/src/conformity/containers/GetConformity"; import React from "react"; import { Link } from "react-router-dom"; import CarChooser from "../../containers/CarChooser"; import { queries } from "../../graphql"; import { ICar } from "../../types"; type Props = { name: string; items?: ICar[]; mainType?: string; mainTypeId?: string; onSelect?: (cars: ICar[]) => void; collapseCallback?: () => void; }; function Component( this: any, { name, items = [], mainType = "", mainTypeId = "", onSelect, collapseCallback }: Props ) { const renderCarChooser = props => { return ( <CarChooser {...props} data={{ name, cars: items, mainType, mainTypeId }} onSelect={onSelect} /> ); }; const renderRelatedCarChooser = props => { return ( <CarChooser {...props} data={{ name, cars: items, mainTypeId, mainType, isRelated: true }} onSelect={onSelect} /> ); }; const carTrigger = ( <button> <Icon icon="plus-circle" /> </button> ); const relCarTrigger = ( <ButtonRelated> <span>{__("See related cars..")}</span> </ButtonRelated> ); const quickButtons = ( <ModalTrigger title="Associate" trigger={carTrigger} size="lg" content={renderCarChooser} /> ); const relQuickButtons = ( <ModalTrigger title="Related Associate" trigger={relCarTrigger} size="lg" content={renderRelatedCarChooser} /> ); const content = () => { if (items.length > 0) { const categoryId = items[0].category?.productCategoryId; localStorage.setItem( "erxes_products:chooser_filter", JSON.stringify({ categoryId }) ); } return ( <> {items.map((car, index) => ( <SectionBodyItem key={index}> <Link to={`/erxes-plugin-car/details/${car._id}`}> <Icon icon="arrow-to-right" /> </Link> <span>{car.plateNumber || "Unknown"}</span> </SectionBodyItem> ))} {items.length === 0 && <EmptyState icon="building" text="No car" />} {mainTypeId && mainType && relQuickButtons} </> ); }; return ( <Box title={__("Cars")} name="showCars" extraButtons={quickButtons} isOpen={true} callback={collapseCallback} > {content()} </Box> ); } type IProps = { mainType?: string; mainTypeId?: string; isOpen?: boolean; cars?: ICar[]; onSelect?: (datas: ICar[]) => void; collapseCallback?: () => void; }; export default (props: IProps) => { return ( <GetConformity {...props} relType="car" component={Component} queryName="cars" itemsQuery={queries.cars} alreadyItems={props.cars} /> ); }; ```
/content/code_sandbox/packages/plugin-cars-ui/src/components/common/CarSection.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
765
```xml import React from "react"; import { useNavigate } from "react-router-dom"; import { Modal, Space } from "antd"; import { useDispatch, useSelector } from "react-redux"; import { PRICING } from "features/pricing/constants/pricing"; import { getFunctions, httpsCallable } from "firebase/functions"; import { RQButton } from "lib/design-system/components"; import { trackCheckoutFailedEvent, trackCheckoutButtonClicked, trackCheckoutInitiated, } from "modules/analytics/events/misc/business/checkout"; import { useState } from "react"; import { actions } from "store"; import { getUserAuthDetails } from "store/selectors"; import { toast } from "utils/Toast"; import { ChangePlanRequestConfirmationModal } from "../ChangePlanRequestConfirmationModal"; import { getPrettyPlanName } from "utils/FormattingHelper"; import { trackPricingPlanCTAClicked } from "modules/analytics/events/misc/business"; import APP_CONSTANTS from "config/constants"; import { redirectToPricingPlans } from "utils/RedirectionUtils"; const CTA_ONCLICK_FUNCTIONS = { MANAGE_SUBSCRIPTION: "manage-subscription", SWITCH_PLAN: "switch-plan", CHECKOUT: "checkout", USE_NOW: "use-now", CONTACT_US: "contact-us", SIGNUP: "signup", }; const CTA_BUTTONS_CONFIG = { signup: { text: "Sign Up", tag: "", onClick: CTA_ONCLICK_FUNCTIONS.SIGNUP, visible: true, }, "use-now": { text: "Use Now", tag: "Current Plan", onClick: CTA_ONCLICK_FUNCTIONS.USE_NOW, visible: true, }, checkout: { text: "Upgrade", tag: "", onClick: CTA_ONCLICK_FUNCTIONS.CHECKOUT, visible: true, }, "not-visible": { text: "Use Now", tag: "", onClick: () => {}, visible: false, }, "current-plan": { text: "", tag: "Current Plan", onClick: () => {}, visible: false, }, "manage-subscription": { text: "Upgrade", tag: "", onClick: CTA_ONCLICK_FUNCTIONS.MANAGE_SUBSCRIPTION, visible: true, }, "switch-plan": { text: "Switch Plan", tag: "", onClick: CTA_ONCLICK_FUNCTIONS.SWITCH_PLAN, visible: true, }, "upgrade-email": { text: "Upgrade", tag: "", onClick: CTA_ONCLICK_FUNCTIONS.SWITCH_PLAN, visible: true, }, "already-included": { text: "", tag: "Already included in team license", onClick: () => {}, visible: false, }, "trial-active": { text: "Upgrade", tag: "30 day trial active", onClick: CTA_ONCLICK_FUNCTIONS.MANAGE_SUBSCRIPTION, visible: true, }, }; // Maps userPlanName -> columnPlanName -> buttonConfig const pricingButtonsMap: Record<string, any> = { default: { [PRICING.PLAN_NAMES.FREE]: { [PRICING.PLAN_NAMES.FREE]: CTA_BUTTONS_CONFIG["use-now"], [PRICING.PLAN_NAMES.LITE]: CTA_BUTTONS_CONFIG.checkout, [PRICING.PLAN_NAMES.BASIC]: CTA_BUTTONS_CONFIG.checkout, [PRICING.PLAN_NAMES.PROFESSIONAL]: CTA_BUTTONS_CONFIG.checkout, }, [PRICING.PLAN_NAMES.LITE]: { [PRICING.PLAN_NAMES.FREE]: CTA_BUTTONS_CONFIG["not-visible"], [PRICING.PLAN_NAMES.LITE]: CTA_BUTTONS_CONFIG["current-plan"], [PRICING.PLAN_NAMES.BASIC]: CTA_BUTTONS_CONFIG["switch-plan"], [PRICING.PLAN_NAMES.PROFESSIONAL]: CTA_BUTTONS_CONFIG["switch-plan"], }, [PRICING.PLAN_NAMES.BASIC]: { [PRICING.PLAN_NAMES.FREE]: CTA_BUTTONS_CONFIG["not-visible"], [PRICING.PLAN_NAMES.LITE]: CTA_BUTTONS_CONFIG["switch-plan"], [PRICING.PLAN_NAMES.BASIC]: CTA_BUTTONS_CONFIG["current-plan"], [PRICING.PLAN_NAMES.PROFESSIONAL]: CTA_BUTTONS_CONFIG["switch-plan"], }, [PRICING.PLAN_NAMES.PROFESSIONAL]: { [PRICING.PLAN_NAMES.FREE]: CTA_BUTTONS_CONFIG["not-visible"], [PRICING.PLAN_NAMES.LITE]: CTA_BUTTONS_CONFIG["switch-plan"], [PRICING.PLAN_NAMES.BASIC]: CTA_BUTTONS_CONFIG["switch-plan"], [PRICING.PLAN_NAMES.PROFESSIONAL]: CTA_BUTTONS_CONFIG["current-plan"], }, }, trial: { [PRICING.PLAN_NAMES.FREE]: CTA_BUTTONS_CONFIG["not-visible"], [PRICING.PLAN_NAMES.LITE]: CTA_BUTTONS_CONFIG["manage-subscription"], [PRICING.PLAN_NAMES.BASIC]: CTA_BUTTONS_CONFIG["manage-subscription"], [PRICING.PLAN_NAMES.PROFESSIONAL]: CTA_BUTTONS_CONFIG["manage-subscription"], }, }; interface PricingTableButtonsProps { columnPlanName: string; product: string; duration: string; source: string; quantity: number; disabled: boolean; setIsContactUsModalOpen: (value: boolean) => void; } export const PricingTableButtons: React.FC<PricingTableButtonsProps> = ({ columnPlanName, product, duration, source, quantity, disabled, setIsContactUsModalOpen, }) => { const dispatch = useDispatch(); const firebaseFunction = getFunctions(); const user = useSelector(getUserAuthDetails); const navigate = useNavigate(); const [isButtonLoading, setIsButtonLoading] = useState(false); const [isConfirmationModalOpen, setIsConfirmationModalOpen] = useState(false); const [isConfirmationModalLoading, setIsConfirmationModalLoading] = useState(false); const isUserPremium = user?.details?.isPremium; const userPlanName = user?.details?.planDetails?.planName ?? PRICING.PLAN_NAMES.FREE; const isUserTrialing = isUserPremium && user?.details?.planDetails?.status === "trialing"; const userPlanType = ["team", "individual"].includes(user?.details?.planDetails?.type) ? user?.details?.planDetails?.type : "individual"; const onButtonClick = (functionName: string) => { trackPricingPlanCTAClicked( { current_plan: `${userPlanName}`, selected_plan: `${columnPlanName}`, action: functionName, quantity, }, source ); setIsButtonLoading(true); if (!user?.details?.isLoggedIn) { dispatch( actions.toggleActiveModal({ modalName: "authModal", newValue: true, newProps: { callback: () => redirectToPricingPlans(navigate), authMode: APP_CONSTANTS.AUTH.ACTION_LABELS.SIGN_UP, eventSource: "pricing_table", }, }) ); setIsButtonLoading(false); return; } switch (functionName) { case CTA_ONCLICK_FUNCTIONS.USE_NOW: { window.location.href = "/"; setIsButtonLoading(false); break; } case CTA_ONCLICK_FUNCTIONS.SIGNUP: { dispatch( actions.toggleActiveModal({ modalName: "authModal", newValue: true, newProps: { authMode: APP_CONSTANTS.AUTH.ACTION_LABELS.SIGN_UP, callback: () => redirectToPricingPlans(navigate), eventSource: "pricing_table", }, }) ); setIsButtonLoading(false); break; } case CTA_ONCLICK_FUNCTIONS.CHECKOUT: { trackCheckoutButtonClicked(duration, columnPlanName, quantity, isUserTrialing, source); dispatch( actions.toggleActiveModal({ modalName: "pricingModal", newValue: true, newProps: { selectedPlan: columnPlanName, planDuration: duration, quantity, source, }, }) ); setIsButtonLoading(false); break; } case CTA_ONCLICK_FUNCTIONS.MANAGE_SUBSCRIPTION: { trackCheckoutButtonClicked(duration, columnPlanName, quantity, isUserTrialing, source); const manageSubscription = httpsCallable(firebaseFunction, "subscription-manageSubscription"); manageSubscription({ planName: columnPlanName, duration, portalFlowType: "update_subscription", }) .then((res: any) => { if (res?.data?.success) { window.location.href = res?.data?.data?.portalUrl; trackCheckoutInitiated({ plan_name: columnPlanName, duration, currency: "usd", quantity: quantity, is_user_on_trial: isUserTrialing, source, }); } }) .catch((err) => { toast.error("Error in managing subscription. Please contact support contact@requestly.io"); trackCheckoutFailedEvent(quantity, source); }) .finally(() => { setIsButtonLoading(false); }); break; } case CTA_ONCLICK_FUNCTIONS.SWITCH_PLAN: { Modal.confirm({ title: "Switch Plan", content: `You are about to switch from ${getPrettyPlanName(userPlanName)} plan to ${getPrettyPlanName( columnPlanName )} plan.`, okText: "Yes", okType: "primary", cancelText: "No", onOk: () => { setIsConfirmationModalOpen(true); setIsConfirmationModalLoading(true); const requestPlanSwitch = httpsCallable(firebaseFunction, "premiumNotifications-requestPlanSwitch"); requestPlanSwitch({ currentPlan: userPlanName, planToSwitch: columnPlanName, currentPlanType: userPlanType, }) .catch(() => { toast.error("Error in switching plan. Please contact support"); setIsConfirmationModalOpen(false); }) .finally(() => { setIsConfirmationModalLoading(false); setIsButtonLoading(false); }); }, onCancel: () => { setIsButtonLoading(false); }, }); break; } case CTA_ONCLICK_FUNCTIONS.CONTACT_US: { setIsContactUsModalOpen(true); break; } default: { setIsButtonLoading(false); } } }; let buttonConfig = pricingButtonsMap.default[userPlanName][columnPlanName]; if (buttonConfig?.onClick === CTA_ONCLICK_FUNCTIONS.USE_NOW && !user?.details?.isLoggedIn) { buttonConfig = CTA_BUTTONS_CONFIG["signup"]; } if (isUserTrialing) { buttonConfig = pricingButtonsMap.trial[columnPlanName]; if (quantity > 1) { buttonConfig = CTA_BUTTONS_CONFIG["checkout"]; } } if (product === PRICING.PRODUCTS.SESSION_REPLAY) { if (columnPlanName === PRICING.PLAN_NAMES.FREE) { return ( <Space size={8}> <RQButton onClick={() => (window.location.href = "/")} type="primary"> Use now </RQButton> <div className="current-pricing-plan-tag">Current Plan</div> </Space> ); } return ( <RQButton onClick={() => { onButtonClick(CTA_ONCLICK_FUNCTIONS.CONTACT_US); }} type="primary" > Contact us </RQButton> ); } if (columnPlanName === PRICING.PLAN_NAMES.ENTERPRISE) { return ( <RQButton onClick={() => { onButtonClick(CTA_ONCLICK_FUNCTIONS.CONTACT_US); }} type="primary" > Schedule a call </RQButton> ); } return ( <> <Space size={8}> {buttonConfig?.text && ( <RQButton onClick={() => { onButtonClick(buttonConfig.onClick); }} type="primary" className={!buttonConfig.visible ? "visibility-hidden" : ""} loading={isButtonLoading} disabled={disabled} > {buttonConfig?.text} </RQButton> )} {buttonConfig.tag && <div className="current-pricing-plan-tag">{buttonConfig.tag}</div>} </Space> <ChangePlanRequestConfirmationModal isOpen={isConfirmationModalOpen} handleToggle={() => setIsConfirmationModalOpen(false)} isLoading={isConfirmationModalLoading} /> </> ); }; ```
/content/code_sandbox/app/src/features/pricing/components/PricingTable/PricingTableButtons.tsx
xml
2016-12-01T04:36:06
2024-08-16T19:12:19
requestly
requestly/requestly
2,121
2,764
```xml //===-- MachProcess.cpp -----------------------------------------*- C++ -*-===// // // See path_to_url for license information. // //===your_sha256_hash------===// // // Created by Greg Clayton on 6/15/07. // //===your_sha256_hash------===// #include "DNB.h" #include "MacOSX/CFUtils.h" #include "SysSignal.h" #include <dlfcn.h> #include <inttypes.h> #include <mach-o/loader.h> #include <mach/mach.h> #include <mach/task.h> #include <pthread.h> #include <signal.h> #include <spawn.h> #include <sys/fcntl.h> #include <sys/ptrace.h> #include <sys/stat.h> #include <sys/sysctl.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <uuid/uuid.h> #include <algorithm> #include <chrono> #include <map> #include <TargetConditionals.h> #import <Foundation/Foundation.h> #include "DNBDataRef.h" #include "DNBLog.h" #include "DNBThreadResumeActions.h" #include "DNBTimer.h" #include "MachProcess.h" #include "PseudoTerminal.h" #include "CFBundle.h" #include "CFString.h" #ifndef PLATFORM_BRIDGEOS #define PLATFORM_BRIDGEOS 5 #endif #ifndef PLATFORM_MACCATALYST #define PLATFORM_MACCATALYST 6 #endif #ifndef PLATFORM_IOSSIMULATOR #define PLATFORM_IOSSIMULATOR 7 #endif #ifndef PLATFORM_TVOSSIMULATOR #define PLATFORM_TVOSSIMULATOR 8 #endif #ifndef PLATFORM_WATCHOSSIMULATOR #define PLATFORM_WATCHOSSIMULATOR 9 #endif #ifndef PLATFORM_DRIVERKIT #define PLATFORM_DRIVERKIT 10 #endif #ifdef WITH_SPRINGBOARD #include <CoreFoundation/CoreFoundation.h> #include <SpringBoardServices/SBSWatchdogAssertion.h> #include <SpringBoardServices/SpringBoardServer.h> #endif // WITH_SPRINGBOARD #if WITH_CAROUSEL // For definition of CSLSOpenApplicationOptionForClockKit. #include <CarouselServices/CSLSOpenApplicationOptions.h> #endif // WITH_CAROUSEL #if defined(WITH_SPRINGBOARD) || defined(WITH_BKS) || defined(WITH_FBS) // This returns a CFRetained pointer to the Bundle ID for app_bundle_path, // or NULL if there was some problem getting the bundle id. static CFStringRef CopyBundleIDForPath(const char *app_bundle_path, DNBError &err_str); #endif #if defined(WITH_BKS) || defined(WITH_FBS) #import <Foundation/Foundation.h> static const int OPEN_APPLICATION_TIMEOUT_ERROR = 111; typedef void (*SetErrorFunction)(NSInteger, std::string, DNBError &); typedef bool (*CallOpenApplicationFunction)(NSString *bundleIDNSStr, NSDictionary *options, DNBError &error, pid_t *return_pid); // This function runs the BKSSystemService (or FBSSystemService) method // openApplication:options:clientPort:withResult, // messaging the app passed in bundleIDNSStr. // The function should be run inside of an NSAutoReleasePool. // // It will use the "options" dictionary passed in, and fill the error passed in // if there is an error. // If return_pid is not NULL, we'll fetch the pid that was made for the // bundleID. // If bundleIDNSStr is NULL, then the system application will be messaged. template <typename OpenFlavor, typename ErrorFlavor, ErrorFlavor no_error_enum_value, SetErrorFunction error_function> static bool CallBoardSystemServiceOpenApplication(NSString *bundleIDNSStr, NSDictionary *options, DNBError &error, pid_t *return_pid) { // Now make our systemService: OpenFlavor *system_service = [[OpenFlavor alloc] init]; if (bundleIDNSStr == nil) { bundleIDNSStr = [system_service systemApplicationBundleIdentifier]; if (bundleIDNSStr == nil) { // Okay, no system app... error.SetErrorString("No system application to message."); return false; } } mach_port_t client_port = [system_service createClientPort]; __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); __block ErrorFlavor open_app_error = no_error_enum_value; __block std::string open_app_error_string; bool wants_pid = (return_pid != NULL); __block pid_t pid_in_block; const char *cstr = [bundleIDNSStr UTF8String]; if (!cstr) cstr = "<Unknown Bundle ID>"; NSString *description = [options description]; DNBLog("[LaunchAttach] START (%d) templated *Board launcher: app lunch " "request for " "'%s' - options:\n%s", getpid(), cstr, [description UTF8String]); [system_service openApplication:bundleIDNSStr options:options clientPort:client_port withResult:^(NSError *bks_error) { // The system service will cleanup the client port we created for // us. if (bks_error) open_app_error = (ErrorFlavor)[bks_error code]; if (open_app_error == no_error_enum_value) { if (wants_pid) { pid_in_block = [system_service pidForApplication:bundleIDNSStr]; DNBLog("[LaunchAttach] In completion handler, got pid for " "bundle id " "'%s', pid: %d.", cstr, pid_in_block); } else { DNBLog("[LaunchAttach] In completion handler, launch was " "successful, " "debugserver did not ask for the pid"); } } else { const char *error_str = [(NSString *)[bks_error localizedDescription] UTF8String]; if (error_str) { open_app_error_string = error_str; DNBLogError( "[LaunchAttach] END (%d) In app launch attempt, got error " "localizedDescription '%s'.", getpid(), error_str); const char *obj_desc = [NSString stringWithFormat:@"%@", bks_error].UTF8String; DNBLogError( "[LaunchAttach] END (%d) In app launch attempt, got error " "NSError object description: '%s'.", getpid(), obj_desc); } DNBLogThreadedIf(LOG_PROCESS, "In completion handler for send " "event, got error \"%s\"(%ld).", error_str ? error_str : "<unknown error>", (long)open_app_error); } [system_service release]; dispatch_semaphore_signal(semaphore); } ]; const uint32_t timeout_secs = 30; dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, timeout_secs * NSEC_PER_SEC); long success = dispatch_semaphore_wait(semaphore, timeout) == 0; dispatch_release(semaphore); DNBLog("[LaunchAttach] END (%d) templated *Board launcher finished app lunch " "request for " "'%s'", getpid(), cstr); if (!success) { DNBLogError("[LaunchAttach] END (%d) timed out trying to send " "openApplication to %s.", getpid(), cstr); error.SetError(OPEN_APPLICATION_TIMEOUT_ERROR, DNBError::Generic); error.SetErrorString("timed out trying to launch app"); } else if (open_app_error != no_error_enum_value) { error_function(open_app_error, open_app_error_string, error); DNBLogError("[LaunchAttach] END (%d) unable to launch the application with " "CFBundleIdentifier '%s' " "bks_error = %ld", getpid(), cstr, (long)open_app_error); success = false; } else if (wants_pid) { *return_pid = pid_in_block; DNBLogThreadedIf( LOG_PROCESS, "Out of completion handler, pid from block %d and passing out: %d", pid_in_block, *return_pid); } return success; } #endif #if defined(WITH_BKS) || defined(WITH_FBS) static void SplitEventData(const char *data, std::vector<std::string> &elements) { elements.clear(); if (!data) return; const char *start = data; while (*start != '\0') { const char *token = strchr(start, ':'); if (!token) { elements.push_back(std::string(start)); return; } if (token != start) elements.push_back(std::string(start, token - start)); start = ++token; } } #endif #ifdef WITH_BKS #import <Foundation/Foundation.h> extern "C" { #import <BackBoardServices/BKSOpenApplicationConstants_Private.h> #import <BackBoardServices/BKSSystemService_LaunchServices.h> #import <BackBoardServices/BackBoardServices.h> } static bool IsBKSProcess(nub_process_t pid) { BKSApplicationStateMonitor *state_monitor = [[BKSApplicationStateMonitor alloc] init]; BKSApplicationState app_state = [state_monitor mostElevatedApplicationStateForPID:pid]; return app_state != BKSApplicationStateUnknown; } static void SetBKSError(NSInteger error_code, std::string error_description, DNBError &error) { error.SetError(error_code, DNBError::BackBoard); NSString *err_nsstr = ::BKSOpenApplicationErrorCodeToString( (BKSOpenApplicationErrorCode)error_code); std::string err_str = "unknown BKS error"; if (error_description.empty() == false) { err_str = error_description; } else if (err_nsstr != nullptr) { err_str = [err_nsstr UTF8String]; } error.SetErrorString(err_str.c_str()); } static bool BKSAddEventDataToOptions(NSMutableDictionary *options, const char *event_data, DNBError &option_error) { std::vector<std::string> values; SplitEventData(event_data, values); bool found_one = false; for (std::string value : values) { if (value.compare("BackgroundContentFetching") == 0) { DNBLog("Setting ActivateForEvent key in options dictionary."); NSDictionary *event_details = [NSDictionary dictionary]; NSDictionary *event_dictionary = [NSDictionary dictionaryWithObject:event_details forKey: BKSActivateForEventOptionTypeBackgroundContentFetching]; [options setObject:event_dictionary forKey:BKSOpenApplicationOptionKeyActivateForEvent]; found_one = true; } else if (value.compare("ActivateSuspended") == 0) { DNBLog("Setting ActivateSuspended key in options dictionary."); [options setObject:@YES forKey: BKSOpenApplicationOptionKeyActivateSuspended]; found_one = true; } else { DNBLogError("Unrecognized event type: %s. Ignoring.", value.c_str()); option_error.SetErrorString("Unrecognized event data"); } } return found_one; } static NSMutableDictionary *BKSCreateOptionsDictionary( const char *app_bundle_path, NSMutableArray *launch_argv, NSMutableDictionary *launch_envp, NSString *stdio_path, bool disable_aslr, const char *event_data) { NSMutableDictionary *debug_options = [NSMutableDictionary dictionary]; if (launch_argv != nil) [debug_options setObject:launch_argv forKey:BKSDebugOptionKeyArguments]; if (launch_envp != nil) [debug_options setObject:launch_envp forKey:BKSDebugOptionKeyEnvironment]; [debug_options setObject:stdio_path forKey:BKSDebugOptionKeyStandardOutPath]; [debug_options setObject:stdio_path forKey:BKSDebugOptionKeyStandardErrorPath]; [debug_options setObject:[NSNumber numberWithBool:YES] forKey:BKSDebugOptionKeyWaitForDebugger]; if (disable_aslr) [debug_options setObject:[NSNumber numberWithBool:YES] forKey:BKSDebugOptionKeyDisableASLR]; // That will go in the overall dictionary: NSMutableDictionary *options = [NSMutableDictionary dictionary]; [options setObject:debug_options forKey:BKSOpenApplicationOptionKeyDebuggingOptions]; // And there are some other options at the top level in this dictionary: [options setObject:[NSNumber numberWithBool:YES] forKey:BKSOpenApplicationOptionKeyUnlockDevice]; DNBError error; BKSAddEventDataToOptions(options, event_data, error); return options; } static CallOpenApplicationFunction BKSCallOpenApplicationFunction = CallBoardSystemServiceOpenApplication< BKSSystemService, BKSOpenApplicationErrorCode, BKSOpenApplicationErrorCodeNone, SetBKSError>; #endif // WITH_BKS #ifdef WITH_FBS #import <Foundation/Foundation.h> extern "C" { #import <FrontBoardServices/FBSOpenApplicationConstants_Private.h> #import <FrontBoardServices/FBSSystemService_LaunchServices.h> #import <FrontBoardServices/FrontBoardServices.h> #import <MobileCoreServices/LSResourceProxy.h> #import <MobileCoreServices/MobileCoreServices.h> } #ifdef WITH_BKS static bool IsFBSProcess(nub_process_t pid) { BKSApplicationStateMonitor *state_monitor = [[BKSApplicationStateMonitor alloc] init]; BKSApplicationState app_state = [state_monitor mostElevatedApplicationStateForPID:pid]; return app_state != BKSApplicationStateUnknown; } #else static bool IsFBSProcess(nub_process_t pid) { // FIXME: What is the FBS equivalent of BKSApplicationStateMonitor return false; } #endif static void SetFBSError(NSInteger error_code, std::string error_description, DNBError &error) { error.SetError((DNBError::ValueType)error_code, DNBError::FrontBoard); NSString *err_nsstr = ::FBSOpenApplicationErrorCodeToString( (FBSOpenApplicationErrorCode)error_code); std::string err_str = "unknown FBS error"; if (error_description.empty() == false) { err_str = error_description; } else if (err_nsstr != nullptr) { err_str = [err_nsstr UTF8String]; } error.SetErrorString(err_str.c_str()); } static bool FBSAddEventDataToOptions(NSMutableDictionary *options, const char *event_data, DNBError &option_error) { std::vector<std::string> values; SplitEventData(event_data, values); bool found_one = false; for (std::string value : values) { if (value.compare("BackgroundContentFetching") == 0) { DNBLog("Setting ActivateForEvent key in options dictionary."); NSDictionary *event_details = [NSDictionary dictionary]; NSDictionary *event_dictionary = [NSDictionary dictionaryWithObject:event_details forKey: FBSActivateForEventOptionTypeBackgroundContentFetching]; [options setObject:event_dictionary forKey:FBSOpenApplicationOptionKeyActivateForEvent]; found_one = true; } else if (value.compare("ActivateSuspended") == 0) { DNBLog("Setting ActivateSuspended key in options dictionary."); [options setObject:@YES forKey: FBSOpenApplicationOptionKeyActivateSuspended]; found_one = true; #if WITH_CAROUSEL } else if (value.compare("WatchComplicationLaunch") == 0) { DNBLog("Setting FBSOpenApplicationOptionKeyActivateSuspended key in options dictionary."); [options setObject:@YES forKey: CSLSOpenApplicationOptionForClockKit]; found_one = true; #endif // WITH_CAROUSEL } else { DNBLogError("Unrecognized event type: %s. Ignoring.", value.c_str()); option_error.SetErrorString("Unrecognized event data."); } } return found_one; } static NSMutableDictionary * FBSCreateOptionsDictionary(const char *app_bundle_path, NSMutableArray *launch_argv, NSDictionary *launch_envp, NSString *stdio_path, bool disable_aslr, const char *event_data) { NSMutableDictionary *debug_options = [NSMutableDictionary dictionary]; if (launch_argv != nil) [debug_options setObject:launch_argv forKey:FBSDebugOptionKeyArguments]; if (launch_envp != nil) [debug_options setObject:launch_envp forKey:FBSDebugOptionKeyEnvironment]; [debug_options setObject:stdio_path forKey:FBSDebugOptionKeyStandardOutPath]; [debug_options setObject:stdio_path forKey:FBSDebugOptionKeyStandardErrorPath]; [debug_options setObject:[NSNumber numberWithBool:YES] forKey:FBSDebugOptionKeyWaitForDebugger]; if (disable_aslr) [debug_options setObject:[NSNumber numberWithBool:YES] forKey:FBSDebugOptionKeyDisableASLR]; // That will go in the overall dictionary: NSMutableDictionary *options = [NSMutableDictionary dictionary]; [options setObject:debug_options forKey:FBSOpenApplicationOptionKeyDebuggingOptions]; // And there are some other options at the top level in this dictionary: [options setObject:[NSNumber numberWithBool:YES] forKey:FBSOpenApplicationOptionKeyUnlockDevice]; // We have to get the "sequence ID & UUID" for this app bundle path and send // them to FBS: NSURL *app_bundle_url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:app_bundle_path] isDirectory:YES]; LSApplicationProxy *app_proxy = [LSApplicationProxy applicationProxyForBundleURL:app_bundle_url]; if (app_proxy) { DNBLog("Sending AppProxy info: sequence no: %lu, GUID: %s.", app_proxy.sequenceNumber, [app_proxy.cacheGUID.UUIDString UTF8String]); [options setObject:[NSNumber numberWithUnsignedInteger:app_proxy.sequenceNumber] forKey:FBSOpenApplicationOptionKeyLSSequenceNumber]; [options setObject:app_proxy.cacheGUID.UUIDString forKey:FBSOpenApplicationOptionKeyLSCacheGUID]; } DNBError error; FBSAddEventDataToOptions(options, event_data, error); return options; } static CallOpenApplicationFunction FBSCallOpenApplicationFunction = CallBoardSystemServiceOpenApplication< FBSSystemService, FBSOpenApplicationErrorCode, FBSOpenApplicationErrorCodeNone, SetFBSError>; #endif // WITH_FBS #if 0 #define DEBUG_LOG(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define DEBUG_LOG(fmt, ...) #endif #ifndef MACH_PROCESS_USE_POSIX_SPAWN #define MACH_PROCESS_USE_POSIX_SPAWN 1 #endif #ifndef _POSIX_SPAWN_DISABLE_ASLR #define _POSIX_SPAWN_DISABLE_ASLR 0x0100 #endif MachProcess::MachProcess() : m_pid(0), m_cpu_type(0), m_child_stdin(-1), m_child_stdout(-1), m_child_stderr(-1), m_path(), m_args(), m_task(this), m_flags(eMachProcessFlagsNone), m_stdio_thread(0), m_stdio_mutex(PTHREAD_MUTEX_RECURSIVE), m_stdout_data(), m_profile_enabled(false), m_profile_interval_usec(0), m_profile_thread(0), m_profile_data_mutex(PTHREAD_MUTEX_RECURSIVE), m_profile_data(), m_profile_events(0, eMachProcessProfileCancel), m_thread_actions(), m_exception_messages(), m_exception_messages_mutex(PTHREAD_MUTEX_RECURSIVE), m_thread_list(), m_activities(), m_state(eStateUnloaded), m_state_mutex(PTHREAD_MUTEX_RECURSIVE), m_events(0, kAllEventsMask), m_private_events(0, kAllEventsMask), m_breakpoints(), m_watchpoints(), m_name_to_addr_callback(NULL), m_name_to_addr_baton(NULL), m_image_infos_callback(NULL), m_image_infos_baton(NULL), m_sent_interrupt_signo(0), m_auto_resume_signo(0), m_did_exec(false), m_dyld_process_info_create(nullptr), m_dyld_process_info_for_each_image(nullptr), m_dyld_process_info_release(nullptr), m_dyld_process_info_get_cache(nullptr), m_dyld_process_info_get_state(nullptr) { m_dyld_process_info_create = (void *(*)(task_t task, uint64_t timestamp, kern_return_t * kernelError)) dlsym(RTLD_DEFAULT, "_dyld_process_info_create"); m_dyld_process_info_for_each_image = (void (*)(void *info, void (^)(uint64_t machHeaderAddress, const uuid_t uuid, const char *path))) dlsym(RTLD_DEFAULT, "_dyld_process_info_for_each_image"); m_dyld_process_info_release = (void (*)(void *info))dlsym(RTLD_DEFAULT, "_dyld_process_info_release"); m_dyld_process_info_get_cache = (void (*)(void *info, void *cacheInfo))dlsym( RTLD_DEFAULT, "_dyld_process_info_get_cache"); m_dyld_process_info_get_platform = (uint32_t (*)(void *info))dlsym( RTLD_DEFAULT, "_dyld_process_info_get_platform"); m_dyld_process_info_get_state = (void (*)(void *info, void *stateInfo))dlsym( RTLD_DEFAULT, "_dyld_process_info_get_state"); DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__); } MachProcess::~MachProcess() { DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__); Clear(); } pid_t MachProcess::SetProcessID(pid_t pid) { // Free any previous process specific data or resources Clear(); // Set the current PID appropriately if (pid == 0) m_pid = ::getpid(); else m_pid = pid; return m_pid; // Return actually PID in case a zero pid was passed in } nub_state_t MachProcess::GetState() { // If any other threads access this we will need a mutex for it PTHREAD_MUTEX_LOCKER(locker, m_state_mutex); return m_state; } const char *MachProcess::ThreadGetName(nub_thread_t tid) { return m_thread_list.GetName(tid); } nub_state_t MachProcess::ThreadGetState(nub_thread_t tid) { return m_thread_list.GetState(tid); } nub_size_t MachProcess::GetNumThreads() const { return m_thread_list.NumThreads(); } nub_thread_t MachProcess::GetThreadAtIndex(nub_size_t thread_idx) const { return m_thread_list.ThreadIDAtIndex(thread_idx); } nub_thread_t MachProcess::GetThreadIDForMachPortNumber(thread_t mach_port_number) const { return m_thread_list.GetThreadIDByMachPortNumber(mach_port_number); } nub_bool_t MachProcess::SyncThreadState(nub_thread_t tid) { MachThreadSP thread_sp(m_thread_list.GetThreadByID(tid)); if (!thread_sp) return false; kern_return_t kret = ::thread_abort_safely(thread_sp->MachPortNumber()); DNBLogThreadedIf(LOG_THREAD, "thread = 0x%8.8" PRIx32 " calling thread_abort_safely (tid) => %u " "(GetGPRState() for stop_count = %u)", thread_sp->MachPortNumber(), kret, thread_sp->Process()->StopCount()); if (kret == KERN_SUCCESS) return true; else return false; } ThreadInfo::QoS MachProcess::GetRequestedQoS(nub_thread_t tid, nub_addr_t tsd, uint64_t dti_qos_class_index) { return m_thread_list.GetRequestedQoS(tid, tsd, dti_qos_class_index); } nub_addr_t MachProcess::GetPThreadT(nub_thread_t tid) { return m_thread_list.GetPThreadT(tid); } nub_addr_t MachProcess::GetDispatchQueueT(nub_thread_t tid) { return m_thread_list.GetDispatchQueueT(tid); } nub_addr_t MachProcess::GetTSDAddressForThread( nub_thread_t tid, uint64_t plo_pthread_tsd_base_address_offset, uint64_t plo_pthread_tsd_base_offset, uint64_t plo_pthread_tsd_entry_size) { return m_thread_list.GetTSDAddressForThread( tid, plo_pthread_tsd_base_address_offset, plo_pthread_tsd_base_offset, plo_pthread_tsd_entry_size); } MachProcess::DeploymentInfo MachProcess::GetDeploymentInfo(const struct load_command &lc, uint64_t load_command_address, bool is_executable) { DeploymentInfo info; uint32_t cmd = lc.cmd & ~LC_REQ_DYLD; // Handle the older LC_VERSION load commands, which don't // distinguish between simulator and real hardware. auto handle_version_min = [&](char platform) { struct version_min_command vers_cmd; if (ReadMemory(load_command_address, sizeof(struct version_min_command), &vers_cmd) != sizeof(struct version_min_command)) return; info.platform = platform; info.major_version = vers_cmd.version >> 16; info.minor_version = (vers_cmd.version >> 8) & 0xffu; info.patch_version = vers_cmd.version & 0xffu; // Disambiguate legacy simulator platforms. #if (defined(__x86_64__) || defined(__i386__)) // If we are running on Intel macOS, it is safe to assume this is // really a back-deploying simulator binary. switch (info.platform) { case PLATFORM_IOS: info.platform = PLATFORM_IOSSIMULATOR; break; case PLATFORM_TVOS: info.platform = PLATFORM_TVOSSIMULATOR; break; case PLATFORM_WATCHOS: info.platform = PLATFORM_WATCHOSSIMULATOR; break; } #else // On an Apple Silicon macOS host, there is no ambiguity. The only // binaries that use legacy load commands are back-deploying // native iOS binaries. All simulator binaries use the newer, // unambiguous LC_BUILD_VERSION load commands. #endif }; switch (cmd) { case LC_VERSION_MIN_IPHONEOS: handle_version_min(PLATFORM_IOS); break; case LC_VERSION_MIN_MACOSX: handle_version_min(PLATFORM_MACOS); break; case LC_VERSION_MIN_TVOS: handle_version_min(PLATFORM_TVOS); break; case LC_VERSION_MIN_WATCHOS: handle_version_min(PLATFORM_WATCHOS); break; #if defined(LC_BUILD_VERSION) case LC_BUILD_VERSION: { struct build_version_command build_vers; if (ReadMemory(load_command_address, sizeof(struct build_version_command), &build_vers) != sizeof(struct build_version_command)) break; info.platform = build_vers.platform; info.major_version = build_vers.minos >> 16; info.minor_version = (build_vers.minos >> 8) & 0xffu; info.patch_version = build_vers.minos & 0xffu; break; } #endif } // The xctest binary is a pure macOS binary but is launched with // DYLD_FORCE_PLATFORM=6. In that case, force the platform to // macCatalyst and use the macCatalyst version of the host OS // instead of the macOS deployment target. if (is_executable && GetPlatform() == PLATFORM_MACCATALYST) { info.platform = PLATFORM_MACCATALYST; std::string catalyst_version = GetMacCatalystVersionString(); const char *major = catalyst_version.c_str(); char *minor = nullptr; char *patch = nullptr; info.major_version = std::strtoul(major, &minor, 10); info.minor_version = 0; info.patch_version = 0; if (minor && *minor == '.') { info.minor_version = std::strtoul(++minor, &patch, 10); if (patch && *patch == '.') info.patch_version = std::strtoul(++patch, nullptr, 10); } } return info; } std::optional<std::string> MachProcess::GetPlatformString(unsigned char platform) { switch (platform) { case PLATFORM_MACOS: return "macosx"; case PLATFORM_MACCATALYST: return "maccatalyst"; case PLATFORM_IOS: return "ios"; case PLATFORM_IOSSIMULATOR: return "iossimulator"; case PLATFORM_TVOS: return "tvos"; case PLATFORM_TVOSSIMULATOR: return "tvossimulator"; case PLATFORM_WATCHOS: return "watchos"; case PLATFORM_WATCHOSSIMULATOR: return "watchossimulator"; case PLATFORM_BRIDGEOS: return "bridgeos"; case PLATFORM_DRIVERKIT: return "driverkit"; default: DNBLogError("Unknown platform %u found for one binary", platform); return std::nullopt; } } static bool mach_header_validity_test(uint32_t magic, uint32_t cputype) { if (magic != MH_MAGIC && magic != MH_CIGAM && magic != MH_MAGIC_64 && magic != MH_CIGAM_64) return false; if (cputype != CPU_TYPE_I386 && cputype != CPU_TYPE_X86_64 && cputype != CPU_TYPE_ARM && cputype != CPU_TYPE_ARM64 && cputype != CPU_TYPE_ARM64_32) return false; return true; } // Given an address, read the mach-o header and load commands out of memory to // fill in // the mach_o_information "inf" object. // // Returns false if there was an error in reading this mach-o file header/load // commands. bool MachProcess::GetMachOInformationFromMemory( uint32_t dyld_platform, nub_addr_t mach_o_header_addr, int wordsize, struct mach_o_information &inf) { uint64_t load_cmds_p; if (wordsize == 4) { struct mach_header header; if (ReadMemory(mach_o_header_addr, sizeof(struct mach_header), &header) != sizeof(struct mach_header)) { return false; } if (!mach_header_validity_test(header.magic, header.cputype)) return false; load_cmds_p = mach_o_header_addr + sizeof(struct mach_header); inf.mach_header.magic = header.magic; inf.mach_header.cputype = header.cputype; // high byte of cpusubtype is used for "capability bits", v. // CPU_SUBTYPE_MASK, CPU_SUBTYPE_LIB64 in machine.h inf.mach_header.cpusubtype = header.cpusubtype & 0x00ffffff; inf.mach_header.filetype = header.filetype; inf.mach_header.ncmds = header.ncmds; inf.mach_header.sizeofcmds = header.sizeofcmds; inf.mach_header.flags = header.flags; } else { struct mach_header_64 header; if (ReadMemory(mach_o_header_addr, sizeof(struct mach_header_64), &header) != sizeof(struct mach_header_64)) { return false; } if (!mach_header_validity_test(header.magic, header.cputype)) return false; load_cmds_p = mach_o_header_addr + sizeof(struct mach_header_64); inf.mach_header.magic = header.magic; inf.mach_header.cputype = header.cputype; // high byte of cpusubtype is used for "capability bits", v. // CPU_SUBTYPE_MASK, CPU_SUBTYPE_LIB64 in machine.h inf.mach_header.cpusubtype = header.cpusubtype & 0x00ffffff; inf.mach_header.filetype = header.filetype; inf.mach_header.ncmds = header.ncmds; inf.mach_header.sizeofcmds = header.sizeofcmds; inf.mach_header.flags = header.flags; } for (uint32_t j = 0; j < inf.mach_header.ncmds; j++) { struct load_command lc; if (ReadMemory(load_cmds_p, sizeof(struct load_command), &lc) != sizeof(struct load_command)) { return false; } if (lc.cmd == LC_SEGMENT) { struct segment_command seg; if (ReadMemory(load_cmds_p, sizeof(struct segment_command), &seg) != sizeof(struct segment_command)) { return false; } struct mach_o_segment this_seg; char name[17]; ::memset(name, 0, sizeof(name)); memcpy(name, seg.segname, sizeof(seg.segname)); this_seg.name = name; this_seg.vmaddr = seg.vmaddr; this_seg.vmsize = seg.vmsize; this_seg.fileoff = seg.fileoff; this_seg.filesize = seg.filesize; this_seg.maxprot = seg.maxprot; this_seg.initprot = seg.initprot; this_seg.nsects = seg.nsects; this_seg.flags = seg.flags; inf.segments.push_back(this_seg); if (this_seg.name == "ExecExtraSuspend") m_task.TaskWillExecProcessesSuspended(); } if (lc.cmd == LC_SEGMENT_64) { struct segment_command_64 seg; if (ReadMemory(load_cmds_p, sizeof(struct segment_command_64), &seg) != sizeof(struct segment_command_64)) { return false; } struct mach_o_segment this_seg; char name[17]; ::memset(name, 0, sizeof(name)); memcpy(name, seg.segname, sizeof(seg.segname)); this_seg.name = name; this_seg.vmaddr = seg.vmaddr; this_seg.vmsize = seg.vmsize; this_seg.fileoff = seg.fileoff; this_seg.filesize = seg.filesize; this_seg.maxprot = seg.maxprot; this_seg.initprot = seg.initprot; this_seg.nsects = seg.nsects; this_seg.flags = seg.flags; inf.segments.push_back(this_seg); if (this_seg.name == "ExecExtraSuspend") m_task.TaskWillExecProcessesSuspended(); } if (lc.cmd == LC_UUID) { struct uuid_command uuidcmd; if (ReadMemory(load_cmds_p, sizeof(struct uuid_command), &uuidcmd) == sizeof(struct uuid_command)) uuid_copy(inf.uuid, uuidcmd.uuid); } if (DeploymentInfo deployment_info = GetDeploymentInfo( lc, load_cmds_p, inf.mach_header.filetype == MH_EXECUTE)) { std::optional<std::string> lc_platform = GetPlatformString(deployment_info.platform); if (dyld_platform != PLATFORM_MACCATALYST && inf.min_version_os_name == "macosx") { // macCatalyst support. // // This the special case of "zippered" frameworks that have both // a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command. // // When we are in this block, this is a binary with both // PLATFORM_MACOS and PLATFORM_MACCATALYST load commands and // the process is not running as PLATFORM_MACCATALYST. Stick // with the "macosx" load command that we've already // processed, ignore this one, which is presumed to be a // PLATFORM_MACCATALYST one. } else { inf.min_version_os_name = lc_platform.value_or(""); inf.min_version_os_version = ""; inf.min_version_os_version += std::to_string(deployment_info.major_version); inf.min_version_os_version += "."; inf.min_version_os_version += std::to_string(deployment_info.minor_version); if (deployment_info.patch_version != 0) { inf.min_version_os_version += "."; inf.min_version_os_version += std::to_string(deployment_info.patch_version); } } } load_cmds_p += lc.cmdsize; } return true; } // Given completely filled in array of binary_image_information structures, // create a JSONGenerator object // with all the details we want to send to lldb. JSONGenerator::ObjectSP MachProcess::FormatDynamicLibrariesIntoJSON( const std::vector<struct binary_image_information> &image_infos) { JSONGenerator::ArraySP image_infos_array_sp(new JSONGenerator::Array()); const size_t image_count = image_infos.size(); for (size_t i = 0; i < image_count; i++) { if (!image_infos[i].is_valid_mach_header) continue; JSONGenerator::DictionarySP image_info_dict_sp( new JSONGenerator::Dictionary()); image_info_dict_sp->AddIntegerItem("load_address", image_infos[i].load_address); image_info_dict_sp->AddIntegerItem("mod_date", image_infos[i].mod_date); image_info_dict_sp->AddStringItem("pathname", image_infos[i].filename); uuid_string_t uuidstr; uuid_unparse_upper(image_infos[i].macho_info.uuid, uuidstr); image_info_dict_sp->AddStringItem("uuid", uuidstr); if (!image_infos[i].macho_info.min_version_os_name.empty() && !image_infos[i].macho_info.min_version_os_version.empty()) { image_info_dict_sp->AddStringItem( "min_version_os_name", image_infos[i].macho_info.min_version_os_name); image_info_dict_sp->AddStringItem( "min_version_os_sdk", image_infos[i].macho_info.min_version_os_version); } JSONGenerator::DictionarySP mach_header_dict_sp( new JSONGenerator::Dictionary()); mach_header_dict_sp->AddIntegerItem( "magic", image_infos[i].macho_info.mach_header.magic); mach_header_dict_sp->AddIntegerItem( "cputype", (uint32_t)image_infos[i].macho_info.mach_header.cputype); mach_header_dict_sp->AddIntegerItem( "cpusubtype", (uint32_t)image_infos[i].macho_info.mach_header.cpusubtype); mach_header_dict_sp->AddIntegerItem( "filetype", image_infos[i].macho_info.mach_header.filetype); mach_header_dict_sp->AddIntegerItem ("flags", image_infos[i].macho_info.mach_header.flags); // DynamicLoaderMacOSX doesn't currently need these fields, so // don't send them. // mach_header_dict_sp->AddIntegerItem ("ncmds", // image_infos[i].macho_info.mach_header.ncmds); // mach_header_dict_sp->AddIntegerItem ("sizeofcmds", // image_infos[i].macho_info.mach_header.sizeofcmds); image_info_dict_sp->AddItem("mach_header", mach_header_dict_sp); JSONGenerator::ArraySP segments_sp(new JSONGenerator::Array()); for (size_t j = 0; j < image_infos[i].macho_info.segments.size(); j++) { JSONGenerator::DictionarySP segment_sp(new JSONGenerator::Dictionary()); segment_sp->AddStringItem("name", image_infos[i].macho_info.segments[j].name); segment_sp->AddIntegerItem("vmaddr", image_infos[i].macho_info.segments[j].vmaddr); segment_sp->AddIntegerItem("vmsize", image_infos[i].macho_info.segments[j].vmsize); segment_sp->AddIntegerItem("fileoff", image_infos[i].macho_info.segments[j].fileoff); segment_sp->AddIntegerItem( "filesize", image_infos[i].macho_info.segments[j].filesize); segment_sp->AddIntegerItem("maxprot", image_infos[i].macho_info.segments[j].maxprot); // DynamicLoaderMacOSX doesn't currently need these fields, // so don't send them. // segment_sp->AddIntegerItem ("initprot", // image_infos[i].macho_info.segments[j].initprot); // segment_sp->AddIntegerItem ("nsects", // image_infos[i].macho_info.segments[j].nsects); // segment_sp->AddIntegerItem ("flags", // image_infos[i].macho_info.segments[j].flags); segments_sp->AddItem(segment_sp); } image_info_dict_sp->AddItem("segments", segments_sp); image_infos_array_sp->AddItem(image_info_dict_sp); } JSONGenerator::DictionarySP reply_sp(new JSONGenerator::Dictionary()); reply_sp->AddItem("images", image_infos_array_sp); return reply_sp; } // Get the shared library information using the old (pre-macOS 10.12, pre-iOS // 10, pre-tvOS 10, pre-watchOS 3) // code path. We'll be given the address of an array of structures in the form // {void* load_addr, void* mod_date, void* pathname} // // In macOS 10.12 etc and newer, we'll use SPI calls into dyld to gather this // information. JSONGenerator::ObjectSP MachProcess::GetLoadedDynamicLibrariesInfos( nub_process_t pid, nub_addr_t image_list_address, nub_addr_t image_count) { JSONGenerator::ObjectSP empty_reply_sp(new JSONGenerator::Dictionary()); int pointer_size = GetInferiorAddrSize(pid); std::vector<struct binary_image_information> image_infos; size_t image_infos_size = image_count * 3 * pointer_size; uint8_t *image_info_buf = (uint8_t *)malloc(image_infos_size); if (image_info_buf == NULL) { return empty_reply_sp; } if (ReadMemory(image_list_address, image_infos_size, image_info_buf) != image_infos_size) { return empty_reply_sp; } /// First the image_infos array with (load addr, pathname, mod date) /// tuples for (size_t i = 0; i < image_count; i++) { struct binary_image_information info; nub_addr_t pathname_address; if (pointer_size == 4) { uint32_t load_address_32; uint32_t pathname_address_32; uint32_t mod_date_32; ::memcpy(&load_address_32, image_info_buf + (i * 3 * pointer_size), 4); ::memcpy(&pathname_address_32, image_info_buf + (i * 3 * pointer_size) + pointer_size, 4); ::memcpy(&mod_date_32, image_info_buf + (i * 3 * pointer_size) + pointer_size + pointer_size, 4); info.load_address = load_address_32; info.mod_date = mod_date_32; pathname_address = pathname_address_32; } else { uint64_t load_address_64; uint64_t pathname_address_64; uint64_t mod_date_64; ::memcpy(&load_address_64, image_info_buf + (i * 3 * pointer_size), 8); ::memcpy(&pathname_address_64, image_info_buf + (i * 3 * pointer_size) + pointer_size, 8); ::memcpy(&mod_date_64, image_info_buf + (i * 3 * pointer_size) + pointer_size + pointer_size, 8); info.load_address = load_address_64; info.mod_date = mod_date_64; pathname_address = pathname_address_64; } char strbuf[17]; info.filename = ""; uint64_t pathname_ptr = pathname_address; bool still_reading = true; while (still_reading && ReadMemory(pathname_ptr, sizeof(strbuf) - 1, strbuf) == sizeof(strbuf) - 1) { strbuf[sizeof(strbuf) - 1] = '\0'; info.filename += strbuf; pathname_ptr += sizeof(strbuf) - 1; // Stop if we found nul byte indicating the end of the string for (size_t i = 0; i < sizeof(strbuf) - 1; i++) { if (strbuf[i] == '\0') { still_reading = false; break; } } } uuid_clear(info.macho_info.uuid); image_infos.push_back(info); } if (image_infos.size() == 0) { return empty_reply_sp; } free(image_info_buf); /// Second, read the mach header / load commands for all the dylibs for (size_t i = 0; i < image_count; i++) { // The SPI to provide platform is not available on older systems. uint32_t platform = 0; if (GetMachOInformationFromMemory(platform, image_infos[i].load_address, pointer_size, image_infos[i].macho_info)) { image_infos[i].is_valid_mach_header = true; } } /// Third, format all of the above in the JSONGenerator object. return FormatDynamicLibrariesIntoJSON(image_infos); } /// From dyld SPI header dyld_process_info.h typedef void *dyld_process_info; struct dyld_process_cache_info { /// UUID of cache used by process. uuid_t cacheUUID; /// Load address of dyld shared cache. uint64_t cacheBaseAddress; /// Process is running without a dyld cache. bool noCache; /// Process is using a private copy of its dyld cache. bool privateCache; }; uint32_t MachProcess::GetPlatform() { if (m_platform == 0) m_platform = MachProcess::GetProcessPlatformViaDYLDSPI(); return m_platform; } uint32_t MachProcess::GetProcessPlatformViaDYLDSPI() { kern_return_t kern_ret; uint32_t platform = 0; if (m_dyld_process_info_create) { dyld_process_info info = m_dyld_process_info_create(m_task.TaskPort(), 0, &kern_ret); if (info) { if (m_dyld_process_info_get_platform) platform = m_dyld_process_info_get_platform(info); m_dyld_process_info_release(info); } } return platform; } void MachProcess::GetAllLoadedBinariesViaDYLDSPI( std::vector<struct binary_image_information> &image_infos) { kern_return_t kern_ret; if (m_dyld_process_info_create) { dyld_process_info info = m_dyld_process_info_create(m_task.TaskPort(), 0, &kern_ret); if (info) { m_dyld_process_info_for_each_image( info, ^(uint64_t mach_header_addr, const uuid_t uuid, const char *path) { struct binary_image_information image; image.filename = path; uuid_copy(image.macho_info.uuid, uuid); image.load_address = mach_header_addr; image_infos.push_back(image); }); m_dyld_process_info_release(info); } } } // Fetch information about all shared libraries using the dyld SPIs that exist // in // macOS 10.12, iOS 10, tvOS 10, watchOS 3 and newer. JSONGenerator::ObjectSP MachProcess::GetAllLoadedLibrariesInfos(nub_process_t pid) { int pointer_size = GetInferiorAddrSize(pid); std::vector<struct binary_image_information> image_infos; GetAllLoadedBinariesViaDYLDSPI(image_infos); uint32_t platform = GetPlatform(); const size_t image_count = image_infos.size(); for (size_t i = 0; i < image_count; i++) { if (GetMachOInformationFromMemory(platform, image_infos[i].load_address, pointer_size, image_infos[i].macho_info)) { image_infos[i].is_valid_mach_header = true; } } return FormatDynamicLibrariesIntoJSON(image_infos); } // Fetch information about the shared libraries at the given load addresses // using the // dyld SPIs that exist in macOS 10.12, iOS 10, tvOS 10, watchOS 3 and newer. JSONGenerator::ObjectSP MachProcess::GetLibrariesInfoForAddresses( nub_process_t pid, std::vector<uint64_t> &macho_addresses) { int pointer_size = GetInferiorAddrSize(pid); // Collect the list of all binaries that dyld knows about in // the inferior process. std::vector<struct binary_image_information> all_image_infos; GetAllLoadedBinariesViaDYLDSPI(all_image_infos); uint32_t platform = GetPlatform(); std::vector<struct binary_image_information> image_infos; const size_t macho_addresses_count = macho_addresses.size(); const size_t all_image_infos_count = all_image_infos.size(); for (size_t i = 0; i < macho_addresses_count; i++) { bool found_matching_entry = false; for (size_t j = 0; j < all_image_infos_count; j++) { if (all_image_infos[j].load_address == macho_addresses[i]) { image_infos.push_back(all_image_infos[j]); found_matching_entry = true; } } if (!found_matching_entry) { // dyld doesn't think there is a binary at this address, // but maybe there isn't a binary YET - let's look in memory // for a proper mach-o header etc and return what we can. // We will have an empty filename for the binary (because dyld // doesn't know about it yet) but we can read all of the mach-o // load commands from memory directly. struct binary_image_information entry; entry.load_address = macho_addresses[i]; image_infos.push_back(entry); } } const size_t image_infos_count = image_infos.size(); for (size_t i = 0; i < image_infos_count; i++) { if (GetMachOInformationFromMemory(platform, image_infos[i].load_address, pointer_size, image_infos[i].macho_info)) { image_infos[i].is_valid_mach_header = true; } } return FormatDynamicLibrariesIntoJSON(image_infos); } // From dyld's internal podyld_process_info.h: JSONGenerator::ObjectSP MachProcess::GetSharedCacheInfo(nub_process_t pid) { JSONGenerator::DictionarySP reply_sp(new JSONGenerator::Dictionary()); kern_return_t kern_ret; if (m_dyld_process_info_create && m_dyld_process_info_get_cache) { dyld_process_info info = m_dyld_process_info_create(m_task.TaskPort(), 0, &kern_ret); if (info) { struct dyld_process_cache_info shared_cache_info; m_dyld_process_info_get_cache(info, &shared_cache_info); reply_sp->AddIntegerItem("shared_cache_base_address", shared_cache_info.cacheBaseAddress); uuid_string_t uuidstr; uuid_unparse_upper(shared_cache_info.cacheUUID, uuidstr); reply_sp->AddStringItem("shared_cache_uuid", uuidstr); reply_sp->AddBooleanItem("no_shared_cache", shared_cache_info.noCache); reply_sp->AddBooleanItem("shared_cache_private_cache", shared_cache_info.privateCache); m_dyld_process_info_release(info); } } return reply_sp; } nub_thread_t MachProcess::GetCurrentThread() { return m_thread_list.CurrentThreadID(); } nub_thread_t MachProcess::GetCurrentThreadMachPort() { return m_thread_list.GetMachPortNumberByThreadID( m_thread_list.CurrentThreadID()); } nub_thread_t MachProcess::SetCurrentThread(nub_thread_t tid) { return m_thread_list.SetCurrentThread(tid); } bool MachProcess::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) { if (m_thread_list.GetThreadStoppedReason(tid, stop_info)) { if (m_did_exec) stop_info->reason = eStopTypeExec; return true; } return false; } void MachProcess::DumpThreadStoppedReason(nub_thread_t tid) const { return m_thread_list.DumpThreadStoppedReason(tid); } const char *MachProcess::GetThreadInfo(nub_thread_t tid) const { return m_thread_list.GetThreadInfo(tid); } uint32_t MachProcess::GetCPUType() { if (m_cpu_type == 0 && m_pid != 0) m_cpu_type = MachProcess::GetCPUTypeForLocalProcess(m_pid); return m_cpu_type; } const DNBRegisterSetInfo * MachProcess::GetRegisterSetInfo(nub_thread_t tid, nub_size_t *num_reg_sets) const { MachThreadSP thread_sp(m_thread_list.GetThreadByID(tid)); if (thread_sp) { DNBArchProtocol *arch = thread_sp->GetArchProtocol(); if (arch) return arch->GetRegisterSetInfo(num_reg_sets); } *num_reg_sets = 0; return NULL; } bool MachProcess::GetRegisterValue(nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value) const { return m_thread_list.GetRegisterValue(tid, set, reg, value); } bool MachProcess::SetRegisterValue(nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value) const { return m_thread_list.SetRegisterValue(tid, set, reg, value); } void MachProcess::SetState(nub_state_t new_state) { // If any other threads access this we will need a mutex for it uint32_t event_mask = 0; // Scope for mutex locker { PTHREAD_MUTEX_LOCKER(locker, m_state_mutex); const nub_state_t old_state = m_state; if (old_state == eStateExited) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SetState(%s) ignoring new " "state since current state is exited", DNBStateAsString(new_state)); } else if (old_state == new_state) { DNBLogThreadedIf( LOG_PROCESS, "MachProcess::SetState(%s) ignoring redundant state change...", DNBStateAsString(new_state)); } else { if (NUB_STATE_IS_STOPPED(new_state)) event_mask = eEventProcessStoppedStateChanged; else event_mask = eEventProcessRunningStateChanged; DNBLogThreadedIf( LOG_PROCESS, "MachProcess::SetState(%s) upating state (previous " "state was %s), event_mask = 0x%8.8x", DNBStateAsString(new_state), DNBStateAsString(old_state), event_mask); m_state = new_state; if (new_state == eStateStopped) m_stop_count++; } } if (event_mask != 0) { m_events.SetEvents(event_mask); m_private_events.SetEvents(event_mask); if (event_mask == eEventProcessStoppedStateChanged) m_private_events.ResetEvents(eEventProcessRunningStateChanged); else m_private_events.ResetEvents(eEventProcessStoppedStateChanged); // Wait for the event bit to reset if a reset ACK is requested m_events.WaitForResetAck(event_mask); } } void MachProcess::Clear(bool detaching) { // Clear any cached thread list while the pid and task are still valid m_task.Clear(); m_platform = 0; // Now clear out all member variables m_pid = INVALID_NUB_PROCESS; if (!detaching) CloseChildFileDescriptors(); m_path.clear(); m_args.clear(); SetState(eStateUnloaded); m_flags = eMachProcessFlagsNone; m_stop_count = 0; m_thread_list.Clear(); { PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex); m_exception_messages.clear(); } m_activities.Clear(); StopProfileThread(); } bool MachProcess::StartSTDIOThread() { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__); // Create the thread that watches for the child STDIO return ::pthread_create(&m_stdio_thread, NULL, MachProcess::STDIOThread, this) == 0; } void MachProcess::SetEnableAsyncProfiling(bool enable, uint64_t interval_usec, DNBProfileDataScanType scan_type) { m_profile_enabled = enable; m_profile_interval_usec = static_cast<useconds_t>(interval_usec); m_profile_scan_type = scan_type; if (m_profile_enabled && (m_profile_thread == NULL)) { StartProfileThread(); } else if (!m_profile_enabled && m_profile_thread) { StopProfileThread(); } } void MachProcess::StopProfileThread() { if (m_profile_thread == NULL) return; m_profile_events.SetEvents(eMachProcessProfileCancel); pthread_join(m_profile_thread, NULL); m_profile_thread = NULL; m_profile_events.ResetEvents(eMachProcessProfileCancel); } bool MachProcess::StartProfileThread() { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__); // Create the thread that profiles the inferior and reports back if enabled return ::pthread_create(&m_profile_thread, NULL, MachProcess::ProfileThread, this) == 0; } nub_addr_t MachProcess::LookupSymbol(const char *name, const char *shlib) { if (m_name_to_addr_callback != NULL && name && name[0]) return m_name_to_addr_callback(ProcessID(), name, shlib, m_name_to_addr_baton); return INVALID_NUB_ADDRESS; } bool MachProcess::Resume(const DNBThreadResumeActions &thread_actions) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Resume ()"); nub_state_t state = GetState(); if (CanResume(state)) { m_thread_actions = thread_actions; PrivateResume(); return true; } else if (state == eStateRunning) { DNBLog("Resume() - task 0x%x is already running, ignoring...", m_task.TaskPort()); return true; } DNBLog("Resume() - task 0x%x has state %s, can't continue...", m_task.TaskPort(), DNBStateAsString(state)); return false; } bool MachProcess::Kill(const struct timespec *timeout_abstime) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill ()"); nub_state_t state = DoSIGSTOP(true, false, NULL); DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() state = %s", DNBStateAsString(state)); errno = 0; DNBLog("Sending ptrace PT_KILL to terminate inferior process pid %d.", m_pid); ::ptrace(PT_KILL, m_pid, 0, 0); DNBError err; err.SetErrorToErrno(); if (DNBLogCheckLogBit(LOG_PROCESS) || err.Fail()) { err.LogThreaded("MachProcess::Kill() DoSIGSTOP() ::ptrace " "(PT_KILL, pid=%u, 0, 0) => 0x%8.8x (%s)", m_pid, err.Status(), err.AsString()); } m_thread_actions = DNBThreadResumeActions(eStateRunning, 0); PrivateResume(); // Try and reap the process without touching our m_events since // we want the code above this to still get the eStateExited event const uint32_t reap_timeout_usec = 1000000; // Wait 1 second and try to reap the process const uint32_t reap_interval_usec = 10000; // uint32_t reap_time_elapsed; for (reap_time_elapsed = 0; reap_time_elapsed < reap_timeout_usec; reap_time_elapsed += reap_interval_usec) { if (GetState() == eStateExited) break; usleep(reap_interval_usec); } DNBLog("Waited %u ms for process to be reaped (state = %s)", reap_time_elapsed / 1000, DNBStateAsString(GetState())); return true; } bool MachProcess::Interrupt() { nub_state_t state = GetState(); if (IsRunning(state)) { if (m_sent_interrupt_signo == 0) { m_sent_interrupt_signo = SIGSTOP; if (Signal(m_sent_interrupt_signo)) { DNBLogThreadedIf( LOG_PROCESS, "MachProcess::Interrupt() - sent %i signal to interrupt process", m_sent_interrupt_signo); return true; } else { m_sent_interrupt_signo = 0; DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Interrupt() - failed to " "send %i signal to interrupt process", m_sent_interrupt_signo); } } else { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Interrupt() - previously " "sent an interrupt signal %i that hasn't " "been received yet, interrupt aborted", m_sent_interrupt_signo); } } else { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Interrupt() - process already " "stopped, no interrupt sent"); } return false; } bool MachProcess::Signal(int signal, const struct timespec *timeout_abstime) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p)", signal, static_cast<const void *>(timeout_abstime)); nub_state_t state = GetState(); if (::kill(ProcessID(), signal) == 0) { // If we were running and we have a timeout, wait for the signal to stop if (IsRunning(state) && timeout_abstime) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout " "= %p) waiting for signal to stop " "process...", signal, static_cast<const void *>(timeout_abstime)); m_private_events.WaitForSetEvents(eEventProcessStoppedStateChanged, timeout_abstime); state = GetState(); DNBLogThreadedIf( LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) state = %s", signal, static_cast<const void *>(timeout_abstime), DNBStateAsString(state)); return !IsRunning(state); } DNBLogThreadedIf( LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) not waiting...", signal, static_cast<const void *>(timeout_abstime)); return true; } DNBError err(errno, DNBError::POSIX); err.LogThreadedIfError("kill (pid = %d, signo = %i)", ProcessID(), signal); return false; } bool MachProcess::SendEvent(const char *event, DNBError &send_err) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SendEvent (event = %s) to pid: %d", event, m_pid); if (m_pid == INVALID_NUB_PROCESS) return false; // FIXME: Shouldn't we use the launch flavor we were started with? #if defined(WITH_FBS) || defined(WITH_BKS) return BoardServiceSendEvent(event, send_err); #endif return true; } nub_state_t MachProcess::DoSIGSTOP(bool clear_bps_and_wps, bool allow_running, uint32_t *thread_idx_ptr) { nub_state_t state = GetState(); DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s", DNBStateAsString(state)); if (!IsRunning(state)) { if (clear_bps_and_wps) { DisableAllBreakpoints(true); DisableAllWatchpoints(true); clear_bps_and_wps = false; } // If we already have a thread stopped due to a SIGSTOP, we don't have // to do anything... uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal(SIGSTOP); if (thread_idx_ptr) *thread_idx_ptr = thread_idx; if (thread_idx != UINT32_MAX) return GetState(); // No threads were stopped with a SIGSTOP, we need to run and halt the // process with a signal DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- resuming process", DNBStateAsString(state)); if (allow_running) m_thread_actions = DNBThreadResumeActions(eStateRunning, 0); else m_thread_actions = DNBThreadResumeActions(eStateSuspended, 0); PrivateResume(); // Reset the event that says we were indeed running m_events.ResetEvents(eEventProcessRunningStateChanged); state = GetState(); } // We need to be stopped in order to be able to detach, so we need // to send ourselves a SIGSTOP DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- sending SIGSTOP", DNBStateAsString(state)); struct timespec sigstop_timeout; DNBTimer::OffsetTimeOfDay(&sigstop_timeout, 2, 0); Signal(SIGSTOP, &sigstop_timeout); if (clear_bps_and_wps) { DisableAllBreakpoints(true); DisableAllWatchpoints(true); // clear_bps_and_wps = false; } uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal(SIGSTOP); if (thread_idx_ptr) *thread_idx_ptr = thread_idx; return GetState(); } bool MachProcess::Detach() { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach()"); uint32_t thread_idx = UINT32_MAX; nub_state_t state = DoSIGSTOP(true, true, &thread_idx); DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach() DoSIGSTOP() returned %s", DNBStateAsString(state)); { m_thread_actions.Clear(); m_activities.Clear(); DNBThreadResumeAction thread_action; thread_action.tid = m_thread_list.ThreadIDAtIndex(thread_idx); thread_action.state = eStateRunning; thread_action.signal = -1; thread_action.addr = INVALID_NUB_ADDRESS; m_thread_actions.Append(thread_action); m_thread_actions.SetDefaultThreadActionIfNeeded(eStateRunning, 0); PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex); ReplyToAllExceptions(); } m_task.ShutDownExcecptionThread(); // Detach from our process errno = 0; nub_process_t pid = m_pid; int ret = ::ptrace(PT_DETACH, pid, (caddr_t)1, 0); DNBError err(errno, DNBError::POSIX); if (DNBLogCheckLogBit(LOG_PROCESS) || err.Fail() || (ret != 0)) err.LogThreaded("::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid); // Resume our task m_task.Resume(); // NULL our task out as we have already restored all exception ports m_task.Clear(); m_platform = 0; // Clear out any notion of the process we once were const bool detaching = true; Clear(detaching); SetState(eStateDetached); return true; } //your_sha256_hash------ // ReadMemory from the MachProcess level will always remove any software // breakpoints from the memory buffer before returning. If you wish to // read memory and see those traps, read from the MachTask // (m_task.ReadMemory()) as that version will give you what is actually // in inferior memory. //your_sha256_hash------ nub_size_t MachProcess::ReadMemory(nub_addr_t addr, nub_size_t size, void *buf) { // We need to remove any current software traps (enabled software // breakpoints) that we may have placed in our tasks memory. // First just read the memory as is nub_size_t bytes_read = m_task.ReadMemory(addr, size, buf); // Then place any opcodes that fall into this range back into the buffer // before we return this to callers. if (bytes_read > 0) m_breakpoints.RemoveTrapsFromBuffer(addr, bytes_read, buf); return bytes_read; } //your_sha256_hash------ // WriteMemory from the MachProcess level will always write memory around // any software breakpoints. Any software breakpoints will have their // opcodes modified if they are enabled. Any memory that doesn't overlap // with software breakpoints will be written to. If you wish to write to // inferior memory without this interference, then write to the MachTask // (m_task.WriteMemory()) as that version will always modify inferior // memory. //your_sha256_hash------ nub_size_t MachProcess::WriteMemory(nub_addr_t addr, nub_size_t size, const void *buf) { // We need to write any data that would go where any current software traps // (enabled software breakpoints) any software traps (breakpoints) that we // may have placed in our tasks memory. std::vector<DNBBreakpoint *> bps; const size_t num_bps = m_breakpoints.FindBreakpointsThatOverlapRange(addr, size, bps); if (num_bps == 0) return m_task.WriteMemory(addr, size, buf); nub_size_t bytes_written = 0; nub_addr_t intersect_addr; nub_size_t intersect_size; nub_size_t opcode_offset; const uint8_t *ubuf = (const uint8_t *)buf; for (size_t i = 0; i < num_bps; ++i) { DNBBreakpoint *bp = bps[i]; const bool intersects = bp->IntersectsRange( addr, size, &intersect_addr, &intersect_size, &opcode_offset); UNUSED_IF_ASSERT_DISABLED(intersects); assert(intersects); assert(addr <= intersect_addr && intersect_addr < addr + size); assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size); assert(opcode_offset + intersect_size <= bp->ByteSize()); // Check for bytes before this breakpoint const nub_addr_t curr_addr = addr + bytes_written; if (intersect_addr > curr_addr) { // There are some bytes before this breakpoint that we need to // just write to memory nub_size_t curr_size = intersect_addr - curr_addr; nub_size_t curr_bytes_written = m_task.WriteMemory(curr_addr, curr_size, ubuf + bytes_written); bytes_written += curr_bytes_written; if (curr_bytes_written != curr_size) { // We weren't able to write all of the requested bytes, we // are done looping and will return the number of bytes that // we have written so far. break; } } // Now write any bytes that would cover up any software breakpoints // directly into the breakpoint opcode buffer ::memcpy(bp->SavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size); bytes_written += intersect_size; } // Write any remaining bytes after the last breakpoint if we have any left if (bytes_written < size) bytes_written += m_task.WriteMemory( addr + bytes_written, size - bytes_written, ubuf + bytes_written); return bytes_written; } void MachProcess::ReplyToAllExceptions() { PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex); if (!m_exception_messages.empty()) { MachException::Message::iterator pos; MachException::Message::iterator begin = m_exception_messages.begin(); MachException::Message::iterator end = m_exception_messages.end(); for (pos = begin; pos != end; ++pos) { DNBLogThreadedIf(LOG_EXCEPTIONS, "Replying to exception %u...", (uint32_t)std::distance(begin, pos)); int thread_reply_signal = 0; nub_thread_t tid = m_thread_list.GetThreadIDByMachPortNumber(pos->state.thread_port); const DNBThreadResumeAction *action = NULL; if (tid != INVALID_NUB_THREAD) { action = m_thread_actions.GetActionForThread(tid, false); } if (action) { thread_reply_signal = action->signal; if (thread_reply_signal) m_thread_actions.SetSignalHandledForThread(tid); } DNBError err(pos->Reply(this, thread_reply_signal)); if (DNBLogCheckLogBit(LOG_EXCEPTIONS)) err.LogThreadedIfError("Error replying to exception"); } // Erase all exception message as we should have used and replied // to them all already. m_exception_messages.clear(); } } void MachProcess::PrivateResume() { PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex); m_auto_resume_signo = m_sent_interrupt_signo; if (m_auto_resume_signo) DNBLogThreadedIf(LOG_PROCESS, "MachProcess::PrivateResume() - task 0x%x " "resuming (with unhandled interrupt signal " "%i)...", m_task.TaskPort(), m_auto_resume_signo); else DNBLogThreadedIf(LOG_PROCESS, "MachProcess::PrivateResume() - task 0x%x resuming...", m_task.TaskPort()); ReplyToAllExceptions(); // bool stepOverBreakInstruction = step; // Let the thread prepare to resume and see if any threads want us to // step over a breakpoint instruction (ProcessWillResume will modify // the value of stepOverBreakInstruction). m_thread_list.ProcessWillResume(this, m_thread_actions); // Set our state accordingly if (m_thread_actions.NumActionsWithState(eStateStepping)) SetState(eStateStepping); else SetState(eStateRunning); // Now resume our task. m_task.Resume(); } DNBBreakpoint *MachProcess::CreateBreakpoint(nub_addr_t addr, nub_size_t length, bool hardware) { DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = " "0x%8.8llx, length = %llu, hardware = %i)", (uint64_t)addr, (uint64_t)length, hardware); DNBBreakpoint *bp = m_breakpoints.FindByAddress(addr); if (bp) bp->Retain(); else bp = m_breakpoints.Add(addr, length, hardware); if (EnableBreakpoint(addr)) { DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = " "0x%8.8llx, length = %llu) => %p", (uint64_t)addr, (uint64_t)length, static_cast<void *>(bp)); return bp; } else if (bp->Release() == 0) { m_breakpoints.Remove(addr); } // We failed to enable the breakpoint return NULL; } DNBBreakpoint *MachProcess::CreateWatchpoint(nub_addr_t addr, nub_size_t length, uint32_t watch_flags, bool hardware) { DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = " "0x%8.8llx, length = %llu, flags = " "0x%8.8x, hardware = %i)", (uint64_t)addr, (uint64_t)length, watch_flags, hardware); DNBBreakpoint *wp = m_watchpoints.FindByAddress(addr); // since the Z packets only send an address, we can only have one watchpoint // at // an address. If there is already one, we must refuse to create another // watchpoint if (wp) return NULL; wp = m_watchpoints.Add(addr, length, hardware); wp->SetIsWatchpoint(watch_flags); if (EnableWatchpoint(addr)) { DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = " "0x%8.8llx, length = %llu) => %p", (uint64_t)addr, (uint64_t)length, static_cast<void *>(wp)); return wp; } else { DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = " "0x%8.8llx, length = %llu) => FAILED", (uint64_t)addr, (uint64_t)length); m_watchpoints.Remove(addr); } // We failed to enable the watchpoint return NULL; } void MachProcess::DisableAllBreakpoints(bool remove) { DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove); m_breakpoints.DisableAllBreakpoints(this); if (remove) m_breakpoints.RemoveDisabled(); } void MachProcess::DisableAllWatchpoints(bool remove) { DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove); m_watchpoints.DisableAllWatchpoints(this); if (remove) m_watchpoints.RemoveDisabled(); } bool MachProcess::DisableBreakpoint(nub_addr_t addr, bool remove) { DNBBreakpoint *bp = m_breakpoints.FindByAddress(addr); if (bp) { // After "exec" we might end up with a bunch of breakpoints that were // disabled // manually, just ignore them if (!bp->IsEnabled()) { // Breakpoint might have been disabled by an exec if (remove && bp->Release() == 0) { m_thread_list.NotifyBreakpointChanged(bp); m_breakpoints.Remove(addr); } return true; } // We have multiple references to this breakpoint, decrement the ref count // and if it isn't zero, then return true; if (remove && bp->Release() > 0) return true; DNBLogThreadedIf( LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d )", (uint64_t)addr, remove); if (bp->IsHardware()) { bool hw_disable_result = m_thread_list.DisableHardwareBreakpoint(bp); if (hw_disable_result) { bp->SetEnabled(false); // Let the thread list know that a breakpoint has been modified if (remove) { m_thread_list.NotifyBreakpointChanged(bp); m_breakpoints.Remove(addr); } DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( " "addr = 0x%8.8llx, remove = %d ) " "(hardware) => success", (uint64_t)addr, remove); return true; } return false; } const nub_size_t break_op_size = bp->ByteSize(); assert(break_op_size > 0); const uint8_t *const break_op = DNBArchProtocol::GetBreakpointOpcode(bp->ByteSize()); if (break_op_size > 0) { // Clear a software breakpoint instruction uint8_t curr_break_op[break_op_size]; bool break_op_found = false; // Read the breakpoint opcode if (m_task.ReadMemory(addr, break_op_size, curr_break_op) == break_op_size) { bool verify = false; if (bp->IsEnabled()) { // Make sure a breakpoint opcode exists at this address if (memcmp(curr_break_op, break_op, break_op_size) == 0) { break_op_found = true; // We found a valid breakpoint opcode at this address, now restore // the saved opcode. if (m_task.WriteMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size) { verify = true; } else { DNBLogError("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, " "remove = %d ) memory write failed when restoring " "original opcode", (uint64_t)addr, remove); } } else { DNBLogWarning("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, " "remove = %d ) expected a breakpoint opcode but " "didn't find one.", (uint64_t)addr, remove); // Set verify to true and so we can check if the original opcode has // already been restored verify = true; } } else { DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, " "remove = %d ) is not enabled", (uint64_t)addr, remove); // Set verify to true and so we can check if the original opcode is // there verify = true; } if (verify) { uint8_t verify_opcode[break_op_size]; // Verify that our original opcode made it back to the inferior if (m_task.ReadMemory(addr, break_op_size, verify_opcode) == break_op_size) { // compare the memory we just read with the original opcode if (memcmp(bp->SavedOpcodeBytes(), verify_opcode, break_op_size) == 0) { // SUCCESS bp->SetEnabled(false); // Let the thread list know that a breakpoint has been modified if (remove && bp->Release() == 0) { m_thread_list.NotifyBreakpointChanged(bp); m_breakpoints.Remove(addr); } DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( addr = " "0x%8.8llx, remove = %d ) => success", (uint64_t)addr, remove); return true; } else { if (break_op_found) DNBLogError("MachProcess::DisableBreakpoint ( addr = " "0x%8.8llx, remove = %d ) : failed to restore " "original opcode", (uint64_t)addr, remove); else DNBLogError("MachProcess::DisableBreakpoint ( addr = " "0x%8.8llx, remove = %d ) : opcode changed", (uint64_t)addr, remove); } } else { DNBLogWarning("MachProcess::DisableBreakpoint: unable to disable " "breakpoint 0x%8.8llx", (uint64_t)addr); } } } else { DNBLogWarning("MachProcess::DisableBreakpoint: unable to read memory " "at 0x%8.8llx", (uint64_t)addr); } } } else { DNBLogError("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = " "%d ) invalid breakpoint address", (uint64_t)addr, remove); } return false; } bool MachProcess::DisableWatchpoint(nub_addr_t addr, bool remove) { DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s(addr = 0x%8.8llx, remove = %d)", __FUNCTION__, (uint64_t)addr, remove); DNBBreakpoint *wp = m_watchpoints.FindByAddress(addr); if (wp) { // If we have multiple references to a watchpoint, removing the watchpoint // shouldn't clear it if (remove && wp->Release() > 0) return true; nub_addr_t addr = wp->Address(); DNBLogThreadedIf( LOG_WATCHPOINTS, "MachProcess::DisableWatchpoint ( addr = 0x%8.8llx, remove = %d )", (uint64_t)addr, remove); if (wp->IsHardware()) { bool hw_disable_result = m_thread_list.DisableHardwareWatchpoint(wp); if (hw_disable_result) { wp->SetEnabled(false); if (remove) m_watchpoints.Remove(addr); DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::Disablewatchpoint ( " "addr = 0x%8.8llx, remove = %d ) " "(hardware) => success", (uint64_t)addr, remove); return true; } } // TODO: clear software watchpoints if we implement them } else { DNBLogError("MachProcess::DisableWatchpoint ( addr = 0x%8.8llx, remove = " "%d ) invalid watchpoint ID", (uint64_t)addr, remove); } return false; } uint32_t MachProcess::GetNumSupportedHardwareWatchpoints() const { return m_thread_list.NumSupportedHardwareWatchpoints(); } bool MachProcess::EnableBreakpoint(nub_addr_t addr) { DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( addr = 0x%8.8llx )", (uint64_t)addr); DNBBreakpoint *bp = m_breakpoints.FindByAddress(addr); if (bp) { if (bp->IsEnabled()) { DNBLogWarning("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): " "breakpoint already enabled.", (uint64_t)addr); return true; } else { if (bp->HardwarePreferred()) { bp->SetHardwareIndex(m_thread_list.EnableHardwareBreakpoint(bp)); if (bp->IsHardware()) { bp->SetEnabled(true); return true; } } const nub_size_t break_op_size = bp->ByteSize(); assert(break_op_size != 0); const uint8_t *const break_op = DNBArchProtocol::GetBreakpointOpcode(break_op_size); if (break_op_size > 0) { // Save the original opcode by reading it if (m_task.ReadMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size) { // Write a software breakpoint in place of the original opcode if (m_task.WriteMemory(addr, break_op_size, break_op) == break_op_size) { uint8_t verify_break_op[4]; if (m_task.ReadMemory(addr, break_op_size, verify_break_op) == break_op_size) { if (memcmp(break_op, verify_break_op, break_op_size) == 0) { bp->SetEnabled(true); // Let the thread list know that a breakpoint has been modified m_thread_list.NotifyBreakpointChanged(bp); DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::" "EnableBreakpoint ( addr = " "0x%8.8llx ) : SUCCESS.", (uint64_t)addr); return true; } else { DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx " "): breakpoint opcode verification failed.", (uint64_t)addr); } } else { DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): " "unable to read memory to verify breakpoint opcode.", (uint64_t)addr); } } else { DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): " "unable to write breakpoint opcode to memory.", (uint64_t)addr); } } else { DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): " "unable to read memory at breakpoint address.", (uint64_t)addr); } } else { DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ) no " "software breakpoint opcode for current architecture.", (uint64_t)addr); } } } return false; } bool MachProcess::EnableWatchpoint(nub_addr_t addr) { DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::EnableWatchpoint(addr = 0x%8.8llx)", (uint64_t)addr); DNBBreakpoint *wp = m_watchpoints.FindByAddress(addr); if (wp) { nub_addr_t addr = wp->Address(); if (wp->IsEnabled()) { DNBLogWarning("MachProcess::EnableWatchpoint(addr = 0x%8.8llx): " "watchpoint already enabled.", (uint64_t)addr); return true; } else { // Currently only try and set hardware watchpoints. wp->SetHardwareIndex(m_thread_list.EnableHardwareWatchpoint(wp)); if (wp->IsHardware()) { wp->SetEnabled(true); return true; } // TODO: Add software watchpoints by doing page protection tricks. } } return false; } // Called by the exception thread when an exception has been received from // our process. The exception message is completely filled and the exception // data has already been copied. void MachProcess::ExceptionMessageReceived( const MachException::Message &exceptionMessage) { PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex); if (m_exception_messages.empty()) m_task.Suspend(); DNBLogThreadedIf(LOG_EXCEPTIONS, "MachProcess::ExceptionMessageReceived ( )"); // Use a locker to automatically unlock our mutex in case of exceptions // Add the exception to our internal exception stack m_exception_messages.push_back(exceptionMessage); } task_t MachProcess::ExceptionMessageBundleComplete() { // We have a complete bundle of exceptions for our child process. PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex); DNBLogThreadedIf(LOG_EXCEPTIONS, "%s: %llu exception messages.", __PRETTY_FUNCTION__, (uint64_t)m_exception_messages.size()); bool auto_resume = false; if (!m_exception_messages.empty()) { m_did_exec = false; // First check for any SIGTRAP and make sure we didn't exec const task_t task = m_task.TaskPort(); size_t i; if (m_pid != 0) { bool received_interrupt = false; uint32_t num_task_exceptions = 0; for (i = 0; i < m_exception_messages.size(); ++i) { if (m_exception_messages[i].state.task_port == task) { ++num_task_exceptions; const int signo = m_exception_messages[i].state.SoftSignal(); if (signo == SIGTRAP) { // SIGTRAP could mean that we exec'ed. We need to check the // dyld all_image_infos.infoArray to see if it is NULL and if // so, say that we exec'ed. const nub_addr_t aii_addr = GetDYLDAllImageInfosAddress(); if (aii_addr != INVALID_NUB_ADDRESS) { const nub_addr_t info_array_count_addr = aii_addr + 4; uint32_t info_array_count = 0; if (m_task.ReadMemory(info_array_count_addr, 4, &info_array_count) == 4) { if (info_array_count == 0) { m_did_exec = true; // Force the task port to update itself in case the task port // changed after exec DNBError err; const task_t old_task = m_task.TaskPort(); const task_t new_task = m_task.TaskPortForProcessID(err, true); if (old_task != new_task) DNBLogThreadedIf( LOG_PROCESS, "exec: task changed from 0x%4.4x to 0x%4.4x", old_task, new_task); } } else { DNBLog("error: failed to read all_image_infos.infoArrayCount " "from 0x%8.8llx", (uint64_t)info_array_count_addr); } } break; } else if (m_sent_interrupt_signo != 0 && signo == m_sent_interrupt_signo) { received_interrupt = true; } } } if (m_did_exec) { cpu_type_t process_cpu_type = MachProcess::GetCPUTypeForLocalProcess(m_pid); if (m_cpu_type != process_cpu_type) { DNBLog("arch changed from 0x%8.8x to 0x%8.8x", m_cpu_type, process_cpu_type); m_cpu_type = process_cpu_type; DNBArchProtocol::SetArchitecture(process_cpu_type); } m_thread_list.Clear(); m_activities.Clear(); m_breakpoints.DisableAll(); m_task.ClearAllocations(); } if (m_sent_interrupt_signo != 0) { if (received_interrupt) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::ExceptionMessageBundleComplete(): " "process successfully interrupted with signal %i", m_sent_interrupt_signo); // Mark that we received the interrupt signal m_sent_interrupt_signo = 0; // Not check if we had a case where: // 1 - We called MachProcess::Interrupt() but we stopped for another // reason // 2 - We called MachProcess::Resume() (but still haven't gotten the // interrupt signal) // 3 - We are now incorrectly stopped because we are handling the // interrupt signal we missed // 4 - We might need to resume if we stopped only with the interrupt // signal that we never handled if (m_auto_resume_signo != 0) { // Only auto_resume if we stopped with _only_ the interrupt signal if (num_task_exceptions == 1) { auto_resume = true; DNBLogThreadedIf(LOG_PROCESS, "MachProcess::" "ExceptionMessageBundleComplete(): " "auto resuming due to unhandled " "interrupt signal %i", m_auto_resume_signo); } m_auto_resume_signo = 0; } } else { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::" "ExceptionMessageBundleComplete(): " "didn't get signal %i after " "MachProcess::Interrupt()", m_sent_interrupt_signo); } } } // Let all threads recover from stopping and do any clean up based // on the previous thread state (if any). m_thread_list.ProcessDidStop(this); m_activities.Clear(); // Let each thread know of any exceptions for (i = 0; i < m_exception_messages.size(); ++i) { // Let the thread list figure use the MachProcess to forward all // exceptions // on down to each thread. if (m_exception_messages[i].state.task_port == task) m_thread_list.NotifyException(m_exception_messages[i].state); if (DNBLogCheckLogBit(LOG_EXCEPTIONS)) m_exception_messages[i].Dump(); } if (DNBLogCheckLogBit(LOG_THREAD)) m_thread_list.Dump(); bool step_more = false; if (m_thread_list.ShouldStop(step_more) && !auto_resume) { // Wait for the eEventProcessRunningStateChanged event to be reset // before changing state to stopped to avoid race condition with // very fast start/stops struct timespec timeout; // DNBTimer::OffsetTimeOfDay(&timeout, 0, 250 * 1000); // Wait for 250 // ms DNBTimer::OffsetTimeOfDay(&timeout, 1, 0); // Wait for 250 ms m_events.WaitForEventsToReset(eEventProcessRunningStateChanged, &timeout); SetState(eStateStopped); } else { // Resume without checking our current state. PrivateResume(); } } else { DNBLogThreadedIf( LOG_EXCEPTIONS, "%s empty exception messages bundle (%llu exceptions).", __PRETTY_FUNCTION__, (uint64_t)m_exception_messages.size()); } return m_task.TaskPort(); } nub_size_t MachProcess::CopyImageInfos(struct DNBExecutableImageInfo **image_infos, bool only_changed) { if (m_image_infos_callback != NULL) return m_image_infos_callback(ProcessID(), image_infos, only_changed, m_image_infos_baton); return 0; } void MachProcess::SharedLibrariesUpdated() { uint32_t event_bits = eEventSharedLibsStateChange; // Set the shared library event bit to let clients know of shared library // changes m_events.SetEvents(event_bits); // Wait for the event bit to reset if a reset ACK is requested m_events.WaitForResetAck(event_bits); } void MachProcess::SetExitInfo(const char *info) { if (info && info[0]) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s(\"%s\")", __FUNCTION__, info); m_exit_info.assign(info); } else { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s(NULL)", __FUNCTION__); m_exit_info.clear(); } } void MachProcess::AppendSTDOUT(char *s, size_t len) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (<%llu> %s) ...", __FUNCTION__, (uint64_t)len, s); PTHREAD_MUTEX_LOCKER(locker, m_stdio_mutex); m_stdout_data.append(s, len); m_events.SetEvents(eEventStdioAvailable); // Wait for the event bit to reset if a reset ACK is requested m_events.WaitForResetAck(eEventStdioAvailable); } size_t MachProcess::GetAvailableSTDOUT(char *buf, size_t buf_size) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%llu]) ...", __FUNCTION__, static_cast<void *>(buf), (uint64_t)buf_size); PTHREAD_MUTEX_LOCKER(locker, m_stdio_mutex); size_t bytes_available = m_stdout_data.size(); if (bytes_available > 0) { if (bytes_available > buf_size) { memcpy(buf, m_stdout_data.data(), buf_size); m_stdout_data.erase(0, buf_size); bytes_available = buf_size; } else { memcpy(buf, m_stdout_data.data(), bytes_available); m_stdout_data.clear(); } } return bytes_available; } nub_addr_t MachProcess::GetDYLDAllImageInfosAddress() { DNBError err; return m_task.GetDYLDAllImageInfosAddress(err); } /// From dyld SPI header dyld_process_info.h struct dyld_process_state_info { uint64_t timestamp; uint32_t imageCount; uint32_t initialImageCount; // one of dyld_process_state_* values uint8_t dyldState; }; enum { dyld_process_state_not_started = 0x00, dyld_process_state_dyld_initialized = 0x10, dyld_process_state_terminated_before_inits = 0x20, dyld_process_state_libSystem_initialized = 0x30, dyld_process_state_running_initializers = 0x40, dyld_process_state_program_running = 0x50, dyld_process_state_dyld_terminated = 0x60 }; JSONGenerator::ObjectSP MachProcess::GetDyldProcessState() { JSONGenerator::DictionarySP reply_sp(new JSONGenerator::Dictionary()); if (!m_dyld_process_info_get_state) { reply_sp->AddStringItem("error", "_dyld_process_info_get_state unavailable"); return reply_sp; } if (!m_dyld_process_info_create) { reply_sp->AddStringItem("error", "_dyld_process_info_create unavailable"); return reply_sp; } kern_return_t kern_ret; dyld_process_info info = m_dyld_process_info_create(m_task.TaskPort(), 0, &kern_ret); if (!info || kern_ret != KERN_SUCCESS) { reply_sp->AddStringItem( "error", "Unable to create dyld_process_info for inferior task"); return reply_sp; } struct dyld_process_state_info state_info; m_dyld_process_info_get_state(info, &state_info); reply_sp->AddIntegerItem("process_state_value", state_info.dyldState); switch (state_info.dyldState) { case dyld_process_state_not_started: reply_sp->AddStringItem("process_state string", "dyld_process_state_not_started"); break; case dyld_process_state_dyld_initialized: reply_sp->AddStringItem("process_state string", "dyld_process_state_dyld_initialized"); break; case dyld_process_state_terminated_before_inits: reply_sp->AddStringItem("process_state string", "dyld_process_state_terminated_before_inits"); break; case dyld_process_state_libSystem_initialized: reply_sp->AddStringItem("process_state string", "dyld_process_state_libSystem_initialized"); break; case dyld_process_state_running_initializers: reply_sp->AddStringItem("process_state string", "dyld_process_state_running_initializers"); break; case dyld_process_state_program_running: reply_sp->AddStringItem("process_state string", "dyld_process_state_program_running"); break; case dyld_process_state_dyld_terminated: reply_sp->AddStringItem("process_state string", "dyld_process_state_dyld_terminated"); break; }; m_dyld_process_info_release(info); return reply_sp; } size_t MachProcess::GetAvailableSTDERR(char *buf, size_t buf_size) { return 0; } void *MachProcess::STDIOThread(void *arg) { MachProcess *proc = (MachProcess *)arg; DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( arg = %p ) thread starting...", __FUNCTION__, arg); #if defined(__APPLE__) pthread_setname_np("stdio monitoring thread"); #endif // We start use a base and more options so we can control if we // are currently using a timeout on the mach_msg. We do this to get a // bunch of related exceptions on our exception port so we can process // then together. When we have multiple threads, we can get an exception // per thread and they will come in consecutively. The main thread loop // will start by calling mach_msg to without having the MACH_RCV_TIMEOUT // flag set in the options, so we will wait forever for an exception on // our exception port. After we get one exception, we then will use the // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current // exceptions for our process. After we have received the last pending // exception, we will get a timeout which enables us to then notify // our main thread that we have an exception bundle available. We then wait // for the main thread to tell this exception thread to start trying to get // exceptions messages again and we start again with a mach_msg read with // infinite timeout. DNBError err; int stdout_fd = proc->GetStdoutFileDescriptor(); int stderr_fd = proc->GetStderrFileDescriptor(); if (stdout_fd == stderr_fd) stderr_fd = -1; while (stdout_fd >= 0 || stderr_fd >= 0) { ::pthread_testcancel(); fd_set read_fds; FD_ZERO(&read_fds); if (stdout_fd >= 0) FD_SET(stdout_fd, &read_fds); if (stderr_fd >= 0) FD_SET(stderr_fd, &read_fds); int nfds = std::max<int>(stdout_fd, stderr_fd) + 1; int num_set_fds = select(nfds, &read_fds, NULL, NULL, NULL); DNBLogThreadedIf(LOG_PROCESS, "select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds); if (num_set_fds < 0) { int select_errno = errno; if (DNBLogCheckLogBit(LOG_PROCESS)) { err.SetError(select_errno, DNBError::POSIX); err.LogThreadedIfError( "select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds); } switch (select_errno) { case EAGAIN: // The kernel was (perhaps temporarily) unable to allocate // the requested number of file descriptors, or we have // non-blocking IO break; case EBADF: // One of the descriptor sets specified an invalid descriptor. return NULL; break; case EINTR: // A signal was delivered before the time limit expired and // before any of the selected events occurred. case EINVAL: // The specified time limit is invalid. One of its components // is negative or too large. default: // Other unknown error break; } } else if (num_set_fds == 0) { } else { char s[1024]; s[sizeof(s) - 1] = '\0'; // Ensure we have NULL termination ssize_t bytes_read = 0; if (stdout_fd >= 0 && FD_ISSET(stdout_fd, &read_fds)) { do { bytes_read = ::read(stdout_fd, s, sizeof(s) - 1); if (bytes_read < 0) { int read_errno = errno; DNBLogThreadedIf(LOG_PROCESS, "read (stdout_fd, ) => %zd errno: %d (%s)", bytes_read, read_errno, strerror(read_errno)); } else if (bytes_read == 0) { // EOF... DNBLogThreadedIf( LOG_PROCESS, "read (stdout_fd, ) => %zd (reached EOF for child STDOUT)", bytes_read); stdout_fd = -1; } else if (bytes_read > 0) { proc->AppendSTDOUT(s, bytes_read); } } while (bytes_read > 0); } if (stderr_fd >= 0 && FD_ISSET(stderr_fd, &read_fds)) { do { bytes_read = ::read(stderr_fd, s, sizeof(s) - 1); if (bytes_read < 0) { int read_errno = errno; DNBLogThreadedIf(LOG_PROCESS, "read (stderr_fd, ) => %zd errno: %d (%s)", bytes_read, read_errno, strerror(read_errno)); } else if (bytes_read == 0) { // EOF... DNBLogThreadedIf( LOG_PROCESS, "read (stderr_fd, ) => %zd (reached EOF for child STDERR)", bytes_read); stderr_fd = -1; } else if (bytes_read > 0) { proc->AppendSTDOUT(s, bytes_read); } } while (bytes_read > 0); } } } DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%p): thread exiting...", __FUNCTION__, arg); return NULL; } void MachProcess::SignalAsyncProfileData(const char *info) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%s) ...", __FUNCTION__, info); PTHREAD_MUTEX_LOCKER(locker, m_profile_data_mutex); m_profile_data.push_back(info); m_events.SetEvents(eEventProfileDataAvailable); // Wait for the event bit to reset if a reset ACK is requested m_events.WaitForResetAck(eEventProfileDataAvailable); } size_t MachProcess::GetAsyncProfileData(char *buf, size_t buf_size) { DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%llu]) ...", __FUNCTION__, static_cast<void *>(buf), (uint64_t)buf_size); PTHREAD_MUTEX_LOCKER(locker, m_profile_data_mutex); if (m_profile_data.empty()) return 0; size_t bytes_available = m_profile_data.front().size(); if (bytes_available > 0) { if (bytes_available > buf_size) { memcpy(buf, m_profile_data.front().data(), buf_size); m_profile_data.front().erase(0, buf_size); bytes_available = buf_size; } else { memcpy(buf, m_profile_data.front().data(), bytes_available); m_profile_data.erase(m_profile_data.begin()); } } return bytes_available; } void *MachProcess::ProfileThread(void *arg) { MachProcess *proc = (MachProcess *)arg; DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( arg = %p ) thread starting...", __FUNCTION__, arg); #if defined(__APPLE__) pthread_setname_np("performance profiling thread"); #endif while (proc->IsProfilingEnabled()) { nub_state_t state = proc->GetState(); if (state == eStateRunning) { std::string data = proc->Task().GetProfileData(proc->GetProfileScanType()); if (!data.empty()) { proc->SignalAsyncProfileData(data.c_str()); } } else if ((state == eStateUnloaded) || (state == eStateDetached) || (state == eStateUnloaded)) { // Done. Get out of this thread. break; } timespec ts; { using namespace std::chrono; std::chrono::microseconds dur(proc->ProfileInterval()); const auto dur_secs = duration_cast<seconds>(dur); const auto dur_usecs = dur % std::chrono::seconds(1); DNBTimer::OffsetTimeOfDay(&ts, dur_secs.count(), dur_usecs.count()); } uint32_t bits_set = proc->m_profile_events.WaitForSetEvents(eMachProcessProfileCancel, &ts); // If we got bits back, we were told to exit. Do so. if (bits_set & eMachProcessProfileCancel) break; } return NULL; } pid_t MachProcess::AttachForDebug( pid_t pid, const RNBContext::IgnoredExceptions &ignored_exceptions, char *err_str, size_t err_len) { // Clear out and clean up from any current state Clear(); if (pid != 0) { DNBError err; // Make sure the process exists... if (::getpgid(pid) < 0) { err.SetErrorToErrno(); const char *err_cstr = err.AsString(); ::snprintf(err_str, err_len, "%s", err_cstr ? err_cstr : "No such process"); DNBLogError ("MachProcess::AttachForDebug pid %d does not exist", pid); return INVALID_NUB_PROCESS; } SetState(eStateAttaching); m_pid = pid; if (!m_task.StartExceptionThread(ignored_exceptions, err)) { const char *err_cstr = err.AsString(); ::snprintf(err_str, err_len, "%s", err_cstr ? err_cstr : "unable to start the exception thread"); DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid); DNBLogError( "[LaunchAttach] END (%d) MachProcess::AttachForDebug failed to start " "exception thread attaching to pid %i: %s", getpid(), pid, err_str); m_pid = INVALID_NUB_PROCESS; return INVALID_NUB_PROCESS; } DNBLog("[LaunchAttach] (%d) About to ptrace(PT_ATTACHEXC, %d)...", getpid(), pid); errno = 0; int ptrace_result = ::ptrace(PT_ATTACHEXC, pid, 0, 0); int ptrace_errno = errno; DNBLog("[LaunchAttach] (%d) Completed ptrace(PT_ATTACHEXC, %d) == %d", getpid(), pid, ptrace_result); if (ptrace_result != 0) { err.SetError(ptrace_errno); DNBLogError("MachProcess::AttachForDebug failed to ptrace(PT_ATTACHEXC) " "pid %i: %s", pid, err.AsString()); } else { err.Clear(); } if (err.Success()) { m_flags |= eMachProcessFlagsAttached; // Sleep a bit to let the exception get received and set our process // status // to stopped. ::usleep(250000); DNBLog("[LaunchAttach] (%d) Done napping after ptrace(PT_ATTACHEXC)'ing", getpid()); DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", pid); return m_pid; } else { ::snprintf(err_str, err_len, "%s", err.AsString()); DNBLogError( "[LaunchAttach] (%d) MachProcess::AttachForDebug error: failed to " "attach to pid %d", getpid(), pid); struct kinfo_proc kinfo; int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}; size_t len = sizeof(struct kinfo_proc); if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), &kinfo, &len, NULL, 0) == 0 && len > 0) { if (kinfo.kp_proc.p_flag & P_TRACED) { ::snprintf(err_str, err_len, "%s - process %d is already being debugged", err.AsString(), pid); DNBLogError( "[LaunchAttach] (%d) MachProcess::AttachForDebug pid %d is " "already being debugged", getpid(), pid); } } } } return INVALID_NUB_PROCESS; } Genealogy::ThreadActivitySP MachProcess::GetGenealogyInfoForThread(nub_thread_t tid, bool &timed_out) { return m_activities.GetGenealogyInfoForThread(m_pid, tid, m_thread_list, m_task.TaskPort(), timed_out); } Genealogy::ProcessExecutableInfoSP MachProcess::GetGenealogyImageInfo(size_t idx) { return m_activities.GetProcessExecutableInfosAtIndex(idx); } bool MachProcess::GetOSVersionNumbers(uint64_t *major, uint64_t *minor, uint64_t *patch) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSOperatingSystemVersion vers = [[NSProcessInfo processInfo] operatingSystemVersion]; if (major) *major = vers.majorVersion; if (minor) *minor = vers.minorVersion; if (patch) *patch = vers.patchVersion; [pool drain]; return true; } std::string MachProcess::GetMacCatalystVersionString() { @autoreleasepool { NSDictionary *version_info = [NSDictionary dictionaryWithContentsOfFile: @"/System/Library/CoreServices/SystemVersion.plist"]; NSString *version_value = [version_info objectForKey: @"iOSSupportVersion"]; if (const char *version_str = [version_value UTF8String]) return version_str; } return {}; } #if defined(WITH_SPRINGBOARD) || defined(WITH_BKS) || defined(WITH_FBS) /// Get the app bundle from the given path. Returns the empty string if the /// path doesn't appear to be an app bundle. static std::string GetAppBundle(std::string path) { auto pos = path.rfind(".app"); // Path doesn't contain `.app`. if (pos == std::string::npos) return {}; // Path has `.app` extension. if (pos == path.size() - 4) return path.substr(0, pos + 4); // Look for `.app` before a path separator. do { if (path[pos + 4] == '/') return path.substr(0, pos + 4); path = path.substr(0, pos); pos = path.rfind(".app"); } while (pos != std::string::npos); return {}; } #endif // Do the process specific setup for attach. If this returns NULL, then there's // no // platform specific stuff to be done to wait for the attach. If you get // non-null, // pass that token to the CheckForProcess method, and then to // CleanupAfterAttach. // Call PrepareForAttach before attaching to a process that has not yet // launched // This returns a token that can be passed to CheckForProcess, and to // CleanupAfterAttach. // You should call CleanupAfterAttach to free the token, and do whatever other // cleanup seems good. const void *MachProcess::PrepareForAttach(const char *path, nub_launch_flavor_t launch_flavor, bool waitfor, DNBError &attach_err) { #if defined(WITH_SPRINGBOARD) || defined(WITH_BKS) || defined(WITH_FBS) // Tell SpringBoard to halt the next launch of this application on startup. if (!waitfor) return NULL; std::string app_bundle_path = GetAppBundle(path); if (app_bundle_path.empty()) { DNBLogThreadedIf( LOG_PROCESS, "MachProcess::PrepareForAttach(): path '%s' doesn't contain .app, " "we can't tell springboard to wait for launch...", path); return NULL; } #if defined(WITH_FBS) if (launch_flavor == eLaunchFlavorDefault) launch_flavor = eLaunchFlavorFBS; if (launch_flavor != eLaunchFlavorFBS) return NULL; #elif defined(WITH_BKS) if (launch_flavor == eLaunchFlavorDefault) launch_flavor = eLaunchFlavorBKS; if (launch_flavor != eLaunchFlavorBKS) return NULL; #elif defined(WITH_SPRINGBOARD) if (launch_flavor == eLaunchFlavorDefault) launch_flavor = eLaunchFlavorSpringBoard; if (launch_flavor != eLaunchFlavorSpringBoard) return NULL; #endif CFStringRef bundleIDCFStr = CopyBundleIDForPath(app_bundle_path.c_str(), attach_err); std::string bundleIDStr; CFString::UTF8(bundleIDCFStr, bundleIDStr); DNBLogThreadedIf(LOG_PROCESS, "CopyBundleIDForPath (%s, err_str) returned @\"%s\"", app_bundle_path.c_str(), bundleIDStr.c_str()); if (bundleIDCFStr == NULL) { return NULL; } #if defined(WITH_FBS) if (launch_flavor == eLaunchFlavorFBS) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *stdio_path = nil; NSFileManager *file_manager = [NSFileManager defaultManager]; const char *null_path = "/dev/null"; stdio_path = [file_manager stringWithFileSystemRepresentation:null_path length:strlen(null_path)]; NSMutableDictionary *debug_options = [NSMutableDictionary dictionary]; NSMutableDictionary *options = [NSMutableDictionary dictionary]; DNBLogThreadedIf(LOG_PROCESS, "Calling BKSSystemService openApplication: " "@\"%s\",options include stdio path: \"%s\", " "BKSDebugOptionKeyDebugOnNextLaunch & " "BKSDebugOptionKeyWaitForDebugger )", bundleIDStr.c_str(), null_path); [debug_options setObject:stdio_path forKey:FBSDebugOptionKeyStandardOutPath]; [debug_options setObject:stdio_path forKey:FBSDebugOptionKeyStandardErrorPath]; [debug_options setObject:[NSNumber numberWithBool:YES] forKey:FBSDebugOptionKeyWaitForDebugger]; [debug_options setObject:[NSNumber numberWithBool:YES] forKey:FBSDebugOptionKeyDebugOnNextLaunch]; [options setObject:debug_options forKey:FBSOpenApplicationOptionKeyDebuggingOptions]; FBSSystemService *system_service = [[FBSSystemService alloc] init]; mach_port_t client_port = [system_service createClientPort]; __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); __block FBSOpenApplicationErrorCode attach_error_code = FBSOpenApplicationErrorCodeNone; NSString *bundleIDNSStr = (NSString *)bundleIDCFStr; DNBLog("[LaunchAttach] START (%d) requesting FBS launch of app with bundle " "ID '%s'", getpid(), bundleIDStr.c_str()); [system_service openApplication:bundleIDNSStr options:options clientPort:client_port withResult:^(NSError *error) { // The system service will cleanup the client port we // created for us. if (error) attach_error_code = (FBSOpenApplicationErrorCode)[error code]; [system_service release]; dispatch_semaphore_signal(semaphore); }]; const uint32_t timeout_secs = 9; dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, timeout_secs * NSEC_PER_SEC); long success = dispatch_semaphore_wait(semaphore, timeout) == 0; if (!success) { DNBLogError("timed out trying to launch %s.", bundleIDStr.c_str()); attach_err.SetErrorString( "debugserver timed out waiting for openApplication to complete."); attach_err.SetError(OPEN_APPLICATION_TIMEOUT_ERROR, DNBError::Generic); } else if (attach_error_code != FBSOpenApplicationErrorCodeNone) { std::string empty_str; SetFBSError(attach_error_code, empty_str, attach_err); DNBLogError("unable to launch the application with CFBundleIdentifier " "'%s' bks_error = %ld", bundleIDStr.c_str(), (NSInteger)attach_error_code); } dispatch_release(semaphore); [pool drain]; } #endif #if defined(WITH_BKS) if (launch_flavor == eLaunchFlavorBKS) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *stdio_path = nil; NSFileManager *file_manager = [NSFileManager defaultManager]; const char *null_path = "/dev/null"; stdio_path = [file_manager stringWithFileSystemRepresentation:null_path length:strlen(null_path)]; NSMutableDictionary *debug_options = [NSMutableDictionary dictionary]; NSMutableDictionary *options = [NSMutableDictionary dictionary]; DNBLogThreadedIf(LOG_PROCESS, "Calling BKSSystemService openApplication: " "@\"%s\",options include stdio path: \"%s\", " "BKSDebugOptionKeyDebugOnNextLaunch & " "BKSDebugOptionKeyWaitForDebugger )", bundleIDStr.c_str(), null_path); [debug_options setObject:stdio_path forKey:BKSDebugOptionKeyStandardOutPath]; [debug_options setObject:stdio_path forKey:BKSDebugOptionKeyStandardErrorPath]; [debug_options setObject:[NSNumber numberWithBool:YES] forKey:BKSDebugOptionKeyWaitForDebugger]; [debug_options setObject:[NSNumber numberWithBool:YES] forKey:BKSDebugOptionKeyDebugOnNextLaunch]; [options setObject:debug_options forKey:BKSOpenApplicationOptionKeyDebuggingOptions]; BKSSystemService *system_service = [[BKSSystemService alloc] init]; mach_port_t client_port = [system_service createClientPort]; __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); __block BKSOpenApplicationErrorCode attach_error_code = BKSOpenApplicationErrorCodeNone; NSString *bundleIDNSStr = (NSString *)bundleIDCFStr; DNBLog("[LaunchAttach] START (%d) requesting BKS launch of app with bundle " "ID '%s'", getpid(), bundleIDStr.c_str()); [system_service openApplication:bundleIDNSStr options:options clientPort:client_port withResult:^(NSError *error) { // The system service will cleanup the client port we // created for us. if (error) attach_error_code = (BKSOpenApplicationErrorCode)[error code]; [system_service release]; dispatch_semaphore_signal(semaphore); }]; const uint32_t timeout_secs = 9; dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, timeout_secs * NSEC_PER_SEC); long success = dispatch_semaphore_wait(semaphore, timeout) == 0; if (!success) { DNBLogError("timed out trying to launch %s.", bundleIDStr.c_str()); attach_err.SetErrorString( "debugserver timed out waiting for openApplication to complete."); attach_err.SetError(OPEN_APPLICATION_TIMEOUT_ERROR, DNBError::Generic); } else if (attach_error_code != BKSOpenApplicationErrorCodeNone) { std::string empty_str; SetBKSError(attach_error_code, empty_str, attach_err); DNBLogError("unable to launch the application with CFBundleIdentifier " "'%s' bks_error = %d", bundleIDStr.c_str(), attach_error_code); } dispatch_release(semaphore); [pool drain]; } #endif #if defined(WITH_SPRINGBOARD) if (launch_flavor == eLaunchFlavorSpringBoard) { SBSApplicationLaunchError sbs_error = 0; const char *stdout_err = "/dev/null"; CFString stdio_path; stdio_path.SetFileSystemRepresentation(stdout_err); DNBLogThreadedIf(LOG_PROCESS, "SBSLaunchApplicationForDebugging ( @\"%s\" " ", NULL, NULL, NULL, @\"%s\", @\"%s\", " "SBSApplicationDebugOnNextLaunch | " "SBSApplicationLaunchWaitForDebugger )", bundleIDStr.c_str(), stdout_err, stdout_err); DNBLog("[LaunchAttach] START (%d) requesting SpringBoard launch of app " "with bundle " "ID '%s'", getpid(), bundleIDStr.c_str()); sbs_error = SBSLaunchApplicationForDebugging( bundleIDCFStr, (CFURLRef)NULL, // openURL NULL, // launch_argv.get(), NULL, // launch_envp.get(), // CFDictionaryRef environment stdio_path.get(), stdio_path.get(), SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger); if (sbs_error != SBSApplicationLaunchErrorSuccess) { attach_err.SetError(sbs_error, DNBError::SpringBoard); return NULL; } } #endif // WITH_SPRINGBOARD DNBLogThreadedIf(LOG_PROCESS, "Successfully set DebugOnNextLaunch."); return bundleIDCFStr; #else // !(defined (WITH_SPRINGBOARD) || defined (WITH_BKS) || defined // (WITH_FBS)) return NULL; #endif } // Pass in the token you got from PrepareForAttach. If there is a process // for that token, then the pid will be returned, otherwise INVALID_NUB_PROCESS // will be returned. nub_process_t MachProcess::CheckForProcess(const void *attach_token, nub_launch_flavor_t launch_flavor) { if (attach_token == NULL) return INVALID_NUB_PROCESS; #if defined(WITH_FBS) if (launch_flavor == eLaunchFlavorFBS) { NSString *bundleIDNSStr = (NSString *)attach_token; FBSSystemService *systemService = [[FBSSystemService alloc] init]; pid_t pid = [systemService pidForApplication:bundleIDNSStr]; [systemService release]; if (pid == 0) return INVALID_NUB_PROCESS; else return pid; } #endif #if defined(WITH_BKS) if (launch_flavor == eLaunchFlavorBKS) { NSString *bundleIDNSStr = (NSString *)attach_token; BKSSystemService *systemService = [[BKSSystemService alloc] init]; pid_t pid = [systemService pidForApplication:bundleIDNSStr]; [systemService release]; if (pid == 0) return INVALID_NUB_PROCESS; else return pid; } #endif #if defined(WITH_SPRINGBOARD) if (launch_flavor == eLaunchFlavorSpringBoard) { CFStringRef bundleIDCFStr = (CFStringRef)attach_token; Boolean got_it; nub_process_t attach_pid; got_it = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &attach_pid); if (got_it) return attach_pid; else return INVALID_NUB_PROCESS; } #endif return INVALID_NUB_PROCESS; } // Call this to clean up after you have either attached or given up on the // attach. // Pass true for success if you have attached, false if you have not. // The token will also be freed at this point, so you can't use it after calling // this method. void MachProcess::CleanupAfterAttach(const void *attach_token, nub_launch_flavor_t launch_flavor, bool success, DNBError &err_str) { if (attach_token == NULL) return; #if defined(WITH_FBS) if (launch_flavor == eLaunchFlavorFBS) { if (!success) { FBSCleanupAfterAttach(attach_token, err_str); } CFRelease((CFStringRef)attach_token); } #endif #if defined(WITH_BKS) if (launch_flavor == eLaunchFlavorBKS) { if (!success) { BKSCleanupAfterAttach(attach_token, err_str); } CFRelease((CFStringRef)attach_token); } #endif #if defined(WITH_SPRINGBOARD) // Tell SpringBoard to cancel the debug on next launch of this application // if we failed to attach if (launch_flavor == eMachProcessFlagsUsingSpringBoard) { if (!success) { SBSApplicationLaunchError sbs_error = 0; CFStringRef bundleIDCFStr = (CFStringRef)attach_token; sbs_error = SBSLaunchApplicationForDebugging( bundleIDCFStr, (CFURLRef)NULL, NULL, NULL, NULL, NULL, SBSApplicationCancelDebugOnNextLaunch); if (sbs_error != SBSApplicationLaunchErrorSuccess) { err_str.SetError(sbs_error, DNBError::SpringBoard); return; } } CFRelease((CFStringRef)attach_token); } #endif } pid_t MachProcess::LaunchForDebug( const char *path, char const *argv[], char const *envp[], const char *working_directory, // NULL => don't change, non-NULL => set // working directory for inferior to this const char *stdin_path, const char *stdout_path, const char *stderr_path, bool no_stdio, nub_launch_flavor_t launch_flavor, int disable_aslr, const char *event_data, const RNBContext::IgnoredExceptions &ignored_exceptions, DNBError &launch_err) { // Clear out and clean up from any current state Clear(); DNBLogThreadedIf(LOG_PROCESS, "%s( path = '%s', argv = %p, envp = %p, " "launch_flavor = %u, disable_aslr = %d )", __FUNCTION__, path, static_cast<const void *>(argv), static_cast<const void *>(envp), launch_flavor, disable_aslr); // Fork a child process for debugging SetState(eStateLaunching); switch (launch_flavor) { case eLaunchFlavorForkExec: m_pid = MachProcess::ForkChildForPTraceDebugging(path, argv, envp, this, launch_err); break; #ifdef WITH_FBS case eLaunchFlavorFBS: { std::string app_bundle_path = GetAppBundle(path); if (!app_bundle_path.empty()) { m_flags |= (eMachProcessFlagsUsingFBS | eMachProcessFlagsBoardCalculated); if (BoardServiceLaunchForDebug(app_bundle_path.c_str(), argv, envp, no_stdio, disable_aslr, event_data, ignored_exceptions, launch_err) != 0) return m_pid; // A successful SBLaunchForDebug() returns and assigns a // non-zero m_pid. } DNBLog("Failed to launch '%s' with FBS", app_bundle_path); } break; #endif #ifdef WITH_BKS case eLaunchFlavorBKS: { std::string app_bundle_path = GetAppBundle(path); if (!app_bundle_path.empty()) { m_flags |= (eMachProcessFlagsUsingBKS | eMachProcessFlagsBoardCalculated); if (BoardServiceLaunchForDebug(app_bundle_path.c_str(), argv, envp, no_stdio, disable_aslr, event_data, ignored_exceptions, launch_err) != 0) return m_pid; // A successful SBLaunchForDebug() returns and assigns a // non-zero m_pid. } DNBLog("Failed to launch '%s' with BKS", app_bundle_path); } break; #endif #ifdef WITH_SPRINGBOARD case eLaunchFlavorSpringBoard: { std::string app_bundle_path = GetAppBundle(path); if (!app_bundle_path.empty()) { if (SBLaunchForDebug(app_bundle_path.c_str(), argv, envp, no_stdio, disable_aslr, ignored_exceptions, launch_err) != 0) return m_pid; // A successful SBLaunchForDebug() returns and assigns a // non-zero m_pid. } DNBLog("Failed to launch '%s' with SpringBoard", app_bundle_path); } break; #endif case eLaunchFlavorPosixSpawn: m_pid = MachProcess::PosixSpawnChildForPTraceDebugging( path, DNBArchProtocol::GetCPUType(), DNBArchProtocol::GetCPUSubType(), argv, envp, working_directory, stdin_path, stdout_path, stderr_path, no_stdio, this, disable_aslr, launch_err); break; default: DNBLog("Failed to launch: invalid launch flavor: %d", launch_flavor); launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic); return INVALID_NUB_PROCESS; } if (m_pid == INVALID_NUB_PROCESS) { // If we don't have a valid process ID and no one has set the error, // then return a generic error if (launch_err.Success()) launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic); } else { m_path = path; size_t i; char const *arg; for (i = 0; (arg = argv[i]) != NULL; i++) m_args.push_back(arg); m_task.StartExceptionThread(ignored_exceptions, launch_err); if (launch_err.Fail()) { if (launch_err.AsString() == NULL) launch_err.SetErrorString("unable to start the exception thread"); DNBLog("Could not get inferior's Mach exception port, sending ptrace " "PT_KILL and exiting."); ::ptrace(PT_KILL, m_pid, 0, 0); m_pid = INVALID_NUB_PROCESS; return INVALID_NUB_PROCESS; } StartSTDIOThread(); if (launch_flavor == eLaunchFlavorPosixSpawn) { SetState(eStateAttaching); errno = 0; DNBLog("[LaunchAttach] (%d) About to ptrace(PT_ATTACHEXC, %d)...", getpid(), m_pid); int err = ::ptrace(PT_ATTACHEXC, m_pid, 0, 0); int ptrace_errno = errno; DNBLog("[LaunchAttach] (%d) Completed ptrace(PT_ATTACHEXC, %d) == %d", getpid(), m_pid, err); if (err == 0) { m_flags |= eMachProcessFlagsAttached; DNBLogThreadedIf(LOG_PROCESS, "successfully spawned pid %d", m_pid); launch_err.Clear(); } else { SetState(eStateExited); DNBError ptrace_err(ptrace_errno, DNBError::POSIX); DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to spawned pid " "%d (err = %i, errno = %i (%s))", m_pid, err, ptrace_err.Status(), ptrace_err.AsString()); launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic); } } else { launch_err.Clear(); } } return m_pid; } pid_t MachProcess::PosixSpawnChildForPTraceDebugging( const char *path, cpu_type_t cpu_type, cpu_subtype_t cpu_subtype, char const *argv[], char const *envp[], const char *working_directory, const char *stdin_path, const char *stdout_path, const char *stderr_path, bool no_stdio, MachProcess *process, int disable_aslr, DNBError &err) { posix_spawnattr_t attr; short flags; DNBLogThreadedIf(LOG_PROCESS, "%s ( path='%s', argv=%p, envp=%p, " "working_dir=%s, stdin=%s, stdout=%s " "stderr=%s, no-stdio=%i)", __FUNCTION__, path, static_cast<const void *>(argv), static_cast<const void *>(envp), working_directory, stdin_path, stdout_path, stderr_path, no_stdio); err.SetError(::posix_spawnattr_init(&attr), DNBError::POSIX); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded("::posix_spawnattr_init ( &attr )"); if (err.Fail()) return INVALID_NUB_PROCESS; flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETPGROUP; if (disable_aslr) flags |= _POSIX_SPAWN_DISABLE_ASLR; sigset_t no_signals; sigset_t all_signals; sigemptyset(&no_signals); sigfillset(&all_signals); ::posix_spawnattr_setsigmask(&attr, &no_signals); ::posix_spawnattr_setsigdefault(&attr, &all_signals); err.SetError(::posix_spawnattr_setflags(&attr, flags), DNBError::POSIX); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded( "::posix_spawnattr_setflags ( &attr, POSIX_SPAWN_START_SUSPENDED%s )", flags & _POSIX_SPAWN_DISABLE_ASLR ? " | _POSIX_SPAWN_DISABLE_ASLR" : ""); if (err.Fail()) return INVALID_NUB_PROCESS; // Don't do this on SnowLeopard, _sometimes_ the TASK_BASIC_INFO will fail // and we will fail to continue with our process... // On SnowLeopard we should set "DYLD_NO_PIE" in the inferior environment.... if (cpu_type != 0) { size_t ocount = 0; bool slice_preference_set = false; if (cpu_subtype != 0) { typedef int (*posix_spawnattr_setarchpref_np_t)( posix_spawnattr_t *, size_t, cpu_type_t *, cpu_subtype_t *, size_t *); posix_spawnattr_setarchpref_np_t posix_spawnattr_setarchpref_np_fn = (posix_spawnattr_setarchpref_np_t)dlsym( RTLD_DEFAULT, "posix_spawnattr_setarchpref_np"); if (posix_spawnattr_setarchpref_np_fn) { err.SetError((*posix_spawnattr_setarchpref_np_fn)( &attr, 1, &cpu_type, &cpu_subtype, &ocount)); slice_preference_set = err.Success(); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded( "::posix_spawnattr_setarchpref_np ( &attr, 1, cpu_type = " "0x%8.8x, cpu_subtype = 0x%8.8x, count => %llu )", cpu_type, cpu_subtype, (uint64_t)ocount); if (err.Fail() != 0 || ocount != 1) return INVALID_NUB_PROCESS; } } if (!slice_preference_set) { err.SetError( ::posix_spawnattr_setbinpref_np(&attr, 1, &cpu_type, &ocount), DNBError::POSIX); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded( "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = " "0x%8.8x, count => %llu )", cpu_type, (uint64_t)ocount); if (err.Fail() != 0 || ocount != 1) return INVALID_NUB_PROCESS; } } PseudoTerminal pty; posix_spawn_file_actions_t file_actions; err.SetError(::posix_spawn_file_actions_init(&file_actions), DNBError::POSIX); int file_actions_valid = err.Success(); if (!file_actions_valid || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded("::posix_spawn_file_actions_init ( &file_actions )"); int pty_error = -1; pid_t pid = INVALID_NUB_PROCESS; if (file_actions_valid) { if (stdin_path == NULL && stdout_path == NULL && stderr_path == NULL && !no_stdio) { pty_error = pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY); if (pty_error == PseudoTerminal::success) { stdin_path = stdout_path = stderr_path = pty.SecondaryName(); } } // if no_stdio or std paths not supplied, then route to "/dev/null". if (no_stdio || stdin_path == NULL || stdin_path[0] == '\0') stdin_path = "/dev/null"; if (no_stdio || stdout_path == NULL || stdout_path[0] == '\0') stdout_path = "/dev/null"; if (no_stdio || stderr_path == NULL || stderr_path[0] == '\0') stderr_path = "/dev/null"; err.SetError(::posix_spawn_file_actions_addopen(&file_actions, STDIN_FILENO, stdin_path, O_RDONLY | O_NOCTTY, 0), DNBError::POSIX); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded("::posix_spawn_file_actions_addopen (&file_actions, " "filedes=STDIN_FILENO, path='%s')", stdin_path); err.SetError(::posix_spawn_file_actions_addopen( &file_actions, STDOUT_FILENO, stdout_path, O_WRONLY | O_NOCTTY | O_CREAT, 0640), DNBError::POSIX); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded("::posix_spawn_file_actions_addopen (&file_actions, " "filedes=STDOUT_FILENO, path='%s')", stdout_path); err.SetError(::posix_spawn_file_actions_addopen( &file_actions, STDERR_FILENO, stderr_path, O_WRONLY | O_NOCTTY | O_CREAT, 0640), DNBError::POSIX); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded("::posix_spawn_file_actions_addopen (&file_actions, " "filedes=STDERR_FILENO, path='%s')", stderr_path); // TODO: Verify if we can set the working directory back immediately // after the posix_spawnp call without creating a race condition??? if (working_directory) ::chdir(working_directory); err.SetError(::posix_spawnp(&pid, path, &file_actions, &attr, const_cast<char *const *>(argv), const_cast<char *const *>(envp)), DNBError::POSIX); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = " "%p, attr = %p, argv = %p, envp = %p )", pid, path, &file_actions, &attr, argv, envp); } else { // TODO: Verify if we can set the working directory back immediately // after the posix_spawnp call without creating a race condition??? if (working_directory) ::chdir(working_directory); err.SetError(::posix_spawnp(&pid, path, NULL, &attr, const_cast<char *const *>(argv), const_cast<char *const *>(envp)), DNBError::POSIX); if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = " "%p, attr = %p, argv = %p, envp = %p )", pid, path, NULL, &attr, argv, envp); } // We have seen some cases where posix_spawnp was returning a valid // looking pid even when an error was returned, so clear it out if (err.Fail()) pid = INVALID_NUB_PROCESS; if (pty_error == 0) { if (process != NULL) { int primary_fd = pty.ReleasePrimaryFD(); process->SetChildFileDescriptors(primary_fd, primary_fd, primary_fd); } } ::posix_spawnattr_destroy(&attr); if (pid != INVALID_NUB_PROCESS) { cpu_type_t pid_cpu_type = MachProcess::GetCPUTypeForLocalProcess(pid); DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( ) pid=%i, cpu_type=0x%8.8x", __FUNCTION__, pid, pid_cpu_type); if (pid_cpu_type) DNBArchProtocol::SetArchitecture(pid_cpu_type); } if (file_actions_valid) { DNBError err2; err2.SetError(::posix_spawn_file_actions_destroy(&file_actions), DNBError::POSIX); if (err2.Fail() || DNBLogCheckLogBit(LOG_PROCESS)) err2.LogThreaded("::posix_spawn_file_actions_destroy ( &file_actions )"); } return pid; } uint32_t MachProcess::GetCPUTypeForLocalProcess(pid_t pid) { int mib[CTL_MAXNAME] = { 0, }; size_t len = CTL_MAXNAME; if (::sysctlnametomib("sysctl.proc_cputype", mib, &len)) return 0; mib[len] = pid; len++; cpu_type_t cpu; size_t cpu_len = sizeof(cpu); if (::sysctl(mib, static_cast<u_int>(len), &cpu, &cpu_len, 0, 0)) cpu = 0; return cpu; } pid_t MachProcess::ForkChildForPTraceDebugging(const char *path, char const *argv[], char const *envp[], MachProcess *process, DNBError &launch_err) { PseudoTerminal::Status pty_error = PseudoTerminal::success; // Use a fork that ties the child process's stdin/out/err to a pseudo // terminal so we can read it in our MachProcess::STDIOThread // as unbuffered io. PseudoTerminal pty; pid_t pid = pty.Fork(pty_error); if (pid < 0) { //-------------------------------------------------------------- // Status during fork. //-------------------------------------------------------------- return pid; } else if (pid == 0) { //-------------------------------------------------------------- // Child process //-------------------------------------------------------------- ::ptrace(PT_TRACE_ME, 0, 0, 0); // Debug this process ::ptrace(PT_SIGEXC, 0, 0, 0); // Get BSD signals as mach exceptions // If our parent is setgid, lets make sure we don't inherit those // extra powers due to nepotism. if (::setgid(getgid()) == 0) { // Let the child have its own process group. We need to execute // this call in both the child and parent to avoid a race condition // between the two processes. ::setpgid(0, 0); // Set the child process group to match its pid // Sleep a bit to before the exec call ::sleep(1); // Turn this process into ::execv(path, const_cast<char *const *>(argv)); } // Exit with error code. Child process should have taken // over in above exec call and if the exec fails it will // exit the child process below. ::exit(127); } else { //-------------------------------------------------------------- // Parent process //-------------------------------------------------------------- // Let the child have its own process group. We need to execute // this call in both the child and parent to avoid a race condition // between the two processes. ::setpgid(pid, pid); // Set the child process group to match its pid if (process != NULL) { // Release our primary pty file descriptor so the pty class doesn't // close it and so we can continue to use it in our STDIO thread int primary_fd = pty.ReleasePrimaryFD(); process->SetChildFileDescriptors(primary_fd, primary_fd, primary_fd); } } return pid; } #if defined(WITH_SPRINGBOARD) || defined(WITH_BKS) || defined(WITH_FBS) // This returns a CFRetained pointer to the Bundle ID for app_bundle_path, // or NULL if there was some problem getting the bundle id. static CFStringRef CopyBundleIDForPath(const char *app_bundle_path, DNBError &err_str) { CFBundle bundle(app_bundle_path); CFStringRef bundleIDCFStr = bundle.GetIdentifier(); std::string bundleID; if (CFString::UTF8(bundleIDCFStr, bundleID) == NULL) { struct stat app_bundle_stat; char err_msg[PATH_MAX]; if (::stat(app_bundle_path, &app_bundle_stat) < 0) { err_str.SetError(errno, DNBError::POSIX); snprintf(err_msg, sizeof(err_msg), "%s: \"%s\"", err_str.AsString(), app_bundle_path); err_str.SetErrorString(err_msg); DNBLogThreadedIf(LOG_PROCESS, "%s() error: %s", __FUNCTION__, err_msg); } else { err_str.SetError(-1, DNBError::Generic); snprintf(err_msg, sizeof(err_msg), "failed to extract CFBundleIdentifier from %s", app_bundle_path); err_str.SetErrorString(err_msg); DNBLogThreadedIf( LOG_PROCESS, "%s() error: failed to extract CFBundleIdentifier from '%s'", __FUNCTION__, app_bundle_path); } return NULL; } DNBLogThreadedIf(LOG_PROCESS, "%s() extracted CFBundleIdentifier: %s", __FUNCTION__, bundleID.c_str()); CFRetain(bundleIDCFStr); return bundleIDCFStr; } #endif // #if defined (WITH_SPRINGBOARD) || defined (WITH_BKS) || defined // (WITH_FBS) #ifdef WITH_SPRINGBOARD pid_t MachProcess::SBLaunchForDebug(const char *path, char const *argv[], char const *envp[], bool no_stdio, bool disable_aslr, const RNBContext::IgnoredExceptions &ignored_exceptions, DNBError &launch_err) { // Clear out and clean up from any current state Clear(); DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv)", __FUNCTION__, path); // Fork a child process for debugging SetState(eStateLaunching); m_pid = MachProcess::SBForkChildForPTraceDebugging(path, argv, envp, no_stdio, this, launch_err); if (m_pid != 0) { m_path = path; size_t i; char const *arg; for (i = 0; (arg = argv[i]) != NULL; i++) m_args.push_back(arg); m_task.StartExceptionThread(ignored_exceptions, launch_err); if (launch_err.Fail()) { if (launch_err.AsString() == NULL) launch_err.SetErrorString("unable to start the exception thread"); DNBLog("Could not get inferior's Mach exception port, sending ptrace " "PT_KILL and exiting."); ::ptrace(PT_KILL, m_pid, 0, 0); m_pid = INVALID_NUB_PROCESS; return INVALID_NUB_PROCESS; } StartSTDIOThread(); SetState(eStateAttaching); DNBLog("[LaunchAttach] (%d) About to ptrace(PT_ATTACHEXC, %d)...", getpid(), m_pid); int err = ::ptrace(PT_ATTACHEXC, m_pid, 0, 0); DNBLog("[LaunchAttach] (%d) Completed ptrace(PT_ATTACHEXC, %d) == %d", getpid(), m_pid, err); if (err == 0) { m_flags |= eMachProcessFlagsAttached; DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", m_pid); } else { SetState(eStateExited); DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", m_pid); } } return m_pid; } #include <servers/bootstrap.h> pid_t MachProcess::SBForkChildForPTraceDebugging( const char *app_bundle_path, char const *argv[], char const *envp[], bool no_stdio, MachProcess *process, DNBError &launch_err) { DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv, %p)", __FUNCTION__, app_bundle_path, process); CFAllocatorRef alloc = kCFAllocatorDefault; if (argv[0] == NULL) return INVALID_NUB_PROCESS; size_t argc = 0; // Count the number of arguments while (argv[argc] != NULL) argc++; // Enumerate the arguments size_t first_launch_arg_idx = 1; CFReleaser<CFMutableArrayRef> launch_argv; if (argv[first_launch_arg_idx]) { size_t launch_argc = argc > 0 ? argc - 1 : 0; launch_argv.reset( ::CFArrayCreateMutable(alloc, launch_argc, &kCFTypeArrayCallBacks)); size_t i; char const *arg; CFString launch_arg; for (i = first_launch_arg_idx; (i < argc) && ((arg = argv[i]) != NULL); i++) { launch_arg.reset( ::CFStringCreateWithCString(alloc, arg, kCFStringEncodingUTF8)); if (launch_arg.get() != NULL) CFArrayAppendValue(launch_argv.get(), launch_arg.get()); else break; } } // Next fill in the arguments dictionary. Note, the envp array is of the form // Variable=value but SpringBoard wants a CF dictionary. So we have to // convert // this here. CFReleaser<CFMutableDictionaryRef> launch_envp; if (envp[0]) { launch_envp.reset( ::CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); const char *value; int name_len; CFString name_string, value_string; for (int i = 0; envp[i] != NULL; i++) { value = strstr(envp[i], "="); // If the name field is empty or there's no =, skip it. Somebody's // messing with us. if (value == NULL || value == envp[i]) continue; name_len = value - envp[i]; // Now move value over the "=" value++; name_string.reset( ::CFStringCreateWithBytes(alloc, (const UInt8 *)envp[i], name_len, kCFStringEncodingUTF8, false)); value_string.reset( ::CFStringCreateWithCString(alloc, value, kCFStringEncodingUTF8)); CFDictionarySetValue(launch_envp.get(), name_string.get(), value_string.get()); } } CFString stdio_path; PseudoTerminal pty; if (!no_stdio) { PseudoTerminal::Status pty_err = pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY); if (pty_err == PseudoTerminal::success) { const char *secondary_name = pty.SecondaryName(); DNBLogThreadedIf(LOG_PROCESS, "%s() successfully opened primary pty, secondary is %s", __FUNCTION__, secondary_name); if (secondary_name && secondary_name[0]) { ::chmod(secondary_name, S_IRWXU | S_IRWXG | S_IRWXO); stdio_path.SetFileSystemRepresentation(secondary_name); } } } if (stdio_path.get() == NULL) { stdio_path.SetFileSystemRepresentation("/dev/null"); } CFStringRef bundleIDCFStr = CopyBundleIDForPath(app_bundle_path, launch_err); if (bundleIDCFStr == NULL) return INVALID_NUB_PROCESS; // This is just for logging: std::string bundleID; CFString::UTF8(bundleIDCFStr, bundleID); DNBLogThreadedIf(LOG_PROCESS, "%s() serialized launch arg array", __FUNCTION__); // Find SpringBoard SBSApplicationLaunchError sbs_error = 0; sbs_error = SBSLaunchApplicationForDebugging( bundleIDCFStr, (CFURLRef)NULL, // openURL launch_argv.get(), launch_envp.get(), // CFDictionaryRef environment stdio_path.get(), stdio_path.get(), SBSApplicationLaunchWaitForDebugger | SBSApplicationLaunchUnlockDevice); launch_err.SetError(sbs_error, DNBError::SpringBoard); if (sbs_error == SBSApplicationLaunchErrorSuccess) { static const useconds_t pid_poll_interval = 200000; static const useconds_t pid_poll_timeout = 30000000; useconds_t pid_poll_total = 0; nub_process_t pid = INVALID_NUB_PROCESS; Boolean pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid); // Poll until the process is running, as long as we are getting valid // responses and the timeout hasn't expired // A return PID of 0 means the process is not running, which may be because // it hasn't been (asynchronously) started // yet, or that it died very quickly (if you weren't using waitForDebugger). while (!pid_found && pid_poll_total < pid_poll_timeout) { usleep(pid_poll_interval); pid_poll_total += pid_poll_interval; DNBLogThreadedIf(LOG_PROCESS, "%s() polling Springboard for pid for %s...", __FUNCTION__, bundleID.c_str()); pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid); } CFRelease(bundleIDCFStr); if (pid_found) { if (process != NULL) { // Release our primary pty file descriptor so the pty class doesn't // close it and so we can continue to use it in our STDIO thread int primary_fd = pty.ReleasePrimaryFD(); process->SetChildFileDescriptors(primary_fd, primary_fd, primary_fd); } DNBLogThreadedIf(LOG_PROCESS, "%s() => pid = %4.4x", __FUNCTION__, pid); } else { DNBLogError("failed to lookup the process ID for CFBundleIdentifier %s.", bundleID.c_str()); } return pid; } DNBLogError("unable to launch the application with CFBundleIdentifier '%s' " "sbs_error = %u", bundleID.c_str(), sbs_error); return INVALID_NUB_PROCESS; } #endif // #ifdef WITH_SPRINGBOARD #if defined(WITH_BKS) || defined(WITH_FBS) pid_t MachProcess::BoardServiceLaunchForDebug( const char *path, char const *argv[], char const *envp[], bool no_stdio, bool disable_aslr, const char *event_data, const RNBContext::IgnoredExceptions &ignored_exceptions, DNBError &launch_err) { DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv)", __FUNCTION__, path); // Fork a child process for debugging SetState(eStateLaunching); m_pid = BoardServiceForkChildForPTraceDebugging( path, argv, envp, no_stdio, disable_aslr, event_data, launch_err); if (m_pid != 0) { m_path = path; size_t i; char const *arg; for (i = 0; (arg = argv[i]) != NULL; i++) m_args.push_back(arg); m_task.StartExceptionThread(ignored_exceptions, launch_err); if (launch_err.Fail()) { if (launch_err.AsString() == NULL) launch_err.SetErrorString("unable to start the exception thread"); DNBLog("[LaunchAttach] END (%d) Could not get inferior's Mach exception " "port, " "sending ptrace " "PT_KILL to pid %i and exiting.", getpid(), m_pid); ::ptrace(PT_KILL, m_pid, 0, 0); m_pid = INVALID_NUB_PROCESS; return INVALID_NUB_PROCESS; } StartSTDIOThread(); SetState(eStateAttaching); DNBLog("[LaunchAttach] (%d) About to ptrace(PT_ATTACHEXC, %d)...", getpid(), m_pid); int err = ::ptrace(PT_ATTACHEXC, m_pid, 0, 0); DNBLog("[LaunchAttach] (%d) Completed ptrace(PT_ATTACHEXC, %d) == %d", getpid(), m_pid, err); if (err == 0) { m_flags |= eMachProcessFlagsAttached; DNBLog("[LaunchAttach] successfully attached to pid %d", m_pid); } else { SetState(eStateExited); DNBLog("[LaunchAttach] END (%d) error: failed to attach to pid %d", getpid(), m_pid); } } return m_pid; } pid_t MachProcess::BoardServiceForkChildForPTraceDebugging( const char *app_bundle_path, char const *argv[], char const *envp[], bool no_stdio, bool disable_aslr, const char *event_data, DNBError &launch_err) { if (argv[0] == NULL) return INVALID_NUB_PROCESS; DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv, %p)", __FUNCTION__, app_bundle_path, this); NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; size_t argc = 0; // Count the number of arguments while (argv[argc] != NULL) argc++; // Enumerate the arguments size_t first_launch_arg_idx = 1; NSMutableArray *launch_argv = nil; if (argv[first_launch_arg_idx]) { size_t launch_argc = argc > 0 ? argc - 1 : 0; launch_argv = [NSMutableArray arrayWithCapacity:launch_argc]; size_t i; char const *arg; NSString *launch_arg; for (i = first_launch_arg_idx; (i < argc) && ((arg = argv[i]) != NULL); i++) { launch_arg = [NSString stringWithUTF8String:arg]; // FIXME: Should we silently eat an argument that we can't convert into a // UTF8 string? if (launch_arg != nil) [launch_argv addObject:launch_arg]; else break; } } NSMutableDictionary *launch_envp = nil; if (envp[0]) { launch_envp = [[NSMutableDictionary alloc] init]; const char *value; int name_len; NSString *name_string, *value_string; for (int i = 0; envp[i] != NULL; i++) { value = strstr(envp[i], "="); // If the name field is empty or there's no =, skip it. Somebody's // messing with us. if (value == NULL || value == envp[i]) continue; name_len = value - envp[i]; // Now move value over the "=" value++; name_string = [[NSString alloc] initWithBytes:envp[i] length:name_len encoding:NSUTF8StringEncoding]; value_string = [NSString stringWithUTF8String:value]; [launch_envp setObject:value_string forKey:name_string]; } } NSString *stdio_path = nil; NSFileManager *file_manager = [NSFileManager defaultManager]; PseudoTerminal pty; if (!no_stdio) { PseudoTerminal::Status pty_err = pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY); if (pty_err == PseudoTerminal::success) { const char *secondary_name = pty.SecondaryName(); DNBLogThreadedIf(LOG_PROCESS, "%s() successfully opened primary pty, secondary is %s", __FUNCTION__, secondary_name); if (secondary_name && secondary_name[0]) { ::chmod(secondary_name, S_IRWXU | S_IRWXG | S_IRWXO); stdio_path = [file_manager stringWithFileSystemRepresentation:secondary_name length:strlen(secondary_name)]; } } } if (stdio_path == nil) { const char *null_path = "/dev/null"; stdio_path = [file_manager stringWithFileSystemRepresentation:null_path length:strlen(null_path)]; } CFStringRef bundleIDCFStr = CopyBundleIDForPath(app_bundle_path, launch_err); if (bundleIDCFStr == NULL) { [pool drain]; return INVALID_NUB_PROCESS; } // Instead of rewriting CopyBundleIDForPath for NSStrings, we'll just use // toll-free bridging here: NSString *bundleIDNSStr = (NSString *)bundleIDCFStr; // Okay, now let's assemble all these goodies into the BackBoardServices // options mega-dictionary: NSMutableDictionary *options = nullptr; pid_t return_pid = INVALID_NUB_PROCESS; bool success = false; #ifdef WITH_BKS if (ProcessUsingBackBoard()) { options = BKSCreateOptionsDictionary(app_bundle_path, launch_argv, launch_envp, stdio_path, disable_aslr, event_data); success = BKSCallOpenApplicationFunction(bundleIDNSStr, options, launch_err, &return_pid); } #endif #ifdef WITH_FBS if (ProcessUsingFrontBoard()) { options = FBSCreateOptionsDictionary(app_bundle_path, launch_argv, launch_envp, stdio_path, disable_aslr, event_data); success = FBSCallOpenApplicationFunction(bundleIDNSStr, options, launch_err, &return_pid); } #endif if (success) { int primary_fd = pty.ReleasePrimaryFD(); SetChildFileDescriptors(primary_fd, primary_fd, primary_fd); CFString::UTF8(bundleIDCFStr, m_bundle_id); } [pool drain]; return return_pid; } bool MachProcess::BoardServiceSendEvent(const char *event_data, DNBError &send_err) { bool return_value = true; if (event_data == NULL || *event_data == '\0') { DNBLogError("SendEvent called with NULL event data."); send_err.SetErrorString("SendEvent called with empty event data"); return false; } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (strcmp(event_data, "BackgroundApplication") == 0) { // This is an event I cooked up. What you actually do is foreground the system // app, so: #ifdef WITH_BKS if (ProcessUsingBackBoard()) { return_value = BKSCallOpenApplicationFunction(nil, nil, send_err, NULL); } #endif #ifdef WITH_FBS if (ProcessUsingFrontBoard()) { return_value = FBSCallOpenApplicationFunction(nil, nil, send_err, NULL); } #endif if (!return_value) { DNBLogError("Failed to background application, error: %s.", send_err.AsString()); } } else { if (m_bundle_id.empty()) { // See if we can figure out the bundle ID for this PID: DNBLogError( "Tried to send event \"%s\" to a process that has no bundle ID.", event_data); return false; } NSString *bundleIDNSStr = [NSString stringWithUTF8String:m_bundle_id.c_str()]; NSMutableDictionary *options = [NSMutableDictionary dictionary]; #ifdef WITH_BKS if (ProcessUsingBackBoard()) { if (!BKSAddEventDataToOptions(options, event_data, send_err)) { [pool drain]; return false; } return_value = BKSCallOpenApplicationFunction(bundleIDNSStr, options, send_err, NULL); DNBLogThreadedIf(LOG_PROCESS, "Called BKSCallOpenApplicationFunction to send event."); } #endif #ifdef WITH_FBS if (ProcessUsingFrontBoard()) { if (!FBSAddEventDataToOptions(options, event_data, send_err)) { [pool drain]; return false; } return_value = FBSCallOpenApplicationFunction(bundleIDNSStr, options, send_err, NULL); DNBLogThreadedIf(LOG_PROCESS, "Called FBSCallOpenApplicationFunction to send event."); } #endif if (!return_value) { DNBLogError("Failed to send event: %s, error: %s.", event_data, send_err.AsString()); } } [pool drain]; return return_value; } #endif // defined(WITH_BKS) || defined (WITH_FBS) #ifdef WITH_BKS void MachProcess::BKSCleanupAfterAttach(const void *attach_token, DNBError &err_str) { bool success; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Instead of rewriting CopyBundleIDForPath for NSStrings, we'll just use // toll-free bridging here: NSString *bundleIDNSStr = (NSString *)attach_token; // Okay, now let's assemble all these goodies into the BackBoardServices // options mega-dictionary: // First we have the debug sub-dictionary: NSMutableDictionary *debug_options = [NSMutableDictionary dictionary]; [debug_options setObject:[NSNumber numberWithBool:YES] forKey:BKSDebugOptionKeyCancelDebugOnNextLaunch]; // That will go in the overall dictionary: NSMutableDictionary *options = [NSMutableDictionary dictionary]; [options setObject:debug_options forKey:BKSOpenApplicationOptionKeyDebuggingOptions]; success = BKSCallOpenApplicationFunction(bundleIDNSStr, options, err_str, NULL); if (!success) { DNBLogError("error trying to cancel debug on next launch for %s: %s", [bundleIDNSStr UTF8String], err_str.AsString()); } [pool drain]; } #endif // WITH_BKS #ifdef WITH_FBS void MachProcess::FBSCleanupAfterAttach(const void *attach_token, DNBError &err_str) { bool success; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Instead of rewriting CopyBundleIDForPath for NSStrings, we'll just use // toll-free bridging here: NSString *bundleIDNSStr = (NSString *)attach_token; // Okay, now let's assemble all these goodies into the BackBoardServices // options mega-dictionary: // First we have the debug sub-dictionary: NSMutableDictionary *debug_options = [NSMutableDictionary dictionary]; [debug_options setObject:[NSNumber numberWithBool:YES] forKey:FBSDebugOptionKeyCancelDebugOnNextLaunch]; // That will go in the overall dictionary: NSMutableDictionary *options = [NSMutableDictionary dictionary]; [options setObject:debug_options forKey:FBSOpenApplicationOptionKeyDebuggingOptions]; success = FBSCallOpenApplicationFunction(bundleIDNSStr, options, err_str, NULL); if (!success) { DNBLogError("error trying to cancel debug on next launch for %s: %s", [bundleIDNSStr UTF8String], err_str.AsString()); } [pool drain]; } #endif // WITH_FBS void MachProcess::CalculateBoardStatus() { if (m_flags & eMachProcessFlagsBoardCalculated) return; if (m_pid == 0) return; #if defined (WITH_FBS) || defined (WITH_BKS) bool found_app_flavor = false; #endif #if defined(WITH_FBS) if (!found_app_flavor && IsFBSProcess(m_pid)) { found_app_flavor = true; m_flags |= eMachProcessFlagsUsingFBS; } #endif #if defined(WITH_BKS) if (!found_app_flavor && IsBKSProcess(m_pid)) { found_app_flavor = true; m_flags |= eMachProcessFlagsUsingBKS; } #endif m_flags |= eMachProcessFlagsBoardCalculated; } bool MachProcess::ProcessUsingBackBoard() { CalculateBoardStatus(); return (m_flags & eMachProcessFlagsUsingBKS) != 0; } bool MachProcess::ProcessUsingFrontBoard() { CalculateBoardStatus(); return (m_flags & eMachProcessFlagsUsingFBS) != 0; } int MachProcess::GetInferiorAddrSize(pid_t pid) { int pointer_size = 8; int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}; struct kinfo_proc processInfo; size_t bufsize = sizeof(processInfo); if (sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo, &bufsize, NULL, 0) == 0 && bufsize > 0) { if ((processInfo.kp_proc.p_flag & P_LP64) == 0) pointer_size = 4; } return pointer_size; } ```
/content/code_sandbox/gnu/llvm/lldb/tools/debugserver/source/MacOSX/MachProcess.mm
xml
2016-08-30T18:18:25
2024-08-16T17:21:09
src
openbsd/src
3,139
38,482
```xml import { mount } from 'enzyme'; import React from 'react'; import DevModeNotification from '../lib/items/dev-mode-notif'; describe('DevModeNotif', function DevModeNotifTests() { describe('When the window is in dev mode', () => { beforeEach(() => { spyOn(AppEnv, 'inDevMode').andReturn(true); this.notif = mount(<DevModeNotification />); }); it('displays a notification', () => { expect(this.notif.find('.notification').exists()).toEqual(true); }); }); describe('When the window is not in dev mode', () => { beforeEach(() => { spyOn(AppEnv, 'inDevMode').andReturn(false); this.notif = mount(<DevModeNotification />); }); it("doesn't display a notification", () => { expect(this.notif.find('.notification').exists()).toEqual(false); }); }); }); ```
/content/code_sandbox/app/internal_packages/notifications/specs/dev-mode-notif-spec.tsx
xml
2016-10-13T06:45:50
2024-08-16T18:14:37
Mailspring
Foundry376/Mailspring
15,331
194
```xml import * as React from "react"; import { connect } from 'react-redux'; import { AssetEditorState, GalleryView } from './store/assetEditorReducerState'; import { dispatchChangeGalleryView } from './actions/dispatch'; interface AssetGalleryTabProps { title: string; view: GalleryView; selected: boolean; dispatchChangeGalleryView: (view: GalleryView) => void; } class AssetGalleryTabImpl extends React.Component<AssetGalleryTabProps> { handleClick = () => { pxt.tickEvent("assets.gallerytab", { view: this.props.view.toString() }); this.props.dispatchChangeGalleryView(this.props.view); } render() { const { title, selected } = this.props; return <div className={`asset-editor-gallery-tab ${selected ? "selected" : ""}`} onClick={this.handleClick} role="navigation"> {title} </div> } } function mapStateToProps(state: AssetEditorState, ownProps: any) { if (!state) return {}; return { selected: state.view == ownProps.view }; } const mapDispatchToProps = { dispatchChangeGalleryView }; export const AssetGalleryTab = connect(mapStateToProps, mapDispatchToProps)(AssetGalleryTabImpl); ```
/content/code_sandbox/webapp/src/components/assetEditor/assetGalleryTab.tsx
xml
2016-01-24T19:35:52
2024-08-16T16:39:39
pxt
microsoft/pxt
2,069
258
```xml import React, { FunctionComponent } from "react"; import BanAction, { BanActionProps } from "./BanAction"; import ModMessageAction, { ModMessageActionProps } from "./ModMessageAction"; import PremodAction, { PremodActionProps } from "./PremodAction"; import SiteBanAction from "./SiteBanAction"; import SuspensionAction, { SuspensionActionProps } from "./SuspensionAction"; import UserDeletionAction, { UserDeletionActionProps, } from "./UserDeletionAction"; import UsernameChangeAction, { UsernameChangeActionProps, } from "./UsernameChangeAction"; import WarningAction, { WarningActionProps } from "./WarningAction"; export interface HistoryActionProps { kind: | "username" | "suspension" | "ban" | "site-ban" | "premod" | "warning" | "modMessage" | "deletion"; action: | UsernameChangeActionProps | SuspensionActionProps | BanActionProps | PremodActionProps | WarningActionProps | ModMessageActionProps | UserDeletionActionProps; } const AccountHistoryAction: FunctionComponent<HistoryActionProps> = ({ kind, action, }) => { switch (kind) { case "username": return ( <UsernameChangeAction {...(action as UsernameChangeActionProps)} /> ); case "suspension": return <SuspensionAction {...(action as SuspensionActionProps)} />; case "ban": return <BanAction {...(action as BanActionProps)} />; case "site-ban": return <SiteBanAction {...(action as BanActionProps)} />; case "premod": return <PremodAction {...(action as PremodActionProps)} />; case "warning": return <WarningAction {...(action as WarningActionProps)} />; case "modMessage": return <ModMessageAction {...(action as ModMessageActionProps)} />; case "deletion": return <UserDeletionAction {...(action as UserDeletionActionProps)} />; default: return null; } }; export default AccountHistoryAction; ```
/content/code_sandbox/client/src/core/client/admin/components/UserHistoryDrawer/AccountHistoryAction.tsx
xml
2016-10-31T16:14:05
2024-08-06T16:15:57
talk
coralproject/talk
1,881
467
```xml import { Application } from 'app/model/application.model'; import { GroupPermission } from 'app/model/group.model'; import { ProjectIntegration } from 'app/model/integration.model'; import { Key } from 'app/model/keys.model'; import { Pipeline } from 'app/model/pipeline.model'; import { Label, LoadOpts, Project } from 'app/model/project.model'; import { Variable } from 'app/model/variable.model'; import { Workflow } from 'app/model/workflow.model'; import { Environment } from 'app/model/environment.model'; import { VariableSet } from 'app/model/variablesets.model'; // Use to load fetched Project in our app export class LoadProject { static readonly type = '[Project] Load Project'; constructor(public payload: Project) { } } // Use to fetch Project from backend export class FetchProject { static readonly type = '[Project] Fetch Project'; constructor(public payload: { projectKey: string, opts: LoadOpts[] }) { } } // Use to enrich Project from backend export class EnrichProject { static readonly type = '[Project] Enrich Project'; constructor(public payload: { projectKey: string, opts: LoadOpts[] }) { } } export class AddProject { static readonly type = '[Project] Add Project'; constructor(public payload: Project) { } } export class UpdateProject { static readonly type = '[Project] Update Project'; constructor(public payload: Project) { } } export class DeleteProject { static readonly type = '[Project] Delete Project'; constructor(public payload: { projectKey: string }) { } } export class ExternalChangeProject { static readonly type = '[Project] External Change Project'; constructor(public payload: { projectKey: string }) { } } export class DeleteProjectFromCache { static readonly type = '[Project] Delete Project From cache'; constructor(public payload: { projectKey: string }) { } } // ------- Misc --------- // export class UpdateFavoriteProject { static readonly type = '[Project] Update Project Favorite'; constructor(public payload: { projectKey: string }) { } } // ------- Variable Sets ---- // export class FetchVariableSetsInProject { static readonly type = '[Project] Fetch VariableSets in Project'; constructor(public payload: { projectKey: string }) { } } export class ResyncVariableSetsInProject { static readonly type = '[Project] Resync Variable Sets in Project'; constructor(public payload: { projectKey: string }) { } } export class LoadVariableSetsInProject { static readonly type = '[Project] Load Variable Sets in Project'; constructor(public payload: VariableSet[]) { } } export class DeleteVariableSetInProject { static readonly type = '[Project] Delete Variable Set in Project'; constructor(public payload: VariableSet) { } } export class AddVariableSetInProject { static readonly type = '[Project] Add VariableSet in Project'; constructor(public name: string) { } } // ------- Variable --------- // export class ResyncVariablesInProject { static readonly type = '[Project] Resync Variables in Project'; constructor(public payload: { projectKey: string }) { } } export class FetchVariablesInProject { static readonly type = '[Project] Fetch Variables in Project'; constructor(public payload: { projectKey: string }) { } } export class LoadVariablesInProject { static readonly type = '[Project] Load Variables in Project'; constructor(public payload: Variable[]) { } } export class AddVariableInProject { static readonly type = '[Project] Add Variable in Project'; constructor(public payload: Variable) { } } export class UpdateVariableInProject { static readonly type = '[Project] Update Variable in Project'; constructor(public payload: { variableName: string, changes: Variable }) { } } export class DeleteVariableInProject { static readonly type = '[Project] Delete Variable in Project'; constructor(public payload: Variable) { } } // ---------Environment --------- // export class AddEnvironmentInProject { static readonly type = '[Project] Add environment in Project'; constructor(public payload: Environment) { } } // ------- Application --------- // export class AddApplicationInProject { static readonly type = '[Project] Add application in Project'; constructor(public payload: Application) { } } export class UpdateApplicationInProject { static readonly type = '[Project] Update application in Project'; constructor(public payload: { previousAppName: string, changes: Application }) { } } export class DeleteApplicationInProject { static readonly type = '[Project] Delete application in Project'; constructor(public payload: { applicationName: string }) { } } // ------- Workflow --------- // export class AddWorkflowInProject { static readonly type = '[Project] Add Workflow in Project'; constructor(public payload: Workflow) { } } export class UpdateWorkflowInProject { static readonly type = '[Project] Update workflow in Project'; constructor(public payload: { previousWorkflowName: string, changes: Workflow }) { } } export class DeleteWorkflowInProject { static readonly type = '[Project] Delete Workflow in Project'; constructor(public payload: { workflowName: string }) { } } // ------- Pipeline --------- // export class AddPipelineInProject { static readonly type = '[Project] Add Pipeline in Project'; constructor(public payload: Pipeline) { } } export class UpdatePipelineInProject { static readonly type = '[Project] Update pipeline in Project'; constructor(public payload: { previousPipName: string, changes: Pipeline }) { } } export class DeletePipelineInProject { static readonly type = '[Project] Delete Pipeline in Project'; constructor(public payload: { pipelineName: string }) { } } // ------- Group Permission --------- // export class AddGroupInProject { static readonly type = '[Project] Add Group in Project'; constructor(public payload: { projectKey: string, group: GroupPermission, onlyProject?: boolean }) { } } export class UpdateGroupInProject { static readonly type = '[Project] Update Group in Project'; constructor(public payload: { projectKey: string, group: GroupPermission }) { } } export class DeleteGroupInProject { static readonly type = '[Project] Delete Group in Project'; constructor(public payload: { projectKey: string, group: GroupPermission }) { } } // ------- Label --------- // export class SaveLabelsInProject { static readonly type = '[Project] Save Labels in Project'; constructor(public payload: { projectKey: string, labels: Label[] }) { } } export class AddLabelInProject { static readonly type = '[Project] Add Label in Project'; constructor(public payload: { projectKey: string, label: Label }) { } } export class DeleteLabelProject { static readonly type = '[Project] Delete Label in Project'; constructor(public payload: { projectKey: string, label: Label }) { } } export class AddLabelWorkflowInProject { static readonly type = '[Project] Add Label on Workflow in Project'; constructor(public payload: { workflowName: string, label: Label }) { } } export class DeleteLabelWorkflowInProject { static readonly type = '[Project] Delete Label on Workflow in Project'; constructor(public payload: { workflowName: string, labelId: number }) { } } // ------- Integration --------- // export class ResyncIntegrationsInProject { static readonly type = '[Project] Resync Integrations in Project'; constructor(public payload: { projectKey: string }) { } } export class FetchIntegrationsInProject { static readonly type = '[Project] Fetch Integrations in Project'; constructor(public payload: { projectKey: string }) { } } export class LoadIntegrationsInProject { static readonly type = '[Project] Load Integrations in Project'; constructor(public payload: ProjectIntegration[]) { } } export class AddIntegrationInProject { static readonly type = '[Project] Add Integration in Project'; constructor(public payload: { projectKey: string, integration: ProjectIntegration }) { } } export class UpdateIntegrationInProject { static readonly type = '[Project] Update integration in Project'; constructor(public payload: { projectKey: string, integrationName: string, changes: ProjectIntegration }) { } } export class DeleteIntegrationInProject { static readonly type = '[Project] Delete Integration in Project'; constructor(public payload: { projectKey: string, integration: ProjectIntegration }) { } } // ------- Key --------- // export class ResyncKeysInProject { static readonly type = '[Project] Resync Keys in Project'; constructor(public payload: { projectKey: string }) { } } export class FetchKeysInProject { static readonly type = '[Project] Fetch Keys in Project'; constructor(public payload: { projectKey: string }) { } } export class LoadKeysInProject { static readonly type = '[Project] Load Keys in Project'; constructor(public payload: Key[]) { } } export class AddKeyInProject { static readonly type = '[Project] Add Key in Project'; constructor(public payload: { projectKey: string, key: Key }) { } } export class DeleteKeyInProject { static readonly type = '[Project] Delete Key in Project'; constructor(public payload: { projectKey: string, key: Key }) { } } // ------- Repository Manager --------- // export class ConnectRepositoryManagerInProject { static readonly type = '[Project] Connect Repository Manager in Project'; constructor(public payload: { projectKey: string, repoManager: string }) { } } export class DisconnectRepositoryManagerInProject { static readonly type = '[Project] Disconnect Repository Manager in Project'; constructor(public payload: { projectKey: string, repoManager: string }) { } } ```
/content/code_sandbox/ui/src/app/store/project.action.ts
xml
2016-10-11T08:28:23
2024-08-16T01:55:31
cds
ovh/cds
4,535
2,025
```xml <?xml version="1.0" encoding="utf-8"?> Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <TextView xmlns:android="path_to_url" android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawablePadding="20dp" android:gravity="center_vertical" android:minHeight="?android:attr/listPreferredItemHeightSmall" android:paddingEnd="15dp" android:paddingStart="15dp" android:singleLine="true" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@color/dark_mode_tint" /> ```
/content/code_sandbox/libraries_res/chrome_res/src/main/res/layout/bookmark_folder_select_item.xml
xml
2016-07-04T07:28:36
2024-08-15T05:20:42
AndroidChromium
JackyAndroid/AndroidChromium
3,090
157
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd"> <plist version="0.9"> <dict> <key>CFBundleName</key> <string>UnicodeConverter</string> <key>CFBundleVersion</key> <string>@@VERSION@@</string> <key>CFBundleShortVersionString</key> <string>@@VERSION@@</string> <key>CFBundleAllowMixedLocalizations</key> <string>true</string> <key>CFBundleExecutable</key> <string>JavaApplicationStub</string> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleIconFile</key> <string>GenericJavaApp.icns</string> <key>Java</key> <dict> <key>MainClass</key> <string>UnicodeConverter</string> <key>JVMVersion</key> <string>1.4+</string> <key>ClassPath</key> <string>$JAVAROOT/UnicodeConverter.jar</string> <key>Properties</key> <dict> <key>apple.laf.useScreenMenuBar</key> <string>true</string> </dict> </dict> </dict> </plist> ```
/content/code_sandbox/java/unicodeconverter-java/files/Info.plist
xml
2016-10-09T00:31:44
2024-08-16T18:11:47
macports-ports
macports/macports-ports
1,499
361
```xml /** * @name match-sorter * @license MIT license. * @copyright (c) 2020 Kent C. Dodds * @author Kent C. Dodds <me@kentcdodds.com> (path_to_url */ import removeAccents from 'remove-accents' type KeyAttributes = { threshold?: Ranking maxRanking: Ranking minRanking: Ranking } interface RankingInfo { rankedValue: string rank: Ranking keyIndex: number keyThreshold: Ranking | undefined } interface ValueGetterKey<ItemType> { (item: ItemType): string | Array<string> } interface IndexedItem<ItemType> { item: ItemType index: number } interface RankedItem<ItemType> extends RankingInfo, IndexedItem<ItemType> {} interface BaseSorter<ItemType> { (a: RankedItem<ItemType>, b: RankedItem<ItemType>): number } interface Sorter<ItemType> { (matchItems: Array<RankedItem<ItemType>>): Array<RankedItem<ItemType>> } interface KeyAttributesOptions<ItemType> { key?: string | ValueGetterKey<ItemType> threshold?: Ranking maxRanking?: Ranking minRanking?: Ranking } type KeyOption<ItemType> = | KeyAttributesOptions<ItemType> | ValueGetterKey<ItemType> | string interface MatchSorterOptions<ItemType = unknown> { keys?: ReadonlyArray<KeyOption<ItemType>> threshold?: Ranking baseSort?: BaseSorter<ItemType> keepDiacritics?: boolean sorter?: Sorter<ItemType> } type IndexableByString = Record<string, unknown> const rankings = { CASE_SENSITIVE_EQUAL: 7, EQUAL: 6, STARTS_WITH: 5, WORD_STARTS_WITH: 4, CONTAINS: 3, ACRONYM: 2, MATCHES: 1, NO_MATCH: 0, } as const type Ranking = typeof rankings[keyof typeof rankings] const defaultBaseSortFn: BaseSorter<unknown> = (a, b) => String(a.rankedValue).localeCompare(String(b.rankedValue)) /** * Takes an array of items and a value and returns a new array with the items that match the given value * @param {Array} items - the items to sort * @param {String} value - the value to use for ranking * @param {Object} options - Some options to configure the sorter * @return {Array} - the new sorted array */ function matchSorter<ItemType = string>( items: ReadonlyArray<ItemType>, value: string, options: MatchSorterOptions<ItemType> = {}, ): Array<ItemType> { const { keys, threshold = rankings.MATCHES, baseSort = defaultBaseSortFn, sorter = matchedItems => matchedItems.sort((a, b) => sortRankedValues(a, b, baseSort)), } = options const matchedItems = items.reduce(reduceItemsToRanked, []) return sorter(matchedItems).map(({item}) => item) function reduceItemsToRanked( matches: Array<RankedItem<ItemType>>, item: ItemType, index: number, ): Array<RankedItem<ItemType>> { const rankingInfo = getHighestRanking(item, keys, value, options) const {rank, keyThreshold = threshold} = rankingInfo if (rank >= keyThreshold) { matches.push({...rankingInfo, item, index}) } return matches } } matchSorter.rankings = rankings /** * Gets the highest ranking for value for the given item based on its values for the given keys * @param {*} item - the item to rank * @param {Array} keys - the keys to get values from the item for the ranking * @param {String} value - the value to rank against * @param {Object} options - options to control the ranking * @return {{rank: Number, keyIndex: Number, keyThreshold: Number}} - the highest ranking */ function getHighestRanking<ItemType>( item: ItemType, keys: ReadonlyArray<KeyOption<ItemType>> | undefined, value: string, options: MatchSorterOptions<ItemType>, ): RankingInfo { if (!keys) { // if keys is not specified, then we assume the item given is ready to be matched const stringItem = (item as unknown) as string return { // ends up being duplicate of 'item' in matches but consistent rankedValue: stringItem, rank: getMatchRanking(stringItem, value, options), keyIndex: -1, keyThreshold: options.threshold, } } const valuesToRank = getAllValuesToRank(item, keys) return valuesToRank.reduce( ( {rank, rankedValue, keyIndex, keyThreshold}, {itemValue, attributes}, i, ) => { let newRank = getMatchRanking(itemValue, value, options) let newRankedValue = rankedValue const {minRanking, maxRanking, threshold} = attributes if (newRank < minRanking && newRank >= rankings.MATCHES) { newRank = minRanking } else if (newRank > maxRanking) { newRank = maxRanking } if (newRank > rank) { rank = newRank keyIndex = i keyThreshold = threshold newRankedValue = itemValue } return {rankedValue: newRankedValue, rank, keyIndex, keyThreshold} }, { rankedValue: (item as unknown) as string, rank: rankings.NO_MATCH as Ranking, keyIndex: -1, keyThreshold: options.threshold, }, ) } /** * Gives a rankings score based on how well the two strings match. * @param {String} testString - the string to test against * @param {String} stringToRank - the string to rank * @param {Object} options - options for the match (like keepDiacritics for comparison) * @returns {Number} the ranking for how well stringToRank matches testString */ function getMatchRanking<ItemType>( testString: string, stringToRank: string, options: MatchSorterOptions<ItemType>, ): Ranking { testString = prepareValueForComparison(testString, options) stringToRank = prepareValueForComparison(stringToRank, options) // too long if (stringToRank.length > testString.length) { return rankings.NO_MATCH } // case sensitive equals if (testString === stringToRank) { return rankings.CASE_SENSITIVE_EQUAL } // Lower casing before further comparison testString = testString.toLowerCase() stringToRank = stringToRank.toLowerCase() // case insensitive equals if (testString === stringToRank) { return rankings.EQUAL } // starts with if (testString.startsWith(stringToRank)) { return rankings.STARTS_WITH } // word starts with if (testString.includes(` ${stringToRank}`)) { return rankings.WORD_STARTS_WITH } // contains if (testString.includes(stringToRank)) { return rankings.CONTAINS } else if (stringToRank.length === 1) { // If the only character in the given stringToRank // isn't even contained in the testString, then // it's definitely not a match. return rankings.NO_MATCH } // acronym if (getAcronym(testString).includes(stringToRank)) { return rankings.ACRONYM } // will return a number between rankings.MATCHES and // rankings.MATCHES + 1 depending on how close of a match it is. return getClosenessRanking(testString, stringToRank) } /** * Generates an acronym for a string. * * @param {String} string the string for which to produce the acronym * @returns {String} the acronym */ function getAcronym(string: string): string { let acronym = '' const wordsInString = string.split(' ') wordsInString.forEach(wordInString => { const splitByHyphenWords = wordInString.split('-') splitByHyphenWords.forEach(splitByHyphenWord => { acronym += splitByHyphenWord.substr(0, 1) }) }) return acronym } /** * Returns a score based on how spread apart the * characters from the stringToRank are within the testString. * A number close to rankings.MATCHES represents a loose match. A number close * to rankings.MATCHES + 1 represents a tighter match. * @param {String} testString - the string to test against * @param {String} stringToRank - the string to rank * @returns {Number} the number between rankings.MATCHES and * rankings.MATCHES + 1 for how well stringToRank matches testString */ function getClosenessRanking( testString: string, stringToRank: string, ): Ranking { let matchingInOrderCharCount = 0 let charNumber = 0 function findMatchingCharacter( matchChar: string, string: string, index: number, ) { for (let j = index, J = string.length; j < J; j++) { const stringChar = string[j] if (stringChar === matchChar) { matchingInOrderCharCount += 1 return j + 1 } } return -1 } function getRanking(spread: number) { const spreadPercentage = 1 / spread const inOrderPercentage = matchingInOrderCharCount / stringToRank.length const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage return ranking as Ranking } const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0) if (firstIndex < 0) { return rankings.NO_MATCH } charNumber = firstIndex for (let i = 1, I = stringToRank.length; i < I; i++) { const matchChar = stringToRank[i] charNumber = findMatchingCharacter(matchChar, testString, charNumber) const found = charNumber > -1 if (!found) { return rankings.NO_MATCH } } const spread = charNumber - firstIndex return getRanking(spread) } /** * Sorts items that have a rank, index, and keyIndex * @param {Object} a - the first item to sort * @param {Object} b - the second item to sort * @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal */ function sortRankedValues<ItemType>( a: RankedItem<ItemType>, b: RankedItem<ItemType>, baseSort: BaseSorter<ItemType>, ): number { const aFirst = -1 const bFirst = 1 const {rank: aRank, keyIndex: aKeyIndex} = a const {rank: bRank, keyIndex: bKeyIndex} = b const same = aRank === bRank if (same) { if (aKeyIndex === bKeyIndex) { // use the base sort function as a tie-breaker return baseSort(a, b) } else { return aKeyIndex < bKeyIndex ? aFirst : bFirst } } else { return aRank > bRank ? aFirst : bFirst } } /** * Prepares value for comparison by stringifying it, removing diacritics (if specified) * @param {String} value - the value to clean * @param {Object} options - {keepDiacritics: whether to remove diacritics} * @return {String} the prepared value */ function prepareValueForComparison<ItemType>( value: string, {keepDiacritics}: MatchSorterOptions<ItemType>, ): string { // value might not actually be a string at this point (we don't get to choose) // so part of preparing the value for comparison is ensure that it is a string value = `${value}` // toString if (!keepDiacritics) { value = removeAccents(value) } return value } /** * Gets value for key in item at arbitrarily nested keypath * @param {Object} item - the item * @param {Object|Function} key - the potentially nested keypath or property callback * @return {Array} - an array containing the value(s) at the nested keypath */ function getItemValues<ItemType>( item: ItemType, key: KeyOption<ItemType>, ): Array<string> { if (typeof key === 'object') { key = key.key as string } let value: string | Array<string> | null | unknown if (typeof key === 'function') { value = key(item) } else if (item == null) { value = null } else if (Object.hasOwnProperty.call(item, key)) { value = (item as IndexableByString)[key] } else if (key.includes('.')) { // eslint-disable-next-line @typescript-eslint/no-unsafe-call return getNestedValues<ItemType>(key, item) } else { value = null } // because `value` can also be undefined if (value == null) { return [] } if (Array.isArray(value)) { return value } return [String(value)] } /** * Given path: "foo.bar.baz" * And item: {foo: {bar: {baz: 'buzz'}}} * -> 'buzz' * @param path a dot-separated set of keys * @param item the item to get the value from */ function getNestedValues<ItemType>( path: string, item: ItemType, ): Array<string> { const keys = path.split('.') type ValueA = Array<ItemType | IndexableByString | string> let values: ValueA = [item] for (let i = 0, I = keys.length; i < I; i++) { const nestedKey = keys[i] let nestedValues: ValueA = [] for (let j = 0, J = values.length; j < J; j++) { const nestedItem = values[j] if (nestedItem == null) continue if (Object.hasOwnProperty.call(nestedItem, nestedKey)) { const nestedValue = (nestedItem as IndexableByString)[nestedKey] if (nestedValue != null) { nestedValues.push(nestedValue as IndexableByString | string) } } else if (nestedKey === '*') { // ensure that values is an array nestedValues = nestedValues.concat(nestedItem) } } values = nestedValues } if (Array.isArray(values[0])) { // keep allowing the implicit wildcard for an array of strings at the end of // the path; don't use `.flat()` because that's not available in node.js v10 const result: Array<string> = [] return result.concat(...(values as Array<string>)) } // Based on our logic it should be an array of strings by now... // assuming the user's path terminated in strings return values as Array<string> } /** * Gets all the values for the given keys in the given item and returns an array of those values * @param item - the item from which the values will be retrieved * @param keys - the keys to use to retrieve the values * @return objects with {itemValue, attributes} */ function getAllValuesToRank<ItemType>( item: ItemType, keys: ReadonlyArray<KeyOption<ItemType>>, ) { const allValues: Array<{itemValue: string; attributes: KeyAttributes}> = [] for (let j = 0, J = keys.length; j < J; j++) { const key = keys[j] const attributes = getKeyAttributes(key) const itemValues = getItemValues(item, key) for (let i = 0, I = itemValues.length; i < I; i++) { allValues.push({ itemValue: itemValues[i], attributes, }) } } return allValues } const defaultKeyAttributes = { maxRanking: Infinity as Ranking, minRanking: -Infinity as Ranking, } /** * Gets all the attributes for the given key * @param key - the key from which the attributes will be retrieved * @return object containing the key's attributes */ function getKeyAttributes<ItemType>(key: KeyOption<ItemType>): KeyAttributes { if (typeof key === 'string') { return defaultKeyAttributes } return {...defaultKeyAttributes, ...key} } export {matchSorter, rankings, defaultBaseSortFn} export type { MatchSorterOptions, KeyAttributesOptions, KeyOption, KeyAttributes, RankingInfo, ValueGetterKey, } /* eslint no-continue: "off", */ ```
/content/code_sandbox/src/index.ts
xml
2016-08-25T04:04:48
2024-08-16T04:57:41
match-sorter
kentcdodds/match-sorter
3,690
3,764
```xml import * as useLocationFieldOptionsModule from './useLocationFieldOptions'; const defaultFolders: useLocationFieldOptionsModule.ItemDefaultFolder[] = [ { value: '5', text: 'All mail', url: '/all-mail', icon: 'envelopes', }, { value: '0', text: 'Inbox', url: '/inbox', icon: 'inbox', }, { value: '8', text: 'Drafts', url: '/drafts', icon: 'file-lines', }, { value: '12', text: 'Scheduled', url: '/scheduled', icon: 'clock', }, { value: '7', text: 'Sent', url: '/sent', icon: 'paper-plane', }, ]; const folders: useLocationFieldOptionsModule.ItemCustomFolder[] = [ { text: 'news', value: your_sha256_hashNonJ8DsySBbUM0RtQdhYhA==', className: '', folderEntity: { ID: your_sha256_hashNonJ8DsySBbUM0RtQdhYhA==', Name: 'news', Path: 'news', Type: 3, Color: '#54473f', Order: 1, Notify: 1, Expanded: 0, subfolders: [], }, }, ]; const labels: useLocationFieldOptionsModule.ItemLabel[] = [ { color: 'white', text: 'Highlighted', value: '36', url: '/highlighted' }, ]; const all: useLocationFieldOptionsModule.Item[] = [...defaultFolders, ...folders, ...labels]; const grouped: useLocationFieldOptionsModule.ItemsGroup = [ { id: 'DEFAULT_FOLDERS', title: 'Default folders', items: defaultFolders, }, { id: 'CUSTOM_FOLDERS', title: 'Custom folders', items: folders, }, { id: 'LABELS', title: 'Labels', items: labels, }, ]; export const mockUseLocationFieldOptions = ( value?: Partial<ReturnType<typeof useLocationFieldOptionsModule.useLocationFieldOptions>> ) => { const mockedUseLocationFieldOptions = jest.spyOn(useLocationFieldOptionsModule, 'useLocationFieldOptions'); mockedUseLocationFieldOptions.mockReturnValue({ all, grouped, findItemByValue: (value: string) => all.find((item) => item.value === value), isDefaultFolder: ( item: useLocationFieldOptionsModule.Item ): item is useLocationFieldOptionsModule.ItemDefaultFolder => 'url' in item && 'icon' in item, isCustomFolder: ( item: useLocationFieldOptionsModule.Item ): item is useLocationFieldOptionsModule.ItemCustomFolder => 'folderEntity' in item, isLabel: (item: useLocationFieldOptionsModule.Item): item is useLocationFieldOptionsModule.ItemLabel => 'color' in item, ...value, }); return mockedUseLocationFieldOptions; }; ```
/content/code_sandbox/applications/mail/src/app/components/header/search/AdvancedSearchFields/LocationField.test.utils.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
674
```xml import type { Ref } from 'react'; import { forwardRef, useState } from 'react'; import { c } from 'ttag'; import type { InputProps } from '@proton/atoms'; import { Button, Input } from '@proton/atoms'; import Icon from '../../icon/Icon'; type PasswordType = 'password' | 'text'; interface Props extends Omit<InputProps, 'type'> { defaultType?: PasswordType; } const PasswordInputTwoBase = ( { disabled, suffix, defaultType = 'password', ...rest }: Props, ref: Ref<HTMLInputElement> ) => { const [type, setType] = useState<PasswordType>(defaultType); const toggle = () => { setType(type === 'password' ? 'text' : 'password'); }; return ( <Input autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" {...rest} ref={ref} type={type} disabled={disabled} suffix={ <> {suffix} <Button title={type === 'password' ? c('Label').t`Reveal password` : c('Label').t`Hide password`} className="inline-flex shrink-0" tabIndex={-1} disabled={disabled} onClick={toggle} shape="ghost" size="small" icon > <Icon className="m-auto" name={type === 'password' ? 'eye' : 'eye-slash'} /> </Button> </> } /> ); }; const PasswordInputTwo = forwardRef(PasswordInputTwoBase); export default PasswordInputTwo; ```
/content/code_sandbox/packages/components/components/v2/input/PasswordInput.tsx
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
358
```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. */ --> <resources xmlns:android="path_to_url" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <!-- <string name="english_ime_name" msgid="7252517407088836577">"Android "</string> --> <!-- <string name="english_ime_settings" msgid="6661589557206947774">" Android "</string> --> <string name="english_ime_input_options" msgid="3909945612939668554">" "</string> <string name="vibrate_on_keypress" msgid="5258079494276955460">" "</string> <string name="sound_on_keypress" msgid="6093592297198243644">" "</string> <string name="popup_on_keypress" msgid="123894815723512944">" "</string> <string name="hit_correction" msgid="4855351009261318389">" "</string> <string name="hit_correction_summary" msgid="8761701873008070796">" "</string> <string name="hit_correction_land" msgid="2567691684825205448">" "</string> <string name="hit_correction_land_summary" msgid="4076803842198368328">" "</string> <string name="auto_correction" msgid="7911639788808958255">" "</string> <string name="auto_correction_summary" msgid="6881047311475758267">" "</string> <string name="prediction" msgid="466220283138359837">" "</string> <string name="prediction_category" msgid="7027100625580696660">" "</string> <string name="prediction_summary" msgid="459788228830873110">" "</string> <string name="auto_complete_dialog_title" msgid="2172048590607201920">" "</string> <string name="prediction_landscape" msgid="4874601565593216183">" "</string> <string name="prediction_landscape_summary" msgid="6736551095997839472">" "</string> <string name="auto_cap" msgid="1719746674854628252">" "</string> <string name="auto_cap_summary" msgid="3260681697600786825">" "</string> <string name="auto_punctuate" msgid="7276672334264521751">" "</string> <string name="auto_punctuate_summary" msgid="6589441565817502132"></string> <string name="quick_fixes" msgid="5353213327680897927">" "</string> <string name="quick_fixes_summary" msgid="3405028402510332373">" "</string> <string name="show_suggestions" msgid="507074425254289133">" "</string> <string name="show_suggestions_summary" msgid="1989672863935759654">" "</string> <string name="auto_complete" msgid="1103196318775486023">" "</string> <string name="auto_complete_summary" msgid="6113149638718274624">" "</string> <string name="prefs_settings_key" msgid="4623341240804046498">" "</string> <string name="settings_key_mode_auto_name" msgid="2993460277873684680">""</string> <string name="settings_key_mode_always_show_name" msgid="3047567041784760575">" "</string> <string name="settings_key_mode_always_hide_name" msgid="7833948046716923994">" "</string> <!-- no translation found for settings_key_modes:0 (8549888726962891527) --> <!-- no translation found for settings_key_modes:1 (881280041213210923) --> <!-- no translation found for settings_key_modes:2 (7317310620171067848) --> <string name="bigram_suggestion" msgid="1323347224043514969">"Bigram "</string> <string name="bigram_suggestion_summary" msgid="4383845146070101531">" "</string> <string-array name="prediction_modes"> <item msgid="4870266572388153286">""</item> <item msgid="1669461741568287396">""</item> <item msgid="4894328801530136615">""</item> </string-array> <string name="added_word" msgid="8993883354622484372">"<xliff:g id="WORD">%s</xliff:g> : "</string> <string name="tip_long_press" msgid="6101270866284343344">" (, .)"</string> <string name="tip_dismiss" msgid="7585579046862204381">" "</string> <string name="tip_access_symbols" msgid="6344098517525531652">" "</string> <string name="tip_add_to_dictionary" msgid="1487293888469227817">" "</string> <string name="touch_to_continue" msgid="7869803257948414531">" "</string> <string name="touch_to_finish" msgid="7990196086480585789">" !"</string> <string name="tip_to_open_keyboard" msgid="6821200275486950452"><b>" "</b></string> <string name="tip_to_view_accents" msgid="5433158573693308501"><b>" "\n"(, , , , )"</b></string> <string name="tip_to_open_symbols" msgid="7345139325622444880"><b>" "</b></string> <string name="tip_to_close_symbols" msgid="5227724217206927185"><b>" "</b></string> <string name="tip_to_launch_settings" msgid="8402961128983196128"><b>" , "</b></string> <string name="tip_to_start_typing" msgid="7213843601369174313"><b>"!"</b></string> <string name="label_go_key" msgid="1635148082137219148">""</string> <string name="label_next_key" msgid="362972844525672568">""</string> <string name="label_done_key" msgid="2441578748772529288">""</string> <string name="label_send_key" msgid="2815056534433717444">""</string> <string name="label_symbol_key" msgid="6175820506864489453">"?123"</string> <string name="label_phone_key" msgid="4275497665515080551">"123"</string> <string name="label_alpha_key" msgid="8864943487292437456">"ABC"</string> <string name="label_alt_key" msgid="2846315350346694811">"ALT"</string> <string name="voice_warning_title" msgid="4419354150908395008">" "</string> <string name="voice_warning_locale_not_supported" msgid="637923019716442333">" , ."</string> <string name="voice_warning_may_not_understand" msgid="4611518823070986445">" Google- ."</string> <string name="voice_warning_how_to_turn_off" msgid="5652369578498701761">" , ."</string> <string name="voice_hint_dialog_message" msgid="6892342981545727994">" , ."</string> <string name="voice_listening" msgid="467518160751321844">" "</string> <string name="voice_working" msgid="6666937792815731889">""</string> <string name="voice_initializing" msgid="661962047129906646"></string> <string name="voice_error" msgid="5140896300312186162">". ."</string> <string name="voice_network_error" msgid="6649556447401862563">" "</string> <string name="voice_too_much_speech" msgid="5746973620134227376">", ."</string> <string name="voice_audio_error" msgid="5072707727016414454">" "</string> <string name="voice_server_error" msgid="7807129913977261644">" "</string> <string name="voice_speech_timeout" msgid="8461817525075498795">" "</string> <string name="voice_no_match" msgid="4285117547030179174">" "</string> <string name="voice_not_installed" msgid="5552450909753842415">" "</string> <string name="voice_swipe_hint" msgid="6943546180310682021"><b>":"</b>" "</string> <string name="voice_punctuation_hint" msgid="1611389463237317754"><b>":"</b>" , ."</string> <string name="cancel" msgid="6830980399865683324">""</string> <string name="ok" msgid="7898366843681727667">""</string> <string name="voice_input" msgid="2466640768843347841">" "</string> <string-array name="voice_input_modes"> <item msgid="1349082139076086774">" "</item> <item msgid="8529385602829095903">" "</item> <item msgid="7283103513488381103">""</item> </string-array> <string-array name="voice_input_modes_summary"> <item msgid="554248625705084903">" "</item> <item msgid="6907837061058876770">" "</item> <item msgid="3664304608587798036">" "</item> </string-array> <string name="auto_submit" msgid="9151008027068358518">" "</string> <string name="auto_submit_summary" msgid="4961875269610384226">" enter ."</string> <string name="open_the_keyboard" msgid="2215920976029260466"><font size="17"><b>" "\n</b></font><font size="3">\n</font>" ."</string> <string name="close_the_keyboard" msgid="6251022259044940103"><font size="17"><b>" "\n</b></font><font size="3">\n</font>" ."</string> <string name="touch_and_hold" msgid="6154166367273010534"><font size="17"><b>" "\n</b></font><font size="3">\n</font>" ."</string> <string name="keyboard_settings" msgid="4585753477617374032"><font size="17"><b>" "\n</b></font><font size="3">\n</font>" "<b>"?123"</b>"."</string> <string name="popular_domain_0" msgid="3745279225122472969">".com"</string> <string name="popular_domain_1" msgid="1370572248164278467">".net"</string> <string name="popular_domain_2" msgid="3036812463748402878">".org"</string> <string name="popular_domain_3" msgid="8718639560809452028">".gov"</string> <string name="popular_domain_4" msgid="35359437471311470">".edu"</string> <string name="selectInputMethod" msgid="315076553378705821">" "</string> <string name="language_selection_title" msgid="1651299598555326750">" "</string> <string name="language_selection_summary" msgid="187110938289512256">" "</string> <string name="hint_add_to_dictionary" msgid="9006292060636342317">" "</string> <string name="has_dictionary" msgid="6071847973466625007">" "</string> <string name="prefs_enable_log" msgid="6620424505072963557">" "</string> <string name="prefs_description_log" msgid="5827825607258246003">" Google."</string> <string name="prefs_enable_recorrection" msgid="4588408906649533582">" "</string> <string name="prefs_enable_recorrection_summary" msgid="1056068922330206170">" "</string> <string name="keyboard_layout" msgid="437433231038683666">" "</string> <string name="subtype_mode_keyboard" msgid="2242090416595003881">""</string> <string name="subtype_mode_voice" msgid="4394113125441627771">""</string> </resources> ```
/content/code_sandbox/app/src/main/res/values-sr/strings.xml
xml
2016-01-22T21:40:54
2024-08-16T11:54:30
hackerskeyboard
klausw/hackerskeyboard
1,807
2,922
```xml /** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../../..' export const input = ( <editor> <block>one</block> <block>two</block> </editor> ) export const test = editor => { return Editor.path(editor, { anchor: { path: [0, 0], offset: 1 }, focus: { path: [1, 0], offset: 2 }, }) } export const output = [] ```
/content/code_sandbox/packages/slate/test/interfaces/Editor/path/range.tsx
xml
2016-06-18T01:52:42
2024-08-16T18:43:42
slate
ianstormtaylor/slate
29,492
109
```xml import React, { FunctionComponent, useRef, useState, useCallback } from "react" import styled from "styled-components" import Modal, { KeystrokeContainer, Keystroke } from "../../components/Modal" const InstructionText = styled.div` text-align: left; color: ${(props) => props.theme.foreground}; ` const ExampleText = styled.p` margin: 0 0 0 40px; color: ${(props) => props.theme.bold}; ` const PathContainer = styled.div` display: flex; flex-direction: column; padding: 15px; ` const PathLabel = styled.label` font-size: 13px; color: ${(props) => props.theme.heading}; ` const PathInput = styled.input` border: 0; border-bottom: 1px solid ${(props) => props.theme.line}; font-size: 25px; color: ${(props) => props.theme.foregroundLight}; line-height: 40px; background-color: inherit; ` interface Props { isOpen: boolean onClose: () => void onAddSubscription: (path: string) => void } const SubscriptionAddModal: FunctionComponent<Props> = ({ isOpen, onClose, onAddSubscription }) => { const [path, setPath] = useState("") const inputRef = useRef<HTMLInputElement>(null) const handleAfterOpen = () => inputRef.current && inputRef.current.focus() const handleClose = useCallback(() => { setPath("") onClose() }, [onClose]) const handleChange = useCallback((e) => { setPath(e.target.value) }, []) const handleKeypress = useCallback( (e) => { if (e.key === "Enter") { onAddSubscription(path) setPath("") } }, [onAddSubscription, path] ) return ( <Modal title="Add Subscription" isOpen={isOpen} onClose={handleClose} onAfterOpen={handleAfterOpen} additionalKeystrokes={ <KeystrokeContainer> <Keystroke>ENTER</Keystroke> Subscribe </KeystrokeContainer> } > <InstructionText> <p>Enter a path you would like to subscribe. Here are some examples to get you started:</p> <ExampleText>user.firstName</ExampleText> <ExampleText>repo</ExampleText> <ExampleText>repo.*</ExampleText> </InstructionText> <PathContainer> <PathLabel>PATH</PathLabel> <PathInput type="text" ref={inputRef} value={path} onChange={handleChange} onKeyPress={handleKeypress} /> </PathContainer> </Modal> ) } export default SubscriptionAddModal ```
/content/code_sandbox/lib/reactotron-core-ui/src/modals/SubscriptionAddModal/index.tsx
xml
2016-04-15T21:58:32
2024-08-16T11:39:46
reactotron
infinitered/reactotron
14,757
603
```xml import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { Store } from '@ngxs/store'; import { Application } from 'app/model/application.model'; import { Environment } from 'app/model/environment.model'; import { Pipeline } from 'app/model/pipeline.model'; import { IdName, Project } from 'app/model/project.model'; import { WNode, WNodeType } from 'app/model/workflow.model'; import { ApplicationService } from 'app/service/application/application.service'; import { ToastService } from 'app/shared/toast/ToastService'; import { AddApplication } from 'app/store/applications.action'; import { ApplicationsState, ApplicationStateModel } from 'app/store/applications.state'; import { AddEnvironment } from 'app/store/environment.action'; import { AddPipeline } from 'app/store/pipelines.action'; import { PipelinesState, PipelinesStateModel } from 'app/store/pipelines.state'; import { ProjectState, ProjectStateModel } from 'app/store/project.state'; import cloneDeep from 'lodash-es/cloneDeep'; import { Observable, of as observableOf } from 'rxjs'; import { filter, finalize, first, flatMap, map } from 'rxjs/operators'; @Component({ selector: 'app-workflow-node-add-wizard', templateUrl: './node.wizard.html', styleUrls: ['./node.wizard.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class WorkflowNodeAddWizardComponent implements OnInit { @Input() set project(data: Project) { this._project = cloneDeep(data); } get project(): Project { return this._project; } @Input() display: boolean; @Input() hideCancel: boolean; @Input() hideNext: boolean; @Input() loading: boolean; @Output() nodeCreated: EventEmitter<WNode> = new EventEmitter<WNode>(); @Output() pipelineSectionChanged: EventEmitter<number> = new EventEmitter<number>(); _project: Project; node: WNode = new WNode(); applicationsName: IdName[] = []; environmentsName: IdName[] = []; pipIndexTab: number; appIndexTab: number; envIndexTab: number; errorPipelineNamePattern = false; loadingCreatePipeline = false; newPipeline: Pipeline = new Pipeline(); set pipelineSection(data: number) { this._pipelineSection = data; this.pipelineSectionChanged.emit(data); } get pipelineSection() { return this._pipelineSection; } _pipelineSection: number = 0; errorApplicationNamePattern = false; loadingCreateApplication = false; newApplication: Application = new Application(); loadingCreateEnvironment = false; newEnvironment: Environment = new Environment(); integrations: IdName[] = []; loadingIntegrations = false; createFork = false; constructor( private _router: Router, private _translate: TranslateService, private _toast: ToastService, private _appService: ApplicationService, private store: Store, private _cd: ChangeDetectorRef ) { } ngOnInit() { if (Array.isArray(this.project.application_names)) { let voidApp = new IdName(); voidApp.id = 0; voidApp.name = ' '; this.applicationsName = [voidApp, ...this.project.application_names]; } if (Array.isArray(this.project.environments)) { let voidEnv = new IdName(); voidEnv.id = 0; voidEnv.name = ' '; this.environmentsName = [voidEnv, ...this.project.environments]; } } goToProject(): void { this._router.navigate(['/project', this.project.key], { queryParams: { tab: 'workflows' } }); } createNode(): void { if (this.node.context.pipeline_id) { this.node.type = WNodeType.PIPELINE; this.node.context.pipeline_id = Number(this.node.context.pipeline_id); } else { this.node.type = WNodeType.FORK; } if (this.node.context.application_id) { this.node.context.application_id = Number(this.node.context.application_id); } if (this.node.context.environment_id) { this.node.context.environment_id = Number(this.node.context.environment_id); } if (this.node.context.project_integration_id) { this.node.context.project_integration_id = Number(this.node.context.project_integration_id); } if (!this.node.ref) { this.node.ref = new Date().getTime().toString(); } this.nodeCreated.emit(this.node); } createPipeline(): Observable<Pipeline> { if (!Pipeline.checkName(this.newPipeline.name)) { this.errorPipelineNamePattern = true; return observableOf(null); } this.loadingCreatePipeline = true; return this.store.dispatch(new AddPipeline({ projectKey: this.project.key, pipeline: this.newPipeline })).pipe( finalize(() => { this.loadingCreatePipeline = false; this._cd.markForCheck(); }), flatMap(() => this.store.selectOnce(PipelinesState.getCurrent())), map((pip: PipelinesStateModel) => { this._toast.success('', this._translate.instant('pipeline_added')); this.node.context.pipeline_id = pip.pipeline.id; this.pipelineSection = 1; return pip.pipeline; })); } selectOrCreatePipeline(): Observable<number> { if (this.pipIndexTab === 1) { return this.createPipeline().pipe( map(() => 1)); } this.pipelineSection = 1; this._cd.markForCheck(); return observableOf(1); } createApplication(): Observable<Application> { if (!Application.checkName(this.newApplication.name)) { this.errorApplicationNamePattern = true; return observableOf(null); } this.loadingCreateApplication = true; return this.store.dispatch(new AddApplication({ projectKey: this.project.key, application: this.newApplication })).pipe( finalize(() => { this.loadingCreateApplication = false; this._cd.markForCheck(); }), flatMap(() => this.store.selectOnce(ApplicationsState.currentState())), filter((s: ApplicationStateModel) => s.application != null && s.application.name === this.newApplication.name), map((s: ApplicationStateModel) => { this._toast.success('', this._translate.instant('application_created')); this.node.context.application_id = s.application.id; this.pipelineSection = 2; return s.application; }) ); } selectOrCreateApplication(): Observable<number> { if (this.appIndexTab && this.newApplication.name) { return this.createApplication().pipe( map(() => 2)); } this.getIntegrations(); this.pipelineSection = 2; this._cd.markForCheck(); return observableOf(2); } getIntegrations() { this.loadingIntegrations = true; if (!this.node.context.application_id) { this.loadingIntegrations = false; return; } let app = this.project.application_names.find((a) => a.id === Number(this.node.context.application_id)); if (!app) { this.loadingIntegrations = false; return; } // TODO: to update with store this._appService.getDeploymentStrategies(this.project.key, app.name).pipe( first(), finalize(() => { this.loadingIntegrations = false; this._cd.markForCheck(); }) ).subscribe( (data) => { this.integrations = []; let pfNames = Object.keys(data); pfNames.forEach(s => { let pf = this.project.integrations.find(p => p.name === s); if (pf) { let idName = new IdName(); idName.id = pf.id; idName.name = pf.name; this.integrations.push(idName); } }); } ); } createEnvironment(): Observable<Project> { this.loadingCreateEnvironment = true; return this.store.dispatch(new AddEnvironment({ projectKey: this.project.key, environment: this.newEnvironment })).pipe( finalize(() => { this.loadingCreateEnvironment = false; this._cd.markForCheck(); }), flatMap(() => this.store.selectOnce(ProjectState)), map((projState: ProjectStateModel) => { let proj = projState.project; this._toast.success('', this._translate.instant('environment_created')); this.node.context.environment_id = proj.environments.find((env) => env.name === this.newEnvironment.name).id; if (!this.node.context.application_id) { this.createNode(); } else { this.pipelineSection = 3; } return proj; }) ); } selectOrCreateEnvironment() { if (this.envIndexTab === 1 && this.newEnvironment.name) { return this.createEnvironment().pipe( map(() => 3)); } let noIntegrationsAvailable = !this.loadingIntegrations && (!this.integrations || !this.integrations.length); if (!this.node.context.application_id || noIntegrationsAvailable) { this.createNode(); return observableOf(4); } this.pipelineSection = 3; this._cd.markForCheck(); return observableOf(3); } selectOrCreateIntegration() { this.createNode(); return observableOf(4); } public goToPreviousSection() { this.pipelineSection--; this._cd.markForCheck(); } public goToNextSection(): Observable<number> { switch (this.pipelineSection) { case 0: return this.selectOrCreatePipeline(); case 1: return this.selectOrCreateApplication(); case 2: return this.selectOrCreateEnvironment(); case 3: return this.selectOrCreateIntegration(); } } } ```
/content/code_sandbox/ui/src/app/shared/workflow/wizard/node-add/node.wizard.component.ts
xml
2016-10-11T08:28:23
2024-08-16T01:55:31
cds
ovh/cds
4,535
2,145
```xml import * as React from 'react'; export interface IGraphEvalDebugState { panelText: string; } export interface IGraphEvalDebugProps { panelText: string; } export default class GraphEvalDebug extends React.Component<IGraphEvalDebugProps, IGraphEvalDebugState> { constructor(props) { super(props); } public render(): React.ReactElement<void> { return ( <div> <label> <strong>Debugging Information</strong> </label> <pre className="dbgInfo">{this.props.panelText}</pre> </div> ) }; } ```
/content/code_sandbox/samples/react-graph-evalurl/src/webparts/graphEvalUrl/components/GraphEvalDebug.tsx
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
132
```xml import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { RoomOptions } from 'livekit-client'; @Component({ selector: 'app-room-options-dialog', templateUrl: './room-options-dialog.component.html', styleUrls: ['./room-options-dialog.component.css'] }) export class RoomOptionsDialogComponent { roomOptions: RoomOptions; constructor(public dialogRef: MatDialogRef<RoomOptionsDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { this.roomOptions = data.roomOptions; } } ```
/content/code_sandbox/openvidu-testapp/src/app/components/dialogs/room-options-dialog/room-options-dialog.component.ts
xml
2016-10-10T13:31:27
2024-08-15T12:14:04
openvidu
OpenVidu/openvidu
1,859
122
```xml import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { CovalentDialogsModule } from '@covalent/core/dialogs'; import { ComponentDetailsModule } from '../../../../components/shared/component-details/component-details.module'; import { setComponentRoutes } from '../../../../content/components/components'; import { DialogsDemoBasicComponent } from './demos/dialogs-demo-basic/dialogs-demo-basic.component'; import { DialogsDemoBasicSharedModule } from './demos/dialogs-demo-basic/dialogs-demo-basic-shared'; const routes: Routes = setComponentRoutes({ overviewDemoComponent: DialogsDemoBasicComponent, id: 'dialogs', }); @NgModule({ imports: [ DialogsDemoBasicSharedModule, CommonModule, // Material ComponentDetailsModule, // Covalent CovalentDialogsModule, // Docs // Routes RouterModule.forChild(routes), ], exports: [], providers: [], }) export class DialogsDemoModule {} ```
/content/code_sandbox/apps/docs-app/src/app/content/components/component-demos/dialogs/dialogs.module.ts
xml
2016-07-11T23:30:52
2024-08-15T15:20:45
covalent
Teradata/covalent
2,228
219
```xml /* * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. */ import { ButtonSkeleton, StructuredListSkeleton, ContainedList, ContainedListItem, Section, SkeletonText, TabsSkeleton, } from '@carbon/react'; import {TaskDetailsRow} from 'modules/components/TaskDetailsLayout'; import styles from './styles.module.scss'; import headerStyles from './Header.module.scss'; import asideStyles from './Aside.module.scss'; import tabStyles from './TabListNav/styles.module.scss'; type Props = { 'data-testid'?: string; }; const DetailsSkeleton: React.FC<Props> = (props) => { return ( <div className={styles.container} data-testid={props['data-testid']}> <Section className={styles.content}> <header className={headerStyles.header}> <div className={headerStyles.headerLeftContainer}> <SkeletonText width="150px" /> <SkeletonText width="100px" className={styles.margin0} /> </div> <div className={headerStyles.headerRightContainer}> <SkeletonText width="100px" className={styles.margin0} /> <ButtonSkeleton size="sm" /> </div> </header> <TabsSkeleton className={tabStyles.tabs} /> <TaskDetailsRow> <SkeletonText width="150px" heading /> </TaskDetailsRow> <TaskDetailsRow $disabledSidePadding> <StructuredListSkeleton /> </TaskDetailsRow> </Section> <aside className={asideStyles.aside}> <ContainedList label={<SkeletonText width="100px" className={styles.margin0} />} kind="disclosed" > <ContainedListItem> <SkeletonText width="75px" /> <SkeletonText width="125px" /> </ContainedListItem> <ContainedListItem> <SkeletonText width="75px" /> <SkeletonText width="125px" /> </ContainedListItem> <ContainedListItem> <SkeletonText width="75px" /> <SkeletonText width="125px" /> </ContainedListItem> <ContainedListItem> <SkeletonText width="75px" /> <SkeletonText width="125px" /> </ContainedListItem> <ContainedListItem> <SkeletonText width="75px" /> <SkeletonText width="125px" /> </ContainedListItem> </ContainedList> </aside> </div> ); }; export {DetailsSkeleton}; ```
/content/code_sandbox/tasklist/client/src/Tasks/Task/Details/DetailsSkeleton.tsx
xml
2016-03-20T03:38:04
2024-08-16T19:59:58
camunda
camunda/camunda
3,172
540
```xml <?xml version="1.0" encoding="UTF-8"?> <module external.linked.project.id=":views" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" type="JAVA_MODULE" version="4"> <component name="FacetManager"> <facet type="android-gradle" name="Android-Gradle"> <configuration> <option name="GRADLE_PROJECT_PATH" value=":views" /> </configuration> </facet> <facet type="android" name="Android"> <configuration> <option name="SELECTED_BUILD_VARIANT" value="debug" /> <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" /> <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" /> <afterSyncTasks> <task>generateDebugSources</task> </afterSyncTasks> <option name="ALLOW_USER_CONFIGURATION" value="false" /> <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" /> <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" /> <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" /> <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" /> <option name="PROJECT_TYPE" value="1" /> </configuration> </facet> </component> <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7"> <output url="file://$MODULE_DIR$/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes" /> <output-test url="file://$MODULE_DIR$/build/intermediates/javac/debugUnitTest/compileDebugUnitTestJavaWithJavac/classes" /> <exclude-output /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/aidl_source_output_dir/debug/compileDebugAidl/out" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/renderscript_source_output_dir/debug/compileDebugRenderscript/out" isTestSource="false" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/aidl_source_output_dir/debugAndroidTest/compileDebugAndroidTestAidl/out" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/renderscript_source_output_dir/debugAndroidTest/compileDebugAndroidTestRenderscript/out" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/test/debug" isTestSource="true" generated="true" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/shaders" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" /> <excludeFolder url="file://$MODULE_DIR$/build/generated/not_namespaced_r_class_sources" /> <excludeFolder url="file://$MODULE_DIR$/build/generated/source/r" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/aapt_friendly_merged_manifests" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/annotation_processor_list" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/check_manifest_result" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/compile_only_not_namespaced_r_class_jar" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/full_jar" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/intermediate-jars" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javac" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/library_assets" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/library_manifest" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint_jar" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/merged_manifests" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/packaged_res" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/public_res" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/shader_assets" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/shaders" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" /> <excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" /> <excludeFolder url="file://$MODULE_DIR$/build/outputs" /> <excludeFolder url="file://$MODULE_DIR$/build/tmp" /> </content> <orderEntry type="jdk" jdkName="Android API 28 Platform" jdkType="Android SDK" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Gradle: androidx.swiperefreshlayout:swiperefreshlayout:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.savedstate:savedstate-bundle:1.0.0-alpha01@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-core-ui:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.viewpager:viewpager:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.loader:loader:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.drawerlayout:drawerlayout:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.documentfile:documentfile:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.localbroadcastmanager:localbroadcastmanager:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-runtime:2.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-livedata-core:2.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.cursoradapter:cursoradapter:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-viewmodel:2.1.0-alpha02@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-livedata:2.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.versionedparcelable:versionedparcelable:1.1.0-alpha01@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.customview:customview:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.vectordrawable:vectordrawable-animated:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.asynclayoutinflater:asynclayoutinflater:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.vectordrawable:vectordrawable:1.0.1@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.core:core:1.1.0-alpha04@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.interpolator:interpolator:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.savedstate:savedstate-common:1.0.0-alpha01@jar" level="project" /> <orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-common:2.0.0@jar" level="project" /> <orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-core-utils:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.print:print:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.fragment:fragment:1.1.0-alpha04@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.activity:activity:1.0.0-alpha04@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.appcompat:appcompat:1.1.0-alpha02@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.slidingpanelayout:slidingpanelayout:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.annotation:annotation:1.1.0-alpha01@jar" level="project" /> <orderEntry type="library" name="Gradle: androidx.arch.core:core-common:2.0.0@jar" level="project" /> <orderEntry type="library" name="Gradle: androidx.collection:collection:1.1.0-alpha02@jar" level="project" /> <orderEntry type="library" scope="TEST" name="Gradle: junit:junit:4.12@jar" level="project" /> <orderEntry type="library" scope="TEST" name="Gradle: org.hamcrest:hamcrest-core:1.3@jar" level="project" /> <orderEntry type="library" name="Gradle: androidx.coordinatorlayout:coordinatorlayout:1.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: androidx.arch.core:core-runtime:2.0.0@aar" level="project" /> <orderEntry type="library" name="Gradle: com.google.guava:listenablefuture:1.0@jar" level="project" /> <orderEntry type="library" name="Gradle: androidx.concurrent:concurrent-futures:1.0.0-alpha02@jar" level="project" /> </component> </module> ```
/content/code_sandbox/views/views.iml
xml
2016-05-11T16:25:10
2024-07-24T10:40:56
ScratchView
sharish/ScratchView
1,119
3,724
```xml import {PlatformTest, runInContext} from "@tsed/common"; import "@tsed/platform-express"; import {PlatformExpress} from "@tsed/platform-express"; import {ApolloServerTestClient, createTestClient} from "apollo-server-testing"; import gql from "graphql-tag"; import "@tsed/graphql-ws"; import {TypeGraphQLService} from "../src/index.js"; import {Server} from "./app/Server.js"; const GET_RECIPES = gql` query GetRecipes { recipes { title description creationDate } } `; const ADD_RECIPE = gql` mutation AddRecipe($title: String!, $description: String!) { addRecipe(title: $title, description: $description) { title description creationDate } } `; describe("GraphQL", () => { let request: ApolloServerTestClient; beforeAll( PlatformTest.bootstrap(Server, { platform: PlatformExpress }) ); beforeAll(() => { const server = PlatformTest.get<TypeGraphQLService>(TypeGraphQLService).get("default")!; request = createTestClient(server as any); }); afterAll(PlatformTest.reset); it("should get recipes", async () => { const $ctx = PlatformTest.createRequestContext(); const response = await runInContext($ctx, () => { return request.query({ query: GET_RECIPES, variables: {} }); }); expect($ctx.get("test")).toEqual("test"); expect(response.data).toEqual({ recipes: [ { creationDate: "2020-08-20T00:00:00.000Z", description: "Description", title: "title" } ] }); }); it("should add recipe", async () => { const $ctx = PlatformTest.createRequestContext(); const response = await runInContext($ctx, () => { return request.query({ query: ADD_RECIPE, variables: { title: "title", description: "description" } }); }); expect(response.data).toEqual({ addRecipe: { creationDate: expect.any(String), description: "description", title: "title" } }); }); }); ```
/content/code_sandbox/packages/graphql/typegraphql/test/graphql.spec.ts
xml
2016-02-21T18:38:47
2024-08-14T21:19:48
tsed
tsedio/tsed
2,817
491
```xml // path_to_url export enum ListType { None = 0, CustomList = 100, DocumentLibrary = 101, Survey = 102, Links = 103, Announcements = 104, Contacts = 105, Calendar = 106, Tasks = 107, DiscussionBoard = 108, PictureLibrary = 109, DataSources = 110, FormLibrary = 115, NoCodeWorkflows = 117, CustomWorkflowProcess = 118, WikiPageLibrary = 119, CustomGrid = 120, NoCodePublicWorkflows = 122, WorkflowHistory = 140, ProjectTasks = 150, PublicWorkflowsExternalList = 600, IssueTracking = 1100, //Undocumented, but needed for this solution TenantWideExtensions = 337 } export const ListTypeStrings = { [ListType.None]: "N/A", [ListType.CustomList]: "Custom List", [ListType.DocumentLibrary]: "Document Library", [ListType.Survey]: "Survey", [ListType.Links]: "Links", [ListType.Announcements]: "Announcements", [ListType.Contacts]: "Contacts", [ListType.Calendar]: "Calendar", [ListType.Tasks]: "Tasks", [ListType.DiscussionBoard]: "Discussion Board", [ListType.PictureLibrary]: "Picture Library", [ListType.DataSources]: "Data Sources", [ListType.FormLibrary]: "Form Library", [ListType.NoCodeWorkflows]: "No Code Workflows", [ListType.CustomWorkflowProcess]: "Custom Workflow Process", [ListType.WikiPageLibrary]: "Wiki Page Library", [ListType.CustomGrid]: "Custom Grid", [ListType.NoCodePublicWorkflows]: "No Code Public Workflows", [ListType.WorkflowHistory]: "Workflow History", [ListType.ProjectTasks]: "Project Tasks", [ListType.PublicWorkflowsExternalList]: "Public Workflows External List", [ListType.IssueTracking]: "Issue Tracking", [ListType.TenantWideExtensions]: "Tenant Wide Extensions", } export const ListTypes: ListType[] = Object.keys(ListTypeStrings).map(x => parseInt(x)) as ListType[]; export const OFFICIALLY_SUPPORTED_LIST_TYPES = [ListType.CustomList, ListType.DocumentLibrary]; ```
/content/code_sandbox/samples/react-extension-manager/src/Models/ListType.ts
xml
2016-08-30T17:21:43
2024-08-16T18:41:32
sp-dev-fx-webparts
pnp/sp-dev-fx-webparts
2,027
518
```xml import { getProjectRoot, resolvePathInStorybookCache } from 'storybook/internal/common'; import type { Options } from 'storybook/internal/types'; import { getVirtualModules } from '@storybook/builder-webpack5'; export const configureBabelLoader = async (baseConfig: any, options: Options) => { const { virtualModules } = await getVirtualModules(options); const babelOptions = await options.presets.apply('babel', {}, options); const typescriptOptions = await options.presets.apply('typescript', {}, options); baseConfig.module.rules = [ ...baseConfig.module.rules, { test: typescriptOptions.skipCompiler ? /\.((c|m)?jsx?)$/ : /\.((c|m)?(j|t)sx?)$/, use: [ { loader: require.resolve('babel-loader'), options: { cacheDirectory: resolvePathInStorybookCache('babel'), ...babelOptions, }, }, ], include: [getProjectRoot()], exclude: [/node_modules/, ...Object.keys(virtualModules)], }, ]; }; ```
/content/code_sandbox/code/frameworks/nextjs/src/babel/loader.ts
xml
2016-03-18T04:23:44
2024-08-16T19:22:08
storybook
storybookjs/storybook
83,755
228
```xml import { FC, useEffect, useState } from "react"; import useDebounce from "react-debounced"; import { Loading } from "@carbon/react"; type LateLoadingProps = { timeout?: number; }; const LateLoading: FC<LateLoadingProps> = ({ timeout = 300 }) => { const debounce = useDebounce(timeout); const [visible, setVisible] = useState(false); useEffect(() => { debounce(() => setVisible(true)); }, [debounce]); if (visible) { return <Loading />; } return null; }; export default LateLoading; ```
/content/code_sandbox/identity/client/src/components/layout/LateLoading.tsx
xml
2016-03-20T03:38:04
2024-08-16T19:59:58
camunda
camunda/camunda
3,172
125
```xml import { Entity } from "../../../../../src/decorator/entity/Entity" import { PrimaryGeneratedColumn } from "../../../../../src/decorator/columns/PrimaryGeneratedColumn" import { Column } from "../../../../../src/decorator/columns/Column" import { Generated } from "../../../../../src/decorator/Generated" @Entity() export class Question { @PrimaryGeneratedColumn("uuid") id: string @Column() @Generated("uuid") uuid: string @Column("uuid") uuid2: string @Column("uuid", { nullable: true }) uuid3: string | null @Column({ nullable: true }) @Generated("uuid") uuid4: string | null } ```
/content/code_sandbox/test/functional/uuid/cockroach/entity/Question.ts
xml
2016-02-29T07:41:14
2024-08-16T18:28:52
typeorm
typeorm/typeorm
33,875
154
```xml <?xml version="1.0" encoding="utf-8"?> <abapGit version="v1.0.0" serializer="LCL_OBJECT_DEVC" serializer_version="v1.0.0"> <asx:abap xmlns:asx="path_to_url" version="1.0"> <asx:values> <DEVC> <CTEXT>Package for Amazon Elastic Compute Cloud</CTEXT> </DEVC> </asx:values> </asx:abap> </abapGit> ```
/content/code_sandbox/sap-abap/services/ec2/package.devc.xml
xml
2016-08-18T19:06:57
2024-08-16T18:59:44
aws-doc-sdk-examples
awsdocs/aws-doc-sdk-examples
9,298
118
```xml // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // // path_to_url // // Unless required by applicable law or agreed to in writing, // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // specific language governing permissions and limitations import { memcpy } from '../util/buffer.js'; import { TypedArray, BigIntArray, ArrayCtor } from '../interfaces.js'; import { DataType } from '../type.js'; /** @ignore */ function roundLengthUpToNearest64Bytes(len: number, BPE: number) { const bytesMinus1 = Math.ceil(len) * BPE - 1; return ((bytesMinus1 - bytesMinus1 % 64 + 64) || 64) / BPE; } /** @ignore */ function resizeArray<T extends TypedArray | BigIntArray>(arr: T, len = 0): T { return arr.length >= len ? arr.subarray(0, len) as T : memcpy(new (arr.constructor as any)(len), arr, 0); } /** @ignore */ export class BufferBuilder<T extends TypedArray | BigIntArray> { constructor(bufferType: ArrayCtor<T>, initialSize = 0, stride = 1) { this.length = Math.ceil(initialSize / stride); this.buffer = new bufferType(this.length) as T; this.stride = stride; this.BYTES_PER_ELEMENT = bufferType.BYTES_PER_ELEMENT; this.ArrayType = bufferType; } public buffer: T; public length: number; public readonly stride: number; public readonly ArrayType: ArrayCtor<T>; public readonly BYTES_PER_ELEMENT: number; public get byteLength() { return Math.ceil(this.length * this.stride) * this.BYTES_PER_ELEMENT; } public get reservedLength() { return this.buffer.length / this.stride; } public get reservedByteLength() { return this.buffer.byteLength; } // @ts-ignore public set(index: number, value: T[0]) { return this; } public append(value: T[0]) { return this.set(this.length, value); } public reserve(extra: number) { if (extra > 0) { this.length += extra; const stride = this.stride; const length = this.length * stride; const reserved = this.buffer.length; if (length >= reserved) { this._resize(reserved === 0 ? roundLengthUpToNearest64Bytes(length * 1, this.BYTES_PER_ELEMENT) : roundLengthUpToNearest64Bytes(length * 2, this.BYTES_PER_ELEMENT) ); } } return this; } public flush(length = this.length) { length = roundLengthUpToNearest64Bytes(length * this.stride, this.BYTES_PER_ELEMENT); const array = resizeArray<T>(this.buffer, length); this.clear(); return array; } public clear() { this.length = 0; this.buffer = new this.ArrayType() as T; return this; } protected _resize(newLength: number) { return this.buffer = resizeArray<T>(this.buffer, newLength); } } /** @ignore */ export class DataBufferBuilder<T extends TypedArray | BigIntArray> extends BufferBuilder<T> { public last() { return this.get(this.length - 1); } public get(index: number): T[0] { return this.buffer[index]; } public set(index: number, value: T[0]) { this.reserve(index - this.length + 1); this.buffer[index * this.stride] = value; return this; } } /** @ignore */ export class BitmapBufferBuilder extends DataBufferBuilder<Uint8Array> { constructor() { super(Uint8Array, 0, 1 / 8); } public numValid = 0; public get numInvalid() { return this.length - this.numValid; } public get(idx: number) { return this.buffer[idx >> 3] >> idx % 8 & 1; } public set(idx: number, val: number) { const { buffer } = this.reserve(idx - this.length + 1); const byte = idx >> 3, bit = idx % 8, cur = buffer[byte] >> bit & 1; // If `val` is truthy and the current bit is 0, flip it to 1 and increment `numValid`. // If `val` is falsey and the current bit is 1, flip it to 0 and decrement `numValid`. val ? cur === 0 && ((buffer[byte] |= (1 << bit)), ++this.numValid) : cur === 1 && ((buffer[byte] &= ~(1 << bit)), --this.numValid); return this; } public clear() { this.numValid = 0; return super.clear(); } } /** @ignore */ export class OffsetsBufferBuilder<T extends DataType> extends DataBufferBuilder<T['TOffsetArray']> { constructor(type: T) { super(type.OffsetArrayType as ArrayCtor<T['TOffsetArray']>, 1, 1); } public append(value: T['TOffsetArray'][0]) { return this.set(this.length - 1, value); } public set(index: number, value: T['TOffsetArray'][0]) { const offset = this.length - 1; const buffer = this.reserve(index - offset + 1).buffer; if (offset < index++ && offset >= 0) { buffer.fill(buffer[offset], offset, index); } buffer[index] = buffer[index - 1] + value; return this; } public flush(length = this.length - 1) { if (length > this.length) { this.set(length - 1, this.BYTES_PER_ELEMENT > 4 ? BigInt(0) : 0); } return super.flush(length + 1); } } ```
/content/code_sandbox/js/src/builder/buffer.ts
xml
2016-02-17T08:00:23
2024-08-16T19:00:48
arrow
apache/arrow
14,094
1,320
```xml export const getAddressSuggestedLocalPart = (groupName: string) => { return groupName .toLowerCase() .replace(/[^a-z0-9-_\.\s+]/g, '') .replace(/\s+/g, '-'); }; ```
/content/code_sandbox/packages/components/containers/organization/groups/helpers.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
54
```xml /*your_sha256_hash----------------------------- *your_sha256_hash----------------------------*/ import * as vscode from 'vscode'; import { NotificationHandler, RequestType } from 'vscode-languageclient'; import { ConnectionDetails, IConnectionInfo, IServerInfo } from 'vscode-mssql'; import { AccountService } from '../azure/accountService'; import { AccountStore } from '../azure/accountStore'; import { AzureController } from '../azure/azureController'; import { MsalAzureController } from '../azure/msal/msalAzureController'; import providerSettings from '../azure/providerSettings'; import * as Constants from '../constants/constants'; import * as LocalizedConstants from '../constants/localizedConstants'; import { CredentialStore } from '../credentialstore/credentialstore'; import { FirewallService } from '../firewall/firewallService'; import SqlToolsServerClient from '../languageservice/serviceclient'; import { ConnectionCredentials } from '../models/connectionCredentials'; import { ConnectionProfile } from '../models/connectionProfile'; import { ConnectionStore } from '../models/connectionStore'; import { IAccount } from '../models/contracts/azure'; import * as ConnectionContracts from '../models/contracts/connection'; import { ClearPooledConnectionsRequest, ConnectionSummary } from '../models/contracts/connection'; import * as LanguageServiceContracts from '../models/contracts/languageService'; import { EncryptOptions, IConnectionProfile } from '../models/interfaces'; import { PlatformInformation, Runtime } from '../models/platform'; import * as Utils from '../models/utils'; import { IPrompter, IQuestion, QuestionTypes } from '../prompts/question'; import { Deferred } from '../protocol'; import { ConnectionUI } from '../views/connectionUI'; import StatusView from '../views/statusView'; import VscodeWrapper from './vscodeWrapper'; import { sendActionEvent, sendErrorEvent } from '../telemetry/telemetry'; import { TelemetryActions, TelemetryViews } from '../telemetry/telemetryInterfaces'; import { ObjectExplorerUtils } from '../objectExplorer/objectExplorerUtils'; /** * Information for a document's connection. Exported for testing purposes. */ export class ConnectionInfo { /** * Connection GUID returned from the service host */ public connectionId: string; /** * Credentials used to connect */ public credentials: IConnectionInfo; /** * Callback for when a connection notification is received. */ public connectHandler: (result: boolean, error?: any) => void; public connectionCompleteHandler: (result: ConnectionContracts.ConnectionCompleteParams) => void; /** * Information about the SQL Server instance. */ public serverInfo: IServerInfo; /** * Whether the connection is in the process of connecting. */ public connecting: boolean; /** * The MS SQL error number coming from the server */ public errorNumber: number; /** * The MS SQL error message coming from the server */ public errorMessage: string; public get loginFailed(): boolean { return this.errorNumber !== undefined && this.errorNumber === Constants.errorLoginFailed; } } export interface IReconnectAction { (profile: IConnectionInfo): Promise<void>; } // ConnectionManager class is the main controller for connection management export default class ConnectionManager { private _statusView: StatusView; private _connections: { [fileUri: string]: ConnectionInfo }; private _connectionCredentialsToServerInfoMap: Map<IConnectionInfo, IServerInfo>; private _uriToConnectionPromiseMap: Map<string, Deferred<boolean>>; private _uriToConnectionCompleteParamsMap: Map<string, Deferred<ConnectionContracts.ConnectionCompleteParams>>; private _failedUriToFirewallIpMap: Map<string, string>; private _failedUriToSSLMap: Map<string, string>; private _accountService: AccountService; private _firewallService: FirewallService; public azureController: AzureController; constructor(context: vscode.ExtensionContext, statusView: StatusView, prompter: IPrompter, private _client?: SqlToolsServerClient, private _vscodeWrapper?: VscodeWrapper, private _connectionStore?: ConnectionStore, private _credentialStore?: CredentialStore, private _connectionUI?: ConnectionUI, private _accountStore?: AccountStore) { this._statusView = statusView; this._connections = {}; this._connectionCredentialsToServerInfoMap = new Map<IConnectionInfo, IServerInfo>(); this._uriToConnectionPromiseMap = new Map<string, Deferred<boolean>>(); this._uriToConnectionCompleteParamsMap = new Map<string, Deferred<ConnectionContracts.ConnectionCompleteParams>>(); if (!this.client) { this.client = SqlToolsServerClient.instance; } if (!this.vscodeWrapper) { this.vscodeWrapper = new VscodeWrapper(); } if (!this._credentialStore) { this._credentialStore = new CredentialStore(context); } if (!this._connectionStore) { this._connectionStore = new ConnectionStore(context, this.client?.logger, this._credentialStore); } if (!this._accountStore) { this._accountStore = new AccountStore(context, this.client?.logger); } if (!this._connectionUI) { this._connectionUI = new ConnectionUI(this, context, this._connectionStore, this._accountStore, prompter, this.vscodeWrapper); } if (!this.azureController) { this.azureController = new MsalAzureController(context, prompter, this._credentialStore); this.azureController.init(); } // Initiate the firewall service this._accountService = new AccountService(this.client, this._accountStore, this.azureController); this._firewallService = new FirewallService(this._accountService); this._failedUriToFirewallIpMap = new Map<string, string>(); this._failedUriToSSLMap = new Map<string, string>(); if (this.client !== undefined) { this.client.onNotification(ConnectionContracts.ConnectionChangedNotification.type, this.handleConnectionChangedNotification()); this.client.onNotification(ConnectionContracts.ConnectionCompleteNotification.type, this.handleConnectionCompleteNotification()); this.client.onNotification(LanguageServiceContracts.IntelliSenseReadyNotification.type, this.handleLanguageServiceUpdateNotification()); } } /** * Exposed for testing purposes */ public get vscodeWrapper(): VscodeWrapper { return this._vscodeWrapper!; } /** * Exposed for testing purposes */ public set vscodeWrapper(wrapper: VscodeWrapper) { this._vscodeWrapper = wrapper; } /** * Exposed for testing purposes */ public get client(): SqlToolsServerClient { return this._client!; } /** * Exposed for testing purposes */ public set client(client: SqlToolsServerClient) { this._client = client; } /** * Get the connection view. */ public get connectionUI(): ConnectionUI { return this._connectionUI!; } /** * Exposed for testing purposes */ public get statusView(): StatusView { return this._statusView; } /** * Exposed for testing purposes */ public set statusView(value: StatusView) { this._statusView = value; } /** * Exposed for testing purposes */ public get connectionStore(): ConnectionStore { return this._connectionStore!; } /** * Exposed for testing purposes */ public set connectionStore(value: ConnectionStore) { this._connectionStore = value; } /** * Exposed for testing purposes */ public get accountStore(): AccountStore { return this._accountStore!; } /** * Exposed for testing purposes */ public set accountStore(value: AccountStore) { this._accountStore = value; } /** * Exposed for testing purposes */ public get connectionCount(): number { return Object.keys(this._connections).length; } public get failedUriToFirewallIpMap(): Map<string, string> { return this._failedUriToFirewallIpMap; } public get failedUriToSSLMap(): Map<string, string> { return this._failedUriToSSLMap; } public get accountService(): AccountService { return this._accountService; } public get firewallService(): FirewallService { return this._firewallService; } public isActiveConnection(credential: IConnectionInfo): boolean { const connectedCredentials = Object.keys(this._connections).map((uri) => this._connections[uri].credentials); for (let connectedCredential of connectedCredentials) { if (Utils.isSameConnection(credential, connectedCredential)) { return true; } } return false; } public getUriForConnection(connection: IConnectionInfo): string { for (let uri of Object.keys(this._connections)) { if (Utils.isSameConnection(this._connections[uri].credentials, connection)) { return uri; } } return undefined; } public isConnected(fileUri: string): boolean { return (fileUri in this._connections && this._connections[fileUri].connectionId && Utils.isNotEmpty(this._connections[fileUri].connectionId)); } public isConnecting(fileUri: string): boolean { return (fileUri in this._connections && this._connections[fileUri].connecting); } /** * Get the connection string for the provided connection Uri or ConnectionDetails. * @param connectionUriOrDetails Either the connection Uri for the connection or the connection details for the connection is required. * @param includePassword (optional) if password should be included in connection string. * @param includeApplicationName (optional) if application name should be included in connection string. * @returns connection string for the connection */ public async getConnectionString(connectionUriOrDetails: string | ConnectionDetails, includePassword: boolean = false, includeApplicationName: boolean = true): Promise<string> { const listParams = new ConnectionContracts.GetConnectionStringParams(); if (typeof connectionUriOrDetails === 'string') { listParams.ownerUri = connectionUriOrDetails; } else { listParams.connectionDetails = connectionUriOrDetails; } listParams.includePassword = includePassword; listParams.includeApplicationName = includeApplicationName; return this.client.sendRequest(ConnectionContracts.GetConnectionStringRequest.type, listParams); } /** * Set connection details for the provided connection info * Able to use this for getConnectionString requests to STS that require ConnectionDetails type * @param connectionInfo connection info of the connection * @returns connection details credentials for the connection */ public createConnectionDetails(connectionInfo: IConnectionInfo): ConnectionDetails { return ConnectionCredentials.createConnectionDetails(connectionInfo); } /** * Send a request to the SQL Tools Server client * @param requestType The type of the request * @param params The params to pass with the request * @returns A promise object for when the request receives a response */ public async sendRequest<P, R, E, R0>(requestType: RequestType<P, R, E, R0>, params?: P): Promise<R> { return await this.client.sendRequest(requestType, params); } /** * Exposed for testing purposes. */ public getConnectionInfo(fileUri: string): ConnectionInfo { return this._connections[fileUri]; } /** * Public for testing purposes only. */ public handleLanguageServiceUpdateNotification(): NotificationHandler<LanguageServiceContracts.IntelliSenseReadyParams> { // Using a lambda here to perform variable capture on the 'this' reference return (event: LanguageServiceContracts.IntelliSenseReadyParams): void => { this._statusView.languageServiceStatusChanged(event.ownerUri, LocalizedConstants.intelliSenseUpdatedStatus); }; } /** * Public for testing purposes only. */ public handleConnectionChangedNotification(): NotificationHandler<ConnectionContracts.ConnectionChangedParams> { // Using a lambda here to perform variable capture on the 'this' reference const self = this; return (event: ConnectionContracts.ConnectionChangedParams): void => { if (self.isConnected(event.ownerUri)) { let connectionInfo: ConnectionInfo = self._connections[event.ownerUri]; connectionInfo.credentials.server = event.connection.serverName; connectionInfo.credentials.database = event.connection.databaseName; connectionInfo.credentials.user = event.connection.userName; self._statusView.connectSuccess(event.ownerUri, connectionInfo.credentials, connectionInfo.serverInfo); let logMessage = Utils.formatString(LocalizedConstants.msgChangedDatabaseContext, event.connection.databaseName, event.ownerUri); self.vscodeWrapper.logToOutputChannel(logMessage); } }; } /** * Public for testing purposes only. */ public handleConnectionCompleteNotification(): NotificationHandler<ConnectionContracts.ConnectionCompleteParams> { // Using a lambda here to perform variable capture on the 'this' reference const self = this; return async (result: ConnectionContracts.ConnectionCompleteParams): Promise<void> => { let fileUri = result.ownerUri; let connection = self.getConnectionInfo(fileUri); connection.connecting = false; let mruConnection: IConnectionInfo = <any>{}; if (Utils.isNotEmpty(result.connectionId)) { // Use the original connection information to save the MRU connection. // for connections that a database is not provided, the database information will be updated // to the default database name, if we use the new information as the MRU connection, // the connection information will be different from the saved connections (saved connection's database property is empty). // When deleting the saved connection, we won't be able to find its corresponding recent connection, // and the saved connection credentials will become orphaned. mruConnection = Utils.deepClone(connection.credentials); // Convert to credentials if it's a connection string based connection if (connection.credentials.connectionString) { connection.credentials = await this.populateCredentialsFromConnectionString(connection.credentials, result.connectionSummary); } this._connectionCredentialsToServerInfoMap.set(connection.credentials, result.serverInfo); // We have a valid connection // Copy credentials as the database name will be updated let newCredentials: IConnectionInfo = <any>{}; Object.assign<IConnectionInfo, IConnectionInfo>(newCredentials, connection.credentials); if (result.connectionSummary && result.connectionSummary.databaseName) { newCredentials.database = result.connectionSummary.databaseName; mruConnection.database = result.connectionSummary.databaseName; } self.handleConnectionSuccess(fileUri, connection, newCredentials, result); const promise = self._uriToConnectionPromiseMap.get(result.ownerUri); if (promise) { promise.resolve(true); self._uriToConnectionPromiseMap.delete(result.ownerUri); } const completePromise = self._uriToConnectionCompleteParamsMap.get(result.ownerUri); if (completePromise) { completePromise.resolve(result); self._uriToConnectionCompleteParamsMap.delete(result.ownerUri); } } else { mruConnection = undefined; const promise = self._uriToConnectionPromiseMap.get(result.ownerUri); if (promise) { if (result.errorMessage) { await self.handleConnectionErrors(fileUri, connection, result); promise.reject(result.errorMessage); self._uriToConnectionPromiseMap.delete(result.ownerUri); } else if (result.messages) { promise.reject(result.messages); self._uriToConnectionPromiseMap.delete(result.ownerUri); } } const completePromise = self._uriToConnectionCompleteParamsMap.get(result.ownerUri); if (completePromise) { completePromise.resolve(result); self._uriToConnectionCompleteParamsMap.delete(result.ownerUri); } await self.handleConnectionErrors(fileUri, connection, result); } await self.tryAddMruConnection(connection, mruConnection); }; } private handleConnectionSuccess( fileUri: string, connection: ConnectionInfo, newCredentials: IConnectionInfo, result: ConnectionContracts.ConnectionCompleteParams): void { connection.connectionId = result.connectionId; connection.serverInfo = result.serverInfo; connection.credentials = newCredentials; connection.errorNumber = undefined; connection.errorMessage = undefined; this.statusView.connectSuccess(fileUri, newCredentials, connection.serverInfo); this.statusView.languageServiceStatusChanged(fileUri, LocalizedConstants.updatingIntelliSenseStatus); this._vscodeWrapper.logToOutputChannel( Utils.formatString(LocalizedConstants.msgConnectedServerInfo, connection.credentials.server, fileUri, JSON.stringify(connection.serverInfo)) ); sendActionEvent( TelemetryViews.ConnectionPrompt, TelemetryActions.CreateConnectionResult, undefined, undefined, newCredentials as IConnectionProfile, result.serverInfo ); } private async handleConnectionErrors(fileUri: string, connection: ConnectionInfo, result: ConnectionContracts.ConnectionCompleteParams): Promise<void> { if (result.errorNumber && result.errorMessage && !Utils.isEmpty(result.errorMessage)) { // Check if the error is an expired password if (result.errorNumber === Constants.errorPasswordExpired || result.errorNumber === Constants.errorPasswordNeedsReset) { // TODO: we should allow the user to change their password here once corefx supports SqlConnection.ChangePassword() Utils.showErrorMsg(Utils.formatString(LocalizedConstants.msgConnectionErrorPasswordExpired, result.errorNumber, result.errorMessage)); } else if (result.errorNumber === Constants.errorSSLCertificateValidationFailed) { // check if it's an SSL failed error this._failedUriToSSLMap.set(fileUri, result.errorMessage); } else if (result.errorNumber === Constants.errorFirewallRule) { // check whether it's a firewall rule error let firewallResult = await this.firewallService.handleFirewallRule(result.errorNumber, result.errorMessage); if (firewallResult.result && firewallResult.ipAddress) { this.failedUriToFirewallIpMap.set(fileUri, firewallResult.ipAddress); } else { Utils.showErrorMsg(Utils.formatString(LocalizedConstants.msgConnectionError, result.errorNumber, result.errorMessage)); } } else { Utils.showErrorMsg(Utils.formatString(LocalizedConstants.msgConnectionError, result.errorNumber, result.errorMessage)); } connection.errorNumber = result.errorNumber; connection.errorMessage = result.errorMessage; } else { const platformInfo = await PlatformInformation.getCurrent(); if (!platformInfo.isWindows && result.errorMessage && result.errorMessage.includes('Kerberos')) { const action = await this.vscodeWrapper.showErrorMessage( Utils.formatString(LocalizedConstants.msgConnectionError2, result.errorMessage), LocalizedConstants.macOpenSslHelpButton); if (action && action === LocalizedConstants.macOpenSslHelpButton) { await vscode.env.openExternal(vscode.Uri.parse(Constants.integratedAuthHelpLink)); } } else if (platformInfo.runtimeId === Runtime.OSX_10_11_64 && result.messages.indexOf('Unable to load DLL \'System.Security.Cryptography.Native\'') !== -1) { const action = await this.vscodeWrapper.showErrorMessage(Utils.formatString(LocalizedConstants.msgConnectionError2, LocalizedConstants.macOpenSslErrorMessage), LocalizedConstants.macOpenSslHelpButton); if (action && action === LocalizedConstants.macOpenSslHelpButton) { await vscode.env.openExternal(vscode.Uri.parse(Constants.macOpenSslHelpLink)); } } else { Utils.showErrorMsg(Utils.formatString(LocalizedConstants.msgConnectionError2, result.messages)); } } this.statusView.connectError(fileUri, connection.credentials, result); this.vscodeWrapper.logToOutputChannel( Utils.formatString( LocalizedConstants.msgConnectionFailed, connection.credentials.server, result.errorMessage ? result.errorMessage : result.messages) ); sendErrorEvent( TelemetryViews.ConnectionPrompt, TelemetryActions.CreateConnectionResult, new Error(result.errorMessage), false, result.errorNumber?.toString(), undefined, { 'containsError': 'true' }, undefined, connection.credentials as IConnectionProfile, result.serverInfo ); } public async showInstructionTextAsWarning(profile: IConnectionInfo, reconnectAction: IReconnectAction): Promise<void> { const selection = await this.vscodeWrapper.showWarningMessageAdvanced( LocalizedConstants.msgPromptSSLCertificateValidationFailed, { modal: false }, [ LocalizedConstants.enableTrustServerCertificate, LocalizedConstants.readMore, LocalizedConstants.cancel ]); if (selection === LocalizedConstants.enableTrustServerCertificate) { if (profile.connectionString) { // Append connection string with encryption options profile.connectionString = profile.connectionString.concat('; Encrypt=true; Trust Server Certificate=true;'); } profile.encrypt = EncryptOptions.Mandatory; profile.trustServerCertificate = true; await reconnectAction(profile); } else if (selection === LocalizedConstants.readMore) { this.vscodeWrapper.openExternal(Constants.encryptionBlogLink); await this.showInstructionTextAsWarning(profile, reconnectAction); } } public async handleSSLError(uri: string, profile: IConnectionProfile): Promise<IConnectionInfo | undefined> { let updatedConn: IConnectionInfo | undefined; await this.showInstructionTextAsWarning(profile, async updatedConnection => { vscode.commands.executeCommand(Constants.cmdConnectObjectExplorerProfile, updatedConnection); updatedConn = updatedConnection; }); this.failedUriToSSLMap.delete(uri); return updatedConn; } private async tryAddMruConnection(connection: ConnectionInfo, newConnection: IConnectionInfo): Promise<void> { if (newConnection) { let connectionToSave: IConnectionInfo = Object.assign({}, newConnection); try { await this._connectionStore.addRecentlyUsed(connectionToSave); connection.connectHandler(true); } catch (err) { connection.connectHandler(false, err); } } else { connection.connectHandler(false); } } /** * Populates a credential object based on the credential connection string */ private async populateCredentialsFromConnectionString(credentials: IConnectionInfo, connectionSummary: ConnectionSummary): Promise<IConnectionInfo> { // populate credential details credentials.database = connectionSummary.databaseName; credentials.user = connectionSummary.userName; credentials.server = connectionSummary.serverName; // save credentials if needed let isPasswordBased: boolean = ConnectionCredentials.isPasswordBasedConnectionString(credentials.connectionString); if (isPasswordBased) { // save the connection string here await this._connectionStore.saveProfileWithConnectionString(credentials as IConnectionProfile); // replace the conn string from the profile credentials.connectionString = ConnectionStore.formatCredentialId(credentials.server, credentials.database, credentials.user, ConnectionStore.CRED_PROFILE_USER, true); // set auth type credentials.authenticationType = Constants.sqlAuthentication; // set savePassword to true so that credentials are automatically // deleted if the settings file is manually changed (credentials as IConnectionProfile).savePassword = true; } else { credentials.authenticationType = Constants.integratedauth; } return credentials; } /** * Clear the recently used connections list in the connection store. * @returns a boolean value indicating whether the credentials were deleted successfully. */ public clearRecentConnectionsList(): Promise<boolean> { return this.connectionStore.clearRecentlyUsed(); } // choose database to use on current server from UI public async onChooseDatabase(): Promise<boolean> { const fileUri = this.vscodeWrapper.activeTextEditorUri; if (!this.isConnected(fileUri)) { this.vscodeWrapper.showWarningMessage(LocalizedConstants.msgChooseDatabaseNotConnected); return false; } // Get list of databases on current server let listParams = new ConnectionContracts.ListDatabasesParams(); listParams.ownerUri = fileUri; const result: ConnectionContracts.ListDatabasesResult = await this.client.sendRequest(ConnectionContracts.ListDatabasesRequest.type, listParams); // Then let the user select a new database to connect to const newDatabaseCredentials = await this.connectionUI.showDatabasesOnCurrentServer(this._connections[fileUri].credentials, result.databaseNames); if (newDatabaseCredentials) { this.vscodeWrapper.logToOutputChannel( Utils.formatString(LocalizedConstants.msgChangingDatabase, newDatabaseCredentials.database, newDatabaseCredentials.server, fileUri) ); await this.disconnect(fileUri); await this.connect(fileUri, newDatabaseCredentials); this.vscodeWrapper.logToOutputChannel( Utils.formatString( LocalizedConstants.msgChangedDatabase, newDatabaseCredentials.database, newDatabaseCredentials.server, fileUri) ); return true; } else { return false; } } /** * Retrieves the list of databases for the connection specified by the given URI. * @param connectionUri The URI of the connection to list the databases for * @returns The list of databases retrieved from the connection */ public async listDatabases(connectionUri: string): Promise<string[]> { await this.refreshAzureAccountToken(connectionUri); const listParams = new ConnectionContracts.ListDatabasesParams(); listParams.ownerUri = connectionUri; const result: ConnectionContracts.ListDatabasesResult = await this.client.sendRequest(ConnectionContracts.ListDatabasesRequest.type, listParams); return result.databaseNames; } public async changeDatabase(newDatabaseCredentials: IConnectionInfo): Promise<boolean> { const fileUri = this.vscodeWrapper.activeTextEditorUri; if (!this.isConnected(fileUri)) { this.vscodeWrapper.showWarningMessage(LocalizedConstants.msgChooseDatabaseNotConnected); return false; } await this.disconnect(fileUri); await this.connect(fileUri, newDatabaseCredentials); this.vscodeWrapper.logToOutputChannel( Utils.formatString( LocalizedConstants.msgChangedDatabase, newDatabaseCredentials.database, newDatabaseCredentials.server, fileUri)); return true; } public async onChooseLanguageFlavor(isSqlCmdMode: boolean = false, isSqlCmd: boolean = false): Promise<boolean> { const fileUri = this._vscodeWrapper.activeTextEditorUri; if (fileUri && this._vscodeWrapper.isEditingSqlFile) { if (isSqlCmdMode) { SqlToolsServerClient.instance.sendNotification(LanguageServiceContracts.LanguageFlavorChangedNotification.type, <LanguageServiceContracts.DidChangeLanguageFlavorParams>{ uri: fileUri, language: isSqlCmd ? 'sqlcmd' : 'sql', flavor: 'MSSQL' }); return true; } const flavor = await this._connectionUI.promptLanguageFlavor(); if (!flavor) { return false; } this.statusView.languageFlavorChanged(fileUri, flavor); SqlToolsServerClient.instance.sendNotification(LanguageServiceContracts.LanguageFlavorChangedNotification.type, <LanguageServiceContracts.DidChangeLanguageFlavorParams>{ uri: fileUri, language: 'sql', flavor: flavor }); return true; } else { await this._vscodeWrapper.showWarningMessage(LocalizedConstants.msgOpenSqlFile); return false; } } // close active connection, if any public onDisconnect(): Promise<boolean> { return this.disconnect(this.vscodeWrapper.activeTextEditorUri); } public async disconnect(fileUri: string): Promise<boolean> { if (this.isConnected(fileUri)) { let disconnectParams = new ConnectionContracts.DisconnectParams(); disconnectParams.ownerUri = fileUri; const result: ConnectionContracts.DisconnectResult = await this.client.sendRequest(ConnectionContracts.DisconnectRequest.type, disconnectParams); if (this.statusView) { this.statusView.notConnected(fileUri); } if (result) { this.vscodeWrapper.logToOutputChannel( Utils.formatString(LocalizedConstants.msgDisconnected, fileUri) ); } delete this._connections[fileUri]; vscode.commands.executeCommand('setContext', 'mssql.connections', this._connections); return result; } else if (this.isConnecting(fileUri)) { // Prompt the user to cancel connecting await this.onCancelConnect(); return true; } else { return true; } } /** * Helper to show all connections and perform connect logic. */ public async showConnectionsAndConnect(fileUri: string): Promise<IConnectionInfo> { // show connection picklist const connectionCreds = await this.connectionUI.promptForConnection(); if (connectionCreds) { // close active connection await this.disconnect(fileUri); // connect to the server/database const result = await this.connect(fileUri, connectionCreds); await this.handleConnectionResult(result, fileUri, connectionCreds); } return connectionCreds; } /** * Get the server info for a connection * @param connectionCreds */ public getServerInfo(connectionCredentials: IConnectionInfo): IServerInfo { if (this._connectionCredentialsToServerInfoMap.has(connectionCredentials)) { return this._connectionCredentialsToServerInfoMap.get(connectionCredentials); } } /** * Verifies the connection result. If connection failed because of invalid credentials, * tries to connect again by asking user for different credentials * @param result Connection result * @param fileUri file Uri * @param connectionCreds Connection Profile */ public async handleConnectionResult(result: boolean, fileUri: string, connectionCreds: IConnectionInfo): Promise<boolean> { let connection = this._connections[fileUri]; if (!result && connection && connection.loginFailed) { const newConnection = await this.connectionUI.createProfileWithDifferentCredentials(connectionCreds); if (newConnection) { const newResult = await this.connect(fileUri, newConnection); connection = this._connections[fileUri]; if (!newResult && connection && connection.loginFailed) { Utils.showErrorMsg(Utils.formatString(LocalizedConstants.msgConnectionError, connection.errorNumber, connection.errorMessage)); } return newResult; } else { return true; } } else { return true; } } /** * Delete a credential from the credential store */ public async deleteCredential(profile: IConnectionProfile): Promise<boolean> { return await this._connectionStore.deleteCredential(profile); } // let users pick from a picklist of connections public async onNewConnection(): Promise<IConnectionInfo> { const fileUri = this.vscodeWrapper.activeTextEditorUri; if (!fileUri) { // A text document needs to be open before we can connect this.vscodeWrapper.showWarningMessage(LocalizedConstants.msgOpenSqlFile); return undefined; } else if (!this.vscodeWrapper.isEditingSqlFile) { const result = await this.connectionUI.promptToChangeLanguageMode(); if (result) { const credentials = await this.showConnectionsAndConnect(fileUri); return credentials; } else { return undefined; } } const creds = await this.showConnectionsAndConnect(fileUri); return creds; } // create a new connection with the connectionCreds provided public async connect(fileUri: string, connectionCreds: IConnectionInfo, promise?: Deferred<boolean>): Promise<boolean> { return await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: LocalizedConstants.connectProgressNoticationTitle, cancellable: false }, async (_progress, _token) => { if (!connectionCreds.server && !connectionCreds.connectionString) { throw new Error(LocalizedConstants.serverNameMissing); } // Check if the azure account token is present before sending connect request (only with SQL Auth Provider is not enabled.) if (connectionCreds.authenticationType === Constants.azureMfa) { if (AzureController.isTokenInValid(connectionCreds.azureAccountToken, connectionCreds.expiresOn)) { let account: IAccount; let profile: ConnectionProfile; if (connectionCreds.accountId) { account = this.accountStore.getAccount(connectionCreds.accountId); profile = new ConnectionProfile(connectionCreds); } else { throw new Error(LocalizedConstants.cannotConnect); } if (account) { // Always set username connectionCreds.user = account.displayInfo.displayName; connectionCreds.email = account.displayInfo.email; profile.user = account.displayInfo.displayName; profile.email = account.displayInfo.email; let azureAccountToken = await this.azureController.refreshAccessToken(account!, this.accountStore, profile.tenantId, providerSettings.resources.databaseResource!); if (!azureAccountToken) { let errorMessage = LocalizedConstants.msgAccountRefreshFailed; let refreshResult = await this.vscodeWrapper.showErrorMessage(errorMessage, LocalizedConstants.refreshTokenLabel); if (refreshResult === LocalizedConstants.refreshTokenLabel) { await this.azureController.populateAccountProperties( profile, this.accountStore, providerSettings.resources.databaseResource!); } else { throw new Error(LocalizedConstants.cannotConnect); } } else { connectionCreds.azureAccountToken = azureAccountToken.token; connectionCreds.expiresOn = azureAccountToken.expiresOn; } } else { throw new Error(LocalizedConstants.msgAccountNotFound); } } } let connectionPromise = new Promise<boolean>(async (resolve, reject) => { if (connectionCreds.connectionString?.includes(ConnectionStore.CRED_PREFIX) && connectionCreds.connectionString?.includes('isConnectionString:true')) { let connectionString = await this.connectionStore.lookupPassword(connectionCreds, true); connectionCreds.connectionString = connectionString; } let connectionInfo: ConnectionInfo = new ConnectionInfo(); connectionInfo.credentials = connectionCreds; connectionInfo.connecting = true; this._connections[fileUri] = connectionInfo; // Note: must call flavor changed before connecting, or the timer showing an animation doesn't occur if (this.statusView) { this.statusView.languageFlavorChanged(fileUri, Constants.mssqlProviderName); this.statusView.connecting(fileUri, connectionCreds); this.statusView.languageFlavorChanged(fileUri, Constants.mssqlProviderName); } this.vscodeWrapper.logToOutputChannel( Utils.formatString(LocalizedConstants.msgConnecting, connectionCreds.server, fileUri) ); // Setup the handler for the connection complete notification to call connectionInfo.connectHandler = ((connectResult, error) => { if (error) { reject(error); } else { vscode.commands.executeCommand('setContext', 'mssql.connections', this._connections); resolve(connectResult); } }); // package connection details for request message const connectionDetails = ConnectionCredentials.createConnectionDetails(connectionCreds); let connectParams = new ConnectionContracts.ConnectParams(); connectParams.ownerUri = fileUri; connectParams.connection = connectionDetails; // send connection request message to service host this._uriToConnectionPromiseMap.set(connectParams.ownerUri, promise!); try { const result = await this.client.sendRequest(ConnectionContracts.ConnectionRequest.type, connectParams); if (!result) { // Failed to process connect request resolve(false); } } catch (error) { reject(error); } }); return connectionPromise; }); } public async connectDialog(connectionCreds: IConnectionInfo): Promise<ConnectionContracts.ConnectionCompleteParams> { // If the connection info doesn't have server or connection string, throw an error if (!connectionCreds.server && !connectionCreds.connectionString) { throw new Error(LocalizedConstants.serverNameMissing); } if (connectionCreds.authenticationType === Constants.azureMfa) { if (AzureController.isTokenInValid(connectionCreds.azureAccountToken, connectionCreds.expiresOn)) { let account: IAccount; let profile: ConnectionProfile; if (connectionCreds.accountId) { account = this.accountStore.getAccount(connectionCreds.accountId); profile = new ConnectionProfile(connectionCreds); } else { throw new Error(LocalizedConstants.cannotConnect); } if (account) { // Always set username connectionCreds.user = account.displayInfo.displayName; connectionCreds.email = account.displayInfo.email; profile.user = account.displayInfo.displayName; profile.email = account.displayInfo.email; let azureAccountToken = await this.azureController.refreshAccessToken(account!, this.accountStore, profile.tenantId, providerSettings.resources.databaseResource!); if (!azureAccountToken) { let errorMessage = LocalizedConstants.msgAccountRefreshFailed; let refreshResult = await this.vscodeWrapper.showErrorMessage(errorMessage, LocalizedConstants.refreshTokenLabel); if (refreshResult === LocalizedConstants.refreshTokenLabel) { await this.azureController.populateAccountProperties( profile, this.accountStore, providerSettings.resources.databaseResource!); } else { throw new Error(LocalizedConstants.cannotConnect); } } else { connectionCreds.azureAccountToken = azureAccountToken.token; connectionCreds.expiresOn = azureAccountToken.expiresOn; } } else { throw new Error(LocalizedConstants.msgAccountNotFound); } } } if (connectionCreds.connectionString?.includes(ConnectionStore.CRED_PREFIX) && connectionCreds.connectionString?.includes('isConnectionString:true')) { let connectionString = await this.connectionStore.lookupPassword(connectionCreds, true); connectionCreds.connectionString = connectionString; } const uri = ObjectExplorerUtils.getNodeUriFromProfile(connectionCreds as IConnectionProfile); let connectionInfo: ConnectionInfo = new ConnectionInfo(); connectionInfo.credentials = connectionCreds; connectionInfo.connecting = true; // Setup the handler for the connection complete notification to call connectionInfo.connectHandler = ((connectResult, error) => { }); this._connections[uri] = connectionInfo; // Note: must call flavor changed before connecting, or the timer showing an animation doesn't occur if (this.statusView) { this.statusView.languageFlavorChanged(uri, Constants.mssqlProviderName); this.statusView.connecting(uri, connectionCreds); this.statusView.languageFlavorChanged(uri, Constants.mssqlProviderName); } // this.vscodeWrapper.logToOutputChannel( // Utils.formatString(LocalizedConstants.msgConnecting, connectionCreds.server, fileUri) // ); const connectionDetails = ConnectionCredentials.createConnectionDetails(connectionCreds); let connectParams = new ConnectionContracts.ConnectParams(); connectParams.ownerUri = uri; connectParams.connection = connectionDetails; const connectionCompletePromise = new Deferred<ConnectionContracts.ConnectionCompleteParams>(); this._uriToConnectionCompleteParamsMap.set(connectParams.ownerUri, connectionCompletePromise); try { const result = await this.client.sendRequest(ConnectionContracts.ConnectionRequest.type, connectParams); if (!result) { // Failed to process connect request throw new Error('Failed to connect'); } } catch (error) { throw new Error('Failed to connect'); } return await connectionCompletePromise; } public async onCancelConnect(): Promise<void> { const result = await this.connectionUI.promptToCancelConnection(); if (result) { await this.cancelConnect(); } } public async cancelConnect(): Promise<void> { let fileUri = this.vscodeWrapper.activeTextEditorUri; if (!fileUri || Utils.isEmpty(fileUri)) { return; } let cancelParams: ConnectionContracts.CancelConnectParams = new ConnectionContracts.CancelConnectParams(); cancelParams.ownerUri = fileUri; const result = await this.client.sendRequest(ConnectionContracts.CancelConnectRequest.type, cancelParams); if (result) { this.statusView.notConnected(fileUri); } } /** * Called when the 'Manage Connection Profiles' command is issued. */ public onManageProfiles(): Promise<boolean> { // Show quick pick to create, edit, or remove profiles return this.connectionUI.promptToManageProfiles(); } public async onClearPooledConnections(): Promise<void> { return await this._client.sendRequest(ClearPooledConnectionsRequest.type, {}); } public async onCreateProfile(): Promise<boolean> { let self = this; const profile = await self.connectionUI.createAndSaveProfile(self.vscodeWrapper.isEditingSqlFile); return profile ? true : false; } public onRemoveProfile(): Promise<boolean> { return this.connectionUI.removeProfile(); } public async onDidCloseTextDocument(doc: vscode.TextDocument): Promise<void> { let docUri: string = doc.uri.toString(true); // If this file isn't connected, then don't do anything if (!this.isConnected(docUri)) { return; } // Disconnect the document's connection when we close it await this.disconnect(docUri); } public onDidOpenTextDocument(doc: vscode.TextDocument): void { let uri = doc.uri.toString(true); if (doc.languageId === 'sql' && typeof (this._connections[uri]) === 'undefined') { this.statusView.notConnected(uri); } } public async transferFileConnection(oldFileUri: string, newFileUri: string): Promise<void> { // Is the new file connected or the old file not connected? if (!this.isConnected(oldFileUri) || this.isConnected(newFileUri)) { return; } // Connect the saved uri and disconnect the untitled uri on successful connection let creds: IConnectionInfo = this._connections[oldFileUri].credentials; let result = await this.connect(newFileUri, creds); if (result) { await this.disconnect(oldFileUri); } } public async refreshAzureAccountToken(uri: string): Promise<void> { const profile = this.getConnectionInfo(uri); if (!profile) { this.vscodeWrapper.logToOutputChannel(Utils.formatString(LocalizedConstants.msgConnectionNotFound, uri)); return; } // Wait for the pending reconnction promise if any const previousReconnectPromise = this._uriToConnectionPromiseMap.get(uri); if (previousReconnectPromise) { this.vscodeWrapper.logToOutputChannel(Utils.formatString(LocalizedConstants.msgFoundPendingReconnect, uri)); try { const previousConnectionResult = await previousReconnectPromise; if (previousConnectionResult) { this.vscodeWrapper.logToOutputChannel(Utils.formatString(LocalizedConstants.msgPendingReconnectSuccess, uri)); return; } this.vscodeWrapper.logToOutputChannel(Utils.formatString(LocalizedConstants.msgFoundPendingReconnectFailed, uri)); } catch (err) { this.vscodeWrapper.logToOutputChannel(Utils.formatString(LocalizedConstants.msgFoundPendingReconnectError, uri, err)); } } const expiry = profile.credentials.expiresOn; if (typeof expiry === 'number' && !Number.isNaN(expiry)) { if (AzureController.isTokenExpired(expiry)) { this.vscodeWrapper.logToOutputChannel(Utils.formatString(LocalizedConstants.msgAcessTokenExpired, profile.connectionId, uri)); try { let connectionResult = await this.connect(uri, profile.credentials); if (!connectionResult) { this.vscodeWrapper.showErrorMessage(Utils.formatString(LocalizedConstants.msgRefreshConnection, profile.connectionId, uri)); throw new Error('Unable to refresh connection'); } this.vscodeWrapper.logToOutputChannel(Utils.formatString(LocalizedConstants.msgRefreshTokenSuccess, profile.connectionId, uri, this.getConnectionInfo(uri))); return; } catch { this.vscodeWrapper.showInformationMessage(Utils.formatString(LocalizedConstants.msgRefreshTokenError)); } } this.vscodeWrapper.logToOutputChannel(Utils.formatString(LocalizedConstants.msgRefreshTokenNotNeeded, profile.connectionId, uri)); } return; } public async addAccount(): Promise<IAccount> { let account = await this.connectionUI.addNewAccount(); if (account) { this.vscodeWrapper.showInformationMessage(Utils.formatString(LocalizedConstants.accountAddedSuccessfully, account.displayInfo.displayName)); } else { this.vscodeWrapper.showErrorMessage(LocalizedConstants.accountCouldNotBeAdded); } return account; } public async removeAccount(prompter: IPrompter): Promise<void> { // list options for accounts to remove let questions: IQuestion[] = []; let azureAccountChoices = ConnectionProfile.getAccountChoices(this._accountStore); if (azureAccountChoices.length > 0) { questions.push( { type: QuestionTypes.expand, name: 'account', message: LocalizedConstants.azureChooseAccount, choices: azureAccountChoices } ); return prompter.prompt<IAccount>(questions, true).then(async answers => { if (answers?.account) { try { this._accountStore.removeAccount(answers.account.key.id); this.azureController.removeAccount(answers.account); this.vscodeWrapper.showInformationMessage(LocalizedConstants.accountRemovedSuccessfully); } catch (e) { this.vscodeWrapper.showErrorMessage(Utils.formatString(LocalizedConstants.accountRemovalFailed, e.message)); } } }); } else { this.vscodeWrapper.showInformationMessage(LocalizedConstants.noAzureAccountForRemoval); } } public onClearTokenCache(): void { this.azureController.clearTokenCache(); this.vscodeWrapper.showInformationMessage(LocalizedConstants.clearedAzureTokenCache); } } ```
/content/code_sandbox/src/controllers/connectionManager.ts
xml
2016-06-26T04:38:04
2024-08-16T20:04:12
vscode-mssql
microsoft/vscode-mssql
1,523
9,894
```xml import "reflect-metadata" import { DataSource } from "../../../src/data-source/DataSource" import { closeTestingConnections, createTestingConnections, } from "../../utils/test-utils" import { One } from "./entity/One" /** * This test attempts to benchmark the raw CPU usage/latency of the query builder's * SQL string generation. We intentionally don't migrate the database or perform * any actual queries. */ describe("benchmark > QueryBuilder > wide join", () => { let connections: DataSource[] before( async () => (connections = await createTestingConnections({ __dirname, enabledDrivers: ["postgres"], })), ) after(() => closeTestingConnections(connections)) it("testing query builder with join to 10 relations with 10 columns each", () => { for (let i = 1; i <= 10_000; i++) { connections.forEach((connection) => connection.manager .createQueryBuilder(One, "ones") .setFindOptions({ where: { id: 1 }, relations: { two: true, three: true, four: true, five: true, six: true, seven: true, eight: true, nine: true, ten: true, }, }) .getQuery(), ) } /** * On a M1 macbook air, 5 runs: * 1861ms * 1850ms * 1859ms * 1859ms * 1884ms */ }) }) ```
/content/code_sandbox/test/benchmark/multiple-joins-querybuilder/multiple-joins-querybuilder.ts
xml
2016-02-29T07:41:14
2024-08-16T18:28:52
typeorm
typeorm/typeorm
33,875
340
```xml import {Component} from '@angular/core'; import {MatMenuModule} from '@angular/material/menu'; /** * @title Testing with MatMenuHarness */ @Component({ selector: 'menu-harness-example', templateUrl: 'menu-harness-example.html', standalone: true, imports: [MatMenuModule], }) export class MenuHarnessExample {} ```
/content/code_sandbox/src/components-examples/material/menu/menu-harness/menu-harness-example.ts
xml
2016-01-04T18:50:02
2024-08-16T11:21:13
components
angular/components
24,263
74
```xml import Utils from '../lib/Utils.js'; import { TwoVector } from './TwoVector.js'; import { ThreeVector } from './ThreeVector.js'; import Quaternion from './Quaternion.js'; import BaseTypes from './BaseTypes.js'; import Serializable from './Serializable.js'; const MAX_UINT_16 = 0xFFFF; type DataItem = number | string | Object; type DataDesc = { data: DataItem, bufferSize: number } /** * The Serializer is responsible for serializing the game world and its * objects on the server, before they are sent to each client. On the client side the * Serializer deserializes these objects. * */ class Serializer { public registeredClasses: { [key: string]: any } public customTypes: { [key: string]: any} constructor() { this.registeredClasses = {}; this.customTypes = {}; this.registerClass(TwoVector); this.registerClass(ThreeVector); this.registerClass(Quaternion); } /** * Adds a custom primitive to the serializer instance. * This will enable you to use it in an object's netScheme * @param customType */ // TODO: the function below is not used, and it is not clear what that // first argument is supposed to be addCustomType(customType) { this.customTypes[customType.type] = customType; } /** * Checks if type can be assigned by value. * @param {String} type Type to Checks * @return {Boolean} True if type can be assigned */ static typeCanAssign(type) { return type !== BaseTypes.ClassInstance && type !== BaseTypes.List; } /** * Registers a new class with the serializer, so it may be deserialized later * @param {Function} classObj reference to the class (not an instance!) * @param {String} classId Unit specifying a class ID */ registerClass(classObj, classId?) { // if no classId is specified, hash one from the class name classId = classId ? classId : Utils.hashStr(classObj.name); if (this.registeredClasses[classId]) { console.error(`Serializer: accidental override of classId ${classId} when registering class`, classObj); } this.registeredClasses[classId] = classObj; } deserialize(dataBuffer, byteOffset = 0) { let localByteOffset = 0; let dataView = new DataView(dataBuffer); let objectClassId = dataView.getUint8(byteOffset + localByteOffset); // todo if classId is 0 - take care of dynamic serialization. let objectClass = this.registeredClasses[objectClassId]; if (objectClass == null) { console.error('Serializer: Found a class which was not registered. Please use serializer.registerClass() to register all serialized classes.'); } localByteOffset += Uint8Array.BYTES_PER_ELEMENT; // advance the byteOffset after the classId // create de-referenced instance of the class. gameEngine and id will be 'tacked on' later at the sync strategies let obj = new objectClass(null, {}, {}); for (let property of Object.keys(obj.netScheme()).sort()) { let read = this.readDataView(dataView, byteOffset + localByteOffset, obj.netScheme()[property]); obj[property] = read.data; localByteOffset += read.bufferSize; } return { obj, byteOffset: localByteOffset }; } writeDataView(dataView, value, bufferOffset, netSchemProp) { if (netSchemProp.type === BaseTypes.Float32) { dataView.setFloat32(bufferOffset, value); } else if (netSchemProp.type === BaseTypes.Int32) { dataView.setInt32(bufferOffset, value); } else if (netSchemProp.type === BaseTypes.Int16) { dataView.setInt16(bufferOffset, value); } else if (netSchemProp.type === BaseTypes.Int8) { dataView.setInt8(bufferOffset, value); } else if (netSchemProp.type === BaseTypes.UInt8) { dataView.setUint8(bufferOffset, value); } else if (netSchemProp.type === BaseTypes.String) { // MAX_UINT_16 is a reserved (length) value which indicates string hasn't changed if (value === null) { dataView.setUint16(bufferOffset, MAX_UINT_16); } else { let strLen = value.length; dataView.setUint16(bufferOffset, strLen); let localBufferOffset = 2; for (let i = 0; i < strLen; i++) dataView.setUint16(bufferOffset + localBufferOffset + i * 2, value.charCodeAt(i)); } } else if (netSchemProp.type === BaseTypes.ClassInstance) { value.serialize(this, { dataBuffer: dataView.buffer, bufferOffset: bufferOffset }); } else if (netSchemProp.type === BaseTypes.List) { let localBufferOffset = 0; // a list is comprised of the number of items followed by the items dataView.setUint16(bufferOffset + localBufferOffset, value.length); localBufferOffset += Uint16Array.BYTES_PER_ELEMENT; for (let item of value) { // TODO: inelegant, currently doesn't support list of lists if (netSchemProp.itemType === BaseTypes.ClassInstance) { let serializedObj = item.serialize(this, { dataBuffer: dataView.buffer, bufferOffset: bufferOffset + localBufferOffset }); localBufferOffset += serializedObj.bufferOffset; } else if (netSchemProp.itemType === BaseTypes.String) { // MAX_UINT_16 is a reserved (length) value which indicates string hasn't changed if (item === null) { dataView.setUint16(bufferOffset + localBufferOffset, MAX_UINT_16); localBufferOffset += Uint16Array.BYTES_PER_ELEMENT; } else { let strLen = item.length; dataView.setUint16(bufferOffset + localBufferOffset, strLen); localBufferOffset += Uint16Array.BYTES_PER_ELEMENT; for (let i = 0; i < strLen; i++) dataView.setUint16(bufferOffset + localBufferOffset + i * 2, item.charCodeAt(i)); localBufferOffset += Uint16Array.BYTES_PER_ELEMENT * strLen; } } else { this.writeDataView(dataView, item, bufferOffset + localBufferOffset, { type: netSchemProp.itemType }); localBufferOffset += this.getTypeByteSize(netSchemProp.itemType); } } } else if (this.customTypes[netSchemProp.type]) { // this is a custom data property which needs to define its own write method this.customTypes[netSchemProp.type].writeDataView(dataView, value, bufferOffset); } else { console.error(`No custom property ${netSchemProp.type} found!`); } } readDataView(dataView: DataView, bufferOffset, netSchemProp): DataDesc { let data, bufferSize; if (netSchemProp.type === BaseTypes.Float32) { data = dataView.getFloat32(bufferOffset); bufferSize = this.getTypeByteSize(netSchemProp.type); } else if (netSchemProp.type === BaseTypes.Int32) { data = dataView.getInt32(bufferOffset); bufferSize = this.getTypeByteSize(netSchemProp.type); } else if (netSchemProp.type === BaseTypes.Int16) { data = dataView.getInt16(bufferOffset); bufferSize = this.getTypeByteSize(netSchemProp.type); } else if (netSchemProp.type === BaseTypes.Int8) { data = dataView.getInt8(bufferOffset); bufferSize = this.getTypeByteSize(netSchemProp.type); } else if (netSchemProp.type === BaseTypes.UInt8) { data = dataView.getUint8(bufferOffset); bufferSize = this.getTypeByteSize(netSchemProp.type); } else if (netSchemProp.type === BaseTypes.String) { let length = dataView.getUint16(bufferOffset); let localBufferOffset = Uint16Array.BYTES_PER_ELEMENT; bufferSize = localBufferOffset; if (length === MAX_UINT_16) { data = null; } else { let a: number[] = []; for (let i = 0; i < length; i++) a[i] = dataView.getUint16(bufferOffset + localBufferOffset + i * 2); data = String.fromCharCode.apply(null, a); bufferSize += length * Uint16Array.BYTES_PER_ELEMENT; } } else if (netSchemProp.type === BaseTypes.ClassInstance) { var deserializeData = this.deserialize(dataView.buffer, bufferOffset); data = deserializeData.obj; bufferSize = deserializeData.byteOffset; } else if (netSchemProp.type === BaseTypes.List) { let localBufferOffset = 0; let items: DataItem[] = []; let itemCount = dataView.getUint16(bufferOffset + localBufferOffset); localBufferOffset += Uint16Array.BYTES_PER_ELEMENT; for (let x = 0; x < itemCount; x++) { let read = this.readDataView(dataView, bufferOffset + localBufferOffset, { type: netSchemProp.itemType }); items.push(read.data); localBufferOffset += read.bufferSize; } data = items; bufferSize = localBufferOffset; } else if (this.customTypes[netSchemProp.type] != null) { // this is a custom data property which needs to define its own read method data = this.customTypes[netSchemProp.type].readDataView(dataView, bufferOffset); } else { console.error(`No custom property ${netSchemProp.type} found!`); } return { data: data, bufferSize: bufferSize }; } getTypeByteSize(type) { switch (type) { case BaseTypes.Float32: { return Float32Array.BYTES_PER_ELEMENT; } case BaseTypes.Int32: { return Int32Array.BYTES_PER_ELEMENT; } case BaseTypes.Int16: { return Int16Array.BYTES_PER_ELEMENT; } case BaseTypes.Int8: { return Int8Array.BYTES_PER_ELEMENT; } case BaseTypes.UInt8: { return Uint8Array.BYTES_PER_ELEMENT; } // not one of the basic properties default: { if (type === undefined) { throw 'netScheme property declared without type attribute!'; } else if (this.customTypes[type] === null) { throw `netScheme property ${type} undefined! Did you forget to add it to the serializer?`; } else { return this.customTypes[type].BYTES_PER_ELEMENT; } } } } } export default Serializer; ```
/content/code_sandbox/src/serialize/Serializer.ts
xml
2016-06-10T12:58:57
2024-08-15T07:16:18
lance
lance-gg/lance
1,570
2,407
```xml import { vtkObject } from "../../../interfaces" ; /** * */ export interface IPriorityQueueInitialValues { elements?: Array<any>; } export interface vtkPriorityQueue extends vtkObject { /** * Push an element to the queue while defining a priority. * @param {Number} priority The priority of the element. * @param element */ push(priority: number, element: any): void; /** * */ pop(): any | null; /** * Delete an element from the queue by its ID. * @param {Number} id The id of the element. */ deleteById(id: number): void; /** * Get the length of the queue. */ length(): number; } /** * Method used to decorate a given object (publicAPI+model) with vtkPriorityQueue characteristics. * * @param publicAPI object on which methods will be bounds (public) * @param model object on which data structure will be bounds (protected) * @param {IPriorityQueueInitialValues} [initialValues] (default: {}) */ export function extend(publicAPI: object, model: object, initialValues?: IPriorityQueueInitialValues): void; /** * Method used to create a new instance of vtkPriorityQueue * @param {IPriorityQueueInitialValues} [initialValues] for pre-setting some of its content */ export function newInstance(initialValues?: IPriorityQueueInitialValues): vtkPriorityQueue; /** * vtkPriorityQueue is a general object for creating and manipulating lists of * object ids (e.g., point or cell ids). Object ids are sorted according to a * user-specified priority, where entries at the top of the queue have the * smallest values. */ export declare const vtkPriorityQueue: { newInstance: typeof newInstance; extend: typeof extend; } export default vtkPriorityQueue; ```
/content/code_sandbox/static/sim/Sources/Common/Core/PriorityQueue/index.d.ts
xml
2016-12-03T13:41:18
2024-08-15T12:50:03
engineercms
3xxx/engineercms
1,341
386
```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. --> <resources> <string name="app_name">rxandroidnetworking</string> </resources> ```
/content/code_sandbox/rx-android-networking/src/main/res/values/strings.xml
xml
2016-03-21T18:35:44
2024-08-15T11:55:03
Fast-Android-Networking
amitshekhariitbhu/Fast-Android-Networking
5,667
73
```xml import * as React from 'react'; import { INavPage, LoadingComponent } from '@fluentui/react-docsite-components/lib/index2'; export const GetStartedPages: INavPage = { title: 'Get started', url: '#/get-started', isUhfLink: true, hasPlatformPicker: true, component: () => <LoadingComponent title="Get started" />, getComponent: cb => require.ensure([], require => cb(require<any>('../../../pages/Overviews/GetStartedPage/GetStartedPage').GetStartedPage), ), platforms: { web: [ { title: 'Get started', url: '#/get-started/web', isHiddenFromMainNav: true, component: () => <LoadingComponent title="Get started" />, getComponent: cb => require.ensure([], require => cb(require<any>('../../../pages/Overviews/GetStartedPage/GetStartedPage').GetStartedPage), ), }, ], webcomponents: [ { title: 'Get started', url: '#/get-started/webcomponents', isHiddenFromMainNav: true, component: () => <LoadingComponent title="Get started" />, getComponent: cb => require.ensure([], require => cb(require<any>('../../../pages/Overviews/GetStartedPage/GetStartedPage').GetStartedPage), ), }, ], ios: [ { title: 'Get started', url: '#/get-started/ios', isHiddenFromMainNav: true, component: () => <LoadingComponent title="Get started" />, getComponent: cb => require.ensure([], require => cb(require<any>('../../../pages/Overviews/GetStartedPage/GetStartedPage').GetStartedPage), ), }, ], android: [ { title: 'Get started', url: '#/get-started/android', isHiddenFromMainNav: true, component: () => <LoadingComponent title="Get started" />, getComponent: cb => require.ensure([], require => cb(require<any>('../../../pages/Overviews/GetStartedPage/GetStartedPage').GetStartedPage), ), }, ], mac: [ { title: 'Get started', url: '#/get-started/mac', isHiddenFromMainNav: true, component: () => <LoadingComponent title="Get started" />, getComponent: cb => require.ensure([], require => cb(require<any>('../../../pages/Overviews/GetStartedPage/GetStartedPage').GetStartedPage), ), }, ], windows: [ { title: 'Get started', url: '#/get-started/windows', isHiddenFromMainNav: true, component: () => <LoadingComponent title="Get started" />, getComponent: cb => require.ensure([], require => cb(require<any>('../../../pages/Overviews/GetStartedPage/GetStartedPage').GetStartedPage), ), }, ], cross: [ { title: 'Get started', url: '#/get-started/cross', isHiddenFromMainNav: true, component: () => <LoadingComponent title="Get started" />, getComponent: cb => require.ensure([], require => cb(require<any>('../../../pages/Overviews/GetStartedPage/GetStartedPage').GetStartedPage), ), }, ], }, }; ```
/content/code_sandbox/apps/public-docsite/src/SiteDefinition/SiteDefinition.pages/GetStarted/GetStarted.pages.tsx
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
744
```xml import api from 'mastodon/api'; export async function logOut() { try { const response = await api(false).delete<{ redirect_to?: string }>( '/auth/sign_out', { headers: { Accept: 'application/json' }, withCredentials: true }, ); if (response.status === 200 && response.data.redirect_to) window.location.href = response.data.redirect_to; else console.error( 'Failed to log out, got an unexpected non-redirect response from the server', response, ); } catch (error) { console.error('Failed to log out, response was an error', error); } } ```
/content/code_sandbox/app/javascript/mastodon/utils/log_out.ts
xml
2016-02-22T15:01:25
2024-08-16T19:27:35
mastodon
mastodon/mastodon
46,560
140
```xml /* * @license Apache-2.0 * * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ // TypeScript Version: 4.1 /** * Interface describing `dnansumors`. */ interface Routine { /** * Computes the sum of double-precision floating-point strided array elements, ignoring `NaN` values and using ordinary recursive summation. * * @param N - number of indexed elements * @param x - input array * @param stride - stride length * @returns sum * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var x = new Float64Array( [ 1.0, -2.0, NaN, 2.0 ] ); * * var v = dnansumors( x.length, x, 1 ); * // returns 1.0 */ ( N: number, x: Float64Array, stride: number ): number; /** * Computes the sum of double-precision floating-point strided array elements, ignoring `NaN` values and using ordinary recursive summation and alternative indexing semantics. * * @param N - number of indexed elements * @param x - input array * @param stride - stride length * @param offset - starting index * @returns sum * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var x = new Float64Array( [ 1.0, -2.0, NaN, 2.0 ] ); * * var v = dnansumors.ndarray( x.length, x, 1, 0 ); * // returns 1.0 */ ndarray( N: number, x: Float64Array, stride: number, offset: number ): number; } /** * Computes the sum of double-precision floating-point strided array elements, ignoring `NaN` values and using ordinary recursive summation. * * @param N - number of indexed elements * @param x - input array * @param stride - stride length * @returns sum * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var x = new Float64Array( [ 1.0, -2.0, NaN, 2.0 ] ); * * var v = dnansumors( x.length, x, 1 ); * // returns 1.0 * * @example * var Float64Array = require( '@stdlib/array/float64' ); * * var x = new Float64Array( [ 1.0, -2.0, NaN, 2.0 ] ); * * var v = dnansumors.ndarray( x.length, x, 1, 0 ); * // returns 1.0 */ declare var dnansumors: Routine; // EXPORTS // export = dnansumors; ```
/content/code_sandbox/lib/node_modules/@stdlib/blas/ext/base/dnansumors/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
676
```xml <?xml version="1.0" encoding="utf-8"?> <!--EXPORTED BY TOOL, DON'T MODIFY IT!--> <!--Source File: node_test\reference_sub_0.xml--> <behavior name="node_test/reference_sub_0" agenttype="AgentNodeTest" version="5"> <pars> <par name="_$local_task_param_$_0" type="int" value="0" /> <par name="_$local_task_param_$_1" type="float" value="0" /> </pars> <node class="Task" id="7"> <property Prototype="Self.AgentNodeTest::task_test(0,0)" /> <property IsHTN="false" /> <node class="Sequence" id="0"> <node class="Assignment" id="1"> <property CastRight="false" /> <property Opl="int Self.AgentNodeTest::testVar_0" /> <property Opr="int Self.AgentNodeTest::_$local_task_param_$_0" /> </node> <node class="Assignment" id="2"> <property CastRight="false" /> <property Opl="float Self.AgentNodeTest::testVar_2" /> <property Opr="float Self.AgentNodeTest::_$local_task_param_$_1" /> </node> </node> </node> </behavior> ```
/content/code_sandbox/integration/unity/Assets/Resources/behaviac/exported/node_test/reference_sub_0.xml
xml
2016-11-21T05:08:08
2024-08-16T07:18:30
behaviac
Tencent/behaviac
2,831
295
```xml <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="font_huge">22dp</dimen> <dimen name="font_large">20dp</dimen> <dimen name="font_big">18dp</dimen> <dimen name="font_normal">16dp</dimen> <dimen name="font_small">14dp</dimen> <dimen name="font_mini">12dp</dimen> </resources> ```
/content/code_sandbox/lib/utildebug/src/main/res/values/dimens.xml
xml
2016-07-30T18:18:32
2024-08-16T01:37:59
AndroidUtilCode
Blankj/AndroidUtilCode
33,178
112
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration SYSTEM "classpath://org/hibernate/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">pankaj123</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property> <property name="hibernate.connection.username">pankaj</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <!-- For singleton factory --> <!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property> --> <!-- enable second level cache and query cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property> <mapping class="com.journaldev.hibernate.model.Employee" /> <mapping class="com.journaldev.hibernate.model.Address" /> </session-factory> </hibernate-configuration> ```
/content/code_sandbox/Hibernate/HibernateEHCacheExample/src/main/resources/hibernate.cfg.xml
xml
2016-05-02T05:43:21
2024-08-16T06:51:39
journaldev
WebJournal/journaldev
1,314
370
```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="path_to_url" xmlns:app="path_to_url" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.tabs.TabLayout android:id="@+id/pager_tab_strip" android:layout_width="match_parent" android:layout_height="wrap_content" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:tabMode="fixed" app:tabGravity="fill" /> <androidx.viewpager.widget.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> </LinearLayout> ```
/content/code_sandbox/app/src/main/res/layout/tweet_interactions_popup.xml
xml
2016-07-08T03:18:40
2024-08-14T02:54:51
talon-for-twitter-android
klinker24/talon-for-twitter-android
1,189
176
```xml <?xml version="1.0" encoding="UTF-8" ?> <!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. --> <!-- It contains information about your site's posts, pages, comments, categories, and other content. --> <!-- You may use this file to transfer that content from one site to another. --> <!-- This file is not intended to serve as a complete backup of your site. --> <!-- To import this information into a WordPress site follow these steps: --> <!-- 1. Log in to that site as an administrator. --> <!-- 2. Go to Tools: Import in the WordPress admin panel. --> <!-- 3. Install the "WordPress" importer from the list. --> <!-- 4. Activate & Run Importer. --> <!-- 5. Upload this file using the form provided on that page. --> <!-- 6. You will first be asked to map the authors in this export file to users --> <!-- on the site. For each author, you may choose to map to an --> <!-- existing user on the site or to create a new user. --> <!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. --> <!-- contained in this file into your site. --> <!-- generator="WordPress/3.1-RC2-17315" created="2011-01-18 08:06" --> <rss version="2.0" xmlns:excerpt="path_to_url" xmlns:content="path_to_url" xmlns:wfw="path_to_url" xmlns:dc="path_to_url" xmlns:wp="path_to_url" > <channel> <title>trunk</title> <link>path_to_url <description>trunk</description> <pubDate>Tue, 18 Jan 2011 08:06:21 +0000</pubDate> <language>en</language> <wp:wxr_version>1.1</wp:wxr_version> <wp:base_site_url>path_to_url <wp:base_blog_url>path_to_url <wp:author><wp:author_id>1</wp:author_id><wp:author_login>admin</wp:author_login><wp:author_email>local@host.null</wp:author_email><wp:author_display_name><![CDATA[admin]]></wp:author_display_name><wp:author_first_name><![CDATA[]]></wp:author_first_name><wp:author_last_name><![CDATA[]]></wp:author_last_name></wp:author> <wp:category><wp:term_id>8</wp:term_id><wp:category_nicename>alpha</wp:category_nicename><wp:category_parent></wp:category_parent><wp:cat_name><![CDATA[a \"great\" category]]></wp:cat_name></wp:category> <wp:tag><wp:term_id>33</wp:term_id><wp:tag_slug>tag1</wp:tag_slug><wp:tag_name><![CDATA[foo\'bar]]></wp:tag_name></wp:tag> <generator>path_to_url <item> <title>Hello world!</title> <link>path_to_url <pubDate>Tue, 18 Jan 2011 07:40:14 +0000</pubDate> <dc:creator>author</dc:creator> <guid isPermaLink="false">path_to_url <description></description> <content:encoded><![CDATA[Slashes aren\'t \"cool\"]]></content:encoded> <excerpt:encoded><![CDATA[]]></excerpt:encoded> <wp:post_id>1</wp:post_id> <wp:post_date>2011-01-18 07:40:14</wp:post_date> <wp:post_date_gmt>2011-01-18 07:40:14</wp:post_date_gmt> <wp:comment_status>open</wp:comment_status> <wp:ping_status>open</wp:ping_status> <wp:post_name>hello-world</wp:post_name> <wp:status>publish</wp:status> <wp:post_parent>0</wp:post_parent> <wp:menu_order>0</wp:menu_order> <wp:post_type>post</wp:post_type> <wp:post_password></wp:post_password> <wp:is_sticky>0</wp:is_sticky> <category domain="category" nicename="alpha"><![CDATA[a \"great\" category]]></category> <wp:postmeta> <wp:meta_key>Post by</wp:meta_key> <wp:meta_value><![CDATA[admin]]></wp:meta_value> </wp:postmeta> <wp:postmeta> <wp:meta_key>_edit_last</wp:meta_key> <wp:meta_value><![CDATA[1]]></wp:meta_value> </wp:postmeta> </item> </channel> </rss> ```
/content/code_sandbox/tests/phpunit/data/export/slashes.xml
xml
2016-12-05T16:41:44
2024-08-16T18:32:24
wordpress-develop
WordPress/wordpress-develop
2,423
1,127
```xml <vector xmlns:android="path_to_url" android:height="34.0dp" android:tint="?attr/colorControlNormal" android:viewportHeight="15" android:viewportWidth="15" android:width="34.0dp"> <path android:fillColor="@android:color/white" android:pathData="M7 3C7 3 7 6 7 6C7 6.5 6 6.5 6 6C6 6 2.5 6 2.5 6C1.5 6 1 5.5 1 4.5C1 4.5 1 1 1 1C0.5 1 0.5 0 1 0C1.5 0 4 0 4 0C4.5 0 4.5 1 4 1C4 1 4 2.5 4 2.5C4 2.5 4 3 4.5 3C4.5 3 6 3 6 3C6 2.5 7 2.5 7 3zM14 10C14.5 10 14.5 9 14 9C14 9 14 4.5 14 4.5C14 3.5 13.5 3 12.5 3C12.5 3 9 3 9 3C9 2.5 8 2.5 8 3C8 3 8 6 8 6C8 6.5 9 6.5 9 6C9 6 10.5 6 10.5 6C11 6 11 6.5 11 6.5C11 6.5 11 9 11 9C10.5 9 10.5 10 11 10C11 10 14 10 14 10z"/> <path android:fillColor="@android:color/white" android:pathData="M12.5 10.5C12.75 10.5 14.25 12.25 14.25 13.5C14.25 14.5 13.25 15 12.5 15C11.75 15 10.75 14.5 10.75 13.5C10.75 12.25 12.25 10.5 12.5 10.5zM11.15 13.5C11.15 14.1 11.75 14.7 12.5 14.7C11.75 14.4 11.45 14.1 11.15 13.5z"/> </vector> ```
/content/code_sandbox/app/src/main/res/drawable/ic_preset_temaki_plumber.xml
xml
2016-07-02T10:44:04
2024-08-16T18:55:54
StreetComplete
streetcomplete/StreetComplete
3,781
622
```xml import * as React from 'react' import { Dialog, DialogContent, DialogFooter } from '../dialog' import { OkCancelButtonGroup } from '../dialog/ok-cancel-button-group' import { Dispatcher } from '../dispatcher' import { TrashNameLabel } from '../lib/context-menu' import { RetryAction } from '../../models/retry-actions' import { Checkbox, CheckboxValue } from '../lib/checkbox' interface IDiscardChangesRetryDialogProps { readonly dispatcher: Dispatcher readonly retryAction: RetryAction readonly onDismissed: () => void readonly onConfirmDiscardChangesChanged: (optOut: boolean) => void } interface IDiscardChangesRetryDialogState { readonly retrying: boolean readonly confirmDiscardChanges: boolean } export class DiscardChangesRetryDialog extends React.Component< IDiscardChangesRetryDialogProps, IDiscardChangesRetryDialogState > { public constructor(props: IDiscardChangesRetryDialogProps) { super(props) this.state = { retrying: false, confirmDiscardChanges: true } } public render() { const { retrying } = this.state return ( <Dialog title="Error" id="discard-changes-retry" loading={retrying} disabled={retrying} onDismissed={this.props.onDismissed} onSubmit={this.onSubmit} type="error" > <DialogContent> <p>Failed to discard changes to {TrashNameLabel}.</p> <div> Common reasons are: <ul> <li> The {TrashNameLabel} is configured to delete items immediately. </li> <li>Restricted access to move the file(s).</li> </ul> </div> <p>These changes will be unrecoverable from the {TrashNameLabel}.</p> {this.renderConfirmDiscardChanges()} </DialogContent> {this.renderFooter()} </Dialog> ) } private renderConfirmDiscardChanges() { return ( <Checkbox label="Do not show this message again" value={ this.state.confirmDiscardChanges ? CheckboxValue.Off : CheckboxValue.On } onChange={this.onConfirmDiscardChangesChanged} /> ) } private renderFooter() { return ( <DialogFooter> <OkCancelButtonGroup okButtonText={ __DARWIN__ ? 'Permanently Discard Changes' : 'Permanently discard changes' } okButtonTitle={`This will discard changes and they will be unrecoverable.`} cancelButtonText="Cancel" destructive={true} /> </DialogFooter> ) } private onConfirmDiscardChangesChanged = ( event: React.FormEvent<HTMLInputElement> ) => { const value = !event.currentTarget.checked this.setState({ confirmDiscardChanges: value }) } private onSubmit = async () => { const { dispatcher, retryAction } = this.props this.setState({ retrying: true }) await dispatcher.performRetry(retryAction) this.props.onConfirmDiscardChangesChanged(this.state.confirmDiscardChanges) this.props.onDismissed() } } ```
/content/code_sandbox/app/src/ui/discard-changes/discard-changes-retry-dialog.tsx
xml
2016-05-11T15:59:00
2024-08-16T17:00:41
desktop
desktop/desktop
19,544
690
```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. */ --> <org.pocketworkstation.pckeyboard.LatinKeyboardView xmlns:android="path_to_url" xmlns:latin="path_to_url" android:id="@android:id/keyboardView" android:layout_alignParentBottom="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#c0000000" android:verticalCorrection="0dip" latin:keyBackground="@drawable/btn_keyboard_key_ics" latin:keyTextColor="#FFFFFFFF" latin:keyHintColor="#FFAAAAAA" latin:keyCursorColor="#FFFFFFFF" latin:shadowColor="#FF33B5E5" latin:shadowRadius="9" latin:keyTextStyle="bold" latin:recolorSymbols="true" latin:backgroundAlpha="32" /> ```
/content/code_sandbox/app/src/main/res/layout/input_trans_neon.xml
xml
2016-01-22T21:40:54
2024-08-16T11:54:30
hackerskeyboard
klausw/hackerskeyboard
1,807
235
```xml import { isAsyncThunkAction, isPending as isThunkActionPending, isFulfilled as isThunkActionFulfilled, isRejected as isThunkActionRejected, isAction, } from '@reduxjs/toolkit'; import type { Middleware, UnknownAction } from '@reduxjs/toolkit'; import { showLoading, hideLoading } from 'react-redux-loading-bar'; import type { RootState } from '..'; interface Config { promiseTypeSuffixes?: string[]; } const defaultTypeSuffixes: Config['promiseTypeSuffixes'] = [ 'PENDING', 'FULFILLED', 'REJECTED', ]; interface ActionWithSkipLoading extends UnknownAction { skipLoading: boolean; } function isActionWithSkipLoading( action: unknown, ): action is ActionWithSkipLoading { return ( isAction(action) && 'skipLoading' in action && typeof action.skipLoading === 'boolean' ); } export const loadingBarMiddleware = ( config: Config = {}, ): Middleware<{ skipLoading?: boolean }, RootState> => { const promiseTypeSuffixes = config.promiseTypeSuffixes ?? defaultTypeSuffixes; return ({ dispatch }) => (next) => (action) => { let isPending = false; let isFulfilled = false; let isRejected = false; if ( isAsyncThunkAction(action) // TODO: once we get the first use-case for it, add a check for skipLoading ) { if (isThunkActionPending(action)) isPending = true; else if (isThunkActionFulfilled(action)) isFulfilled = true; else if (isThunkActionRejected(action)) isRejected = true; } else if ( isActionWithSkipLoading(action) && !action.skipLoading && typeof action.type === 'string' ) { const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes; const isPendingRegexp = new RegExp(`${PENDING}$`, 'g'); const isFulfilledRegexp = new RegExp(`${FULFILLED}$`, 'g'); const isRejectedRegexp = new RegExp(`${REJECTED}$`, 'g'); if (action.type.match(isPendingRegexp)) { isPending = true; } else if (action.type.match(isFulfilledRegexp)) { isFulfilled = true; } else if (action.type.match(isRejectedRegexp)) { isRejected = true; } } if (isPending) { dispatch(showLoading()); } else if (isFulfilled || isRejected) { dispatch(hideLoading()); } return next(action); }; }; ```
/content/code_sandbox/app/javascript/mastodon/store/middlewares/loading_bar.ts
xml
2016-02-22T15:01:25
2024-08-16T19:27:35
mastodon
mastodon/mastodon
46,560
568
```xml import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core'; import { Code } from '@domain/code'; import { Customer } from '@domain/customer'; import { CustomerService } from '@service/customerservice'; @Component({ selector: 'vertical-scroll-doc', template: ` <app-docsectiontext> <p>Adding <i>scrollable</i> property along with a <i>scrollHeight</i> for the data viewport enables vertical scrolling with fixed headers.</p></app-docsectiontext > <p-deferred-demo (load)="loadDemoData()"> <div class="card"> <p-table [value]="customers" [scrollable]="true" scrollHeight="400px" [tableStyle]="{ 'min-width': '50rem' }"> <ng-template pTemplate="header"> <tr> <th>Name</th> <th>Country</th> <th>Company</th> <th>Representative</th> </tr> </ng-template> <ng-template pTemplate="body" let-customer let-index="index"> <tr> <td>{{ customer.name }}</td> <td>{{ customer.country.name }}</td> <td>{{ customer.company }}</td> <td>{{ customer.representative.name }}</td> </tr> </ng-template> </p-table> </div> </p-deferred-demo> <app-code [code]="code" selector="table-vertical-scroll-demo" [extFiles]="extFiles"></app-code>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class VerticalScrollDoc { customers!: Customer[]; constructor(private customerService: CustomerService, private cd: ChangeDetectorRef) {} loadDemoData() { this.customerService.getCustomersMedium().then((data) => { this.customers = data; this.cd.markForCheck(); }); } code: Code = { basic: `<p-table [value]="customers" [scrollable]="true" scrollHeight="400px" [tableStyle]="{'min-width': '50rem'}"> <ng-template pTemplate="header"> <tr> <th>Name</th> <th>Country</th> <th>Company</th> <th>Representative</th> </tr> </ng-template> <ng-template pTemplate="body" let-customer> <tr> <td>{{customer.name}}</td> <td>{{customer.country.name}}</td> <td>{{customer.company}}</td> <td>{{customer.representative.name}}</td> </tr> </ng-template> </p-table>`, html: `<div class="card"> <p-table [value]="customers" [scrollable]="true" scrollHeight="400px" [tableStyle]="{'min-width': '50rem'}"> <ng-template pTemplate="header"> <tr> <th>Name</th> <th>Country</th> <th>Company</th> <th>Representative</th> </tr> </ng-template> <ng-template pTemplate="body" let-customer> <tr> <td>{{customer.name}}</td> <td>{{customer.country.name}}</td> <td>{{customer.company}}</td> <td>{{customer.representative.name}}</td> </tr> </ng-template> </p-table> </div>`, typescript: `import { Component, OnInit } from '@angular/core'; import { Customer } from '@domain/customer'; import { CustomerService } from '@service/customerservice'; import { TableModule } from 'primeng/table'; import { HttpClientModule } from '@angular/common/http'; @Component({ selector: 'table-vertical-scroll-demo', templateUrl: 'table-vertical-scroll-demo.html', standalone: true, imports: [TableModule, HttpClientModule], providers: [CustomerService] }) export class TableVerticalScrollDemo implements OnInit{ customers!: Customer[]; constructor(private customerService: CustomerService) {} ngOnInit() { this.customerService.getCustomersMedium().then((data) => { this.customers = data; }); } }`, data: `{ id: 1000, name: 'James Butt', country: { name: 'Algeria', code: 'dz' }, company: 'Benton, John B Jr', date: '2015-09-13', status: 'unqualified', verified: true, activity: 17, representative: { name: 'Ioni Bowcher', image: 'ionibowcher.png' }, balance: 70663 }, ...`, service: ['CustomerService'] }; extFiles = [ { path: 'src/domain/customer.ts', content: ` export interface Country { name?: string; code?: string; } export interface Representative { name?: string; image?: string; } export interface Customer { id?: number; name?: string; country?: Country; company?: string; date?: string | Date; status?: string; activity?: number; representative?: Representative; verified?: boolean; balance?: number; }` } ]; } ```
/content/code_sandbox/src/app/showcase/doc/table/verticalscrolldoc.ts
xml
2016-01-16T09:23:28
2024-08-16T19:58:20
primeng
primefaces/primeng
9,969
1,162
```xml <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="path_to_url"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{ACB2F35D-BFDA-41B1-9B79-B82BF23F6769}</ProjectGuid> <ProjectTypeGuids>{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <OutputType>Library</OutputType> <RootNamespace>zxing.monotouch</RootNamespace> <IPhoneResourcePrefix>Resources</IPhoneResourcePrefix> <AssemblyName>zxing.monotouch</AssemblyName> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>True</DebugSymbols> <DebugType>full</DebugType> <Optimize>False</Optimize> <OutputPath>..\..\Build\ios\unified\Debug\</OutputPath> <DefineConstants>DEBUG;MONOTOUCH</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <ConsolePause>False</ConsolePause> <IntermediateOutputPath>obj\unified\$(Platform)\$(Configuration)\</IntermediateOutputPath> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>none</DebugType> <Optimize>True</Optimize> <OutputPath>..\..\Build\ios\unified\Release\</OutputPath> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <ConsolePause>False</ConsolePause> <DefineConstants>MONOTOUCH</DefineConstants> <IntermediateOutputPath>obj\unified\$(Platform)\$(Configuration)\</IntermediateOutputPath> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Xml" /> <Reference Include="System.Core" /> <Reference Include="Xamarin.iOS" /> <Reference Include="System.Numerics" /> </ItemGroup> <Import Project="$(MSBuildExtensionsPath)\Xamarin\iOS\Xamarin.iOS.CSharp.targets" /> <ItemGroup> <Compile Include="BarcodeFormat.cs" /> <Compile Include="BarcodeReader.UIImage.cs" /> <Compile Include="BarcodeReaderCustom.cs" /> <Compile Include="BarcodeReaderGeneric.cs" /> <Compile Include="BarcodeWriter.PixelData.cs" /> <Compile Include="BarcodeWriter.SvgImage.cs" /> <Compile Include="BarcodeWriter.UIImage.cs" /> <Compile Include="BarcodeWriterCustom.cs" /> <Compile Include="BarcodeWriterGeneric.cs" /> <Compile Include="BaseLuminanceSource.cs" /> <Compile Include="Binarizer.cs" /> <Compile Include="BinaryBitmap.cs" /> <Compile Include="DecodeHintType.cs" /> <Compile Include="Dimension.cs" /> <Compile Include="EncodeHintType.cs" /> <Compile Include="FormatException.cs" /> <Compile Include="IBarcodeReader.UIImage.cs" /> <Compile Include="IBarcodeReader.cs" /> <Compile Include="IBarcodeReader.Multiple.UIImage.cs" /> <Compile Include="IBarcodeReader.Multiple.cs" /> <Compile Include="IBarcodeReaderCustom.cs" /> <Compile Include="IBarcodeReaderCustom.Multiple.cs" /> <Compile Include="IBarcodeReaderGeneric.cs" /> <Compile Include="IBarcodeReaderGeneric.Multiple.cs" /> <Compile Include="IBarcodeWriter.cs" /> <Compile Include="IBarcodeWriter.PixelData.cs" /> <Compile Include="IBarcodeWriter.SvgImage.cs" /> <Compile Include="IBarcodeWriter.UIImage.cs" /> <Compile Include="IBarcodeWriterCustom.cs" /> <Compile Include="IBarcodeWriterGeneric.cs" /> <Compile Include="imb\IMBReader.cs" /> <Compile Include="InvertedLuminanceSource.cs" /> <Compile Include="LuminanceSource.cs" /> <Compile Include="MultiFormatReader.cs" /> <Compile Include="MultiFormatWriter.cs" /> <Compile Include="PlanarYUVLuminanceSource.cs" /> <Compile Include="Reader.cs" /> <Compile Include="ReaderException.cs" /> <Compile Include="Result.cs" /> <Compile Include="ResultMetadataType.cs" /> <Compile Include="ResultPoint.cs" /> <Compile Include="ResultPointCallback.cs" /> <Compile Include="RGBLuminanceSource.cs" /> <Compile Include="SupportClass.cs" /> <Compile Include="Writer.cs" /> <Compile Include="WriterException.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="aztec\AztecDetectorResult.cs" /> <Compile Include="aztec\AztecReader.cs" /> <Compile Include="aztec\AztecResultMetadata.cs" /> <Compile Include="aztec\AztecWriter.cs" /> <Compile Include="aztec\decoder\Decoder.cs" /> <Compile Include="aztec\detector\Detector.cs" /> <Compile Include="aztec\encoder\AztecCode.cs" /> <Compile Include="aztec\encoder\AztecEncodingOptions.cs" /> <Compile Include="aztec\encoder\BinaryShiftToken.cs" /> <Compile Include="aztec\encoder\Encoder.cs" /> <Compile Include="aztec\encoder\HighLevelEncoder.cs" /> <Compile Include="aztec\encoder\SimpleToken.cs" /> <Compile Include="aztec\encoder\State.cs" /> <Compile Include="aztec\encoder\Token.cs" /> <Compile Include="client\result\AbstractDoCoMoResultParser.cs" /> <Compile Include="client\result\AddressBookAUResultParser.cs" /> <Compile Include="client\result\AddressBookDoCoMoResultParser.cs" /> <Compile Include="client\result\AddressBookParsedResult.cs" /> <Compile Include="client\result\BizcardResultParser.cs" /> <Compile Include="client\result\BookmarkDoCoMoResultParser.cs" /> <Compile Include="client\result\CalendarParsedResult.cs" /> <Compile Include="client\result\EmailAddressParsedResult.cs" /> <Compile Include="client\result\EmailAddressResultParser.cs" /> <Compile Include="client\result\EmailDoCoMoResultParser.cs" /> <Compile Include="client\result\ExpandedProductParsedResult.cs" /> <Compile Include="client\result\ExpandedProductResultParser.cs" /> <Compile Include="client\result\GeoParsedResult.cs" /> <Compile Include="client\result\GeoResultParser.cs" /> <Compile Include="client\result\ISBNParsedResult.cs" /> <Compile Include="client\result\ISBNResultParser.cs" /> <Compile Include="client\result\ParsedResult.cs" /> <Compile Include="client\result\ParsedResultType.cs" /> <Compile Include="client\result\ProductParsedResult.cs" /> <Compile Include="client\result\ProductResultParser.cs" /> <Compile Include="client\result\ResultParser.cs" /> <Compile Include="client\result\SMSMMSResultParser.cs" /> <Compile Include="client\result\SMSParsedResult.cs" /> <Compile Include="client\result\SMSTOMMSTOResultParser.cs" /> <Compile Include="client\result\SMTPResultParser.cs" /> <Compile Include="client\result\TelParsedResult.cs" /> <Compile Include="client\result\TelResultParser.cs" /> <Compile Include="client\result\TextParsedResult.cs" /> <Compile Include="client\result\URIParsedResult.cs" /> <Compile Include="client\result\URIResultParser.cs" /> <Compile Include="client\result\URLTOResultParser.cs" /> <Compile Include="client\result\VCardResultParser.cs" /> <Compile Include="client\result\VEventResultParser.cs" /> <Compile Include="client\result\VINParsedResult.cs" /> <Compile Include="client\result\VINResultParser.cs" /> <Compile Include="client\result\WifiParsedResult.cs" /> <Compile Include="client\result\WifiResultParser.cs" /> <Compile Include="common\BitArray.cs" /> <Compile Include="common\BitMatrix.cs" /> <Compile Include="common\BitSource.cs" /> <Compile Include="common\CharacterSetECI.cs" /> <Compile Include="common\DecoderResult.cs" /> <Compile Include="common\DecodingOptions.cs" /> <Compile Include="common\DefaultGridSampler.cs" /> <Compile Include="common\DetectorResult.cs" /> <Compile Include="common\ECI.cs" /> <Compile Include="common\EncodingOptions.cs" /> <Compile Include="common\GlobalHistogramBinarizer.cs" /> <Compile Include="common\GridSampler.cs" /> <Compile Include="common\HybridBinarizer.cs" /> <Compile Include="common\PerspectiveTransform.cs" /> <Compile Include="common\StringUtils.cs" /> <Compile Include="common\BigInteger\Base10BigInteger.cs" /> <Compile Include="common\BigInteger\BigInteger.cs" /> <Compile Include="common\BigInteger\BigIntegerException.cs" /> <Compile Include="common\BigInteger\Sign.cs" /> <Compile Include="common\detector\MathUtils.cs" /> <Compile Include="common\detector\MonochromeRectangleDetector.cs" /> <Compile Include="common\detector\WhiteRectangleDetector.cs" /> <Compile Include="common\reedsolomon\GenericGF.cs" /> <Compile Include="common\reedsolomon\GenericGFPoly.cs" /> <Compile Include="common\reedsolomon\ReedSolomonDecoder.cs" /> <Compile Include="common\reedsolomon\ReedSolomonEncoder.cs" /> <Compile Include="datamatrix\DataMatrixReader.cs" /> <Compile Include="datamatrix\DataMatrixWriter.cs" /> <Compile Include="datamatrix\decoder\BitMatrixParser.cs" /> <Compile Include="datamatrix\decoder\DataBlock.cs" /> <Compile Include="datamatrix\decoder\DecodedBitStreamParser.cs" /> <Compile Include="datamatrix\decoder\Decoder.cs" /> <Compile Include="datamatrix\decoder\Version.cs" /> <Compile Include="datamatrix\detector\Detector.cs" /> <Compile Include="datamatrix\encoder\ASCIIEncoder.cs" /> <Compile Include="datamatrix\encoder\Base256Encoder.cs" /> <Compile Include="datamatrix\encoder\C40Encoder.cs" /> <Compile Include="datamatrix\encoder\DatamatrixEncodingOptions.cs" /> <Compile Include="datamatrix\encoder\DataMatrixSymbolInfo144.cs" /> <Compile Include="datamatrix\encoder\DefaultPlacement.cs" /> <Compile Include="datamatrix\encoder\EdifactEncoder.cs" /> <Compile Include="datamatrix\encoder\Encodation.cs" /> <Compile Include="datamatrix\encoder\Encoder.cs" /> <Compile Include="datamatrix\encoder\EncoderContext.cs" /> <Compile Include="datamatrix\encoder\ErrorCorrection.cs" /> <Compile Include="datamatrix\encoder\HighLevelEncoder.cs" /> <Compile Include="datamatrix\encoder\SymbolInfo.cs" /> <Compile Include="datamatrix\encoder\SymbolShapeHint.cs" /> <Compile Include="datamatrix\encoder\TextEncoder.cs" /> <Compile Include="datamatrix\encoder\X12Encoder.cs" /> <Compile Include="maxicode\MaxiCodeReader.cs" /> <Compile Include="maxicode\decoder\BitMatrixParser.cs" /> <Compile Include="maxicode\decoder\DecodedBitStreamParser.cs" /> <Compile Include="maxicode\decoder\Decoder.cs" /> <Compile Include="multi\ByQuadrantReader.cs" /> <Compile Include="multi\GenericMultipleBarcodeReader.cs" /> <Compile Include="multi\MultipleBarcodeReader.cs" /> <Compile Include="multi\qrcode\QRCodeMultiReader.cs" /> <Compile Include="multi\qrcode\detector\MultiDetector.cs" /> <Compile Include="multi\qrcode\detector\MultiFinderPatternFinder.cs" /> <Compile Include="net2.0\TimeZoneInfo.cs" /> <Compile Include="oned\CodaBarReader.cs" /> <Compile Include="oned\CodaBarWriter.cs" /> <Compile Include="oned\Code128EncodingOptions.cs" /> <Compile Include="oned\Code128Reader.cs" /> <Compile Include="oned\Code128Writer.cs" /> <Compile Include="oned\Code39Reader.cs" /> <Compile Include="oned\Code39Writer.cs" /> <Compile Include="oned\Code93Reader.cs" /> <Compile Include="oned\Code93Writer.cs" /> <Compile Include="oned\EAN13Reader.cs" /> <Compile Include="oned\EAN13Writer.cs" /> <Compile Include="oned\EAN8Reader.cs" /> <Compile Include="oned\EAN8Writer.cs" /> <Compile Include="oned\EANManufacturerOrgSupport.cs" /> <Compile Include="oned\ITFReader.cs" /> <Compile Include="oned\ITFWriter.cs" /> <Compile Include="oned\MSIReader.cs" /> <Compile Include="oned\MSIWriter.cs" /> <Compile Include="oned\PlesseyWriter.cs" /> <Compile Include="oned\MultiFormatOneDReader.cs" /> <Compile Include="oned\MultiFormatUPCEANReader.cs" /> <Compile Include="oned\OneDReader.cs" /> <Compile Include="oned\OneDimensionalCodeWriter.cs" /> <Compile Include="oned\UPCAReader.cs" /> <Compile Include="oned\UPCAWriter.cs" /> <Compile Include="oned\UPCEANExtension2Support.cs" /> <Compile Include="oned\UPCEANExtension5Support.cs" /> <Compile Include="oned\UPCEANExtensionSupport.cs" /> <Compile Include="oned\UPCEANReader.cs" /> <Compile Include="oned\UPCEANWriter.cs" /> <Compile Include="oned\UPCEReader.cs" /> <Compile Include="oned\UPCEWriter.cs" /> <Compile Include="oned\rss\AbstractRSSReader.cs" /> <Compile Include="oned\rss\DataCharacter.cs" /> <Compile Include="oned\rss\FinderPattern.cs" /> <Compile Include="oned\rss\Pair.cs" /> <Compile Include="oned\rss\RSS14Reader.cs" /> <Compile Include="oned\rss\RSSUtils.cs" /> <Compile Include="oned\rss\expanded\BitArrayBuilder.cs" /> <Compile Include="oned\rss\expanded\ExpandedPair.cs" /> <Compile Include="oned\rss\expanded\ExpandedRow.cs" /> <Compile Include="oned\rss\expanded\RSSExpandedReader.cs" /> <Compile Include="oned\rss\expanded\decoders\AI013103decoder.cs" /> <Compile Include="oned\rss\expanded\decoders\AI01320xDecoder.cs" /> <Compile Include="oned\rss\expanded\decoders\AI01392xDecoder.cs" /> <Compile Include="oned\rss\expanded\decoders\AI01393xDecoder.cs" /> <Compile Include="oned\rss\expanded\decoders\AI013x0x1xDecoder.cs" /> <Compile Include="oned\rss\expanded\decoders\AI013x0xDecoder.cs" /> <Compile Include="oned\rss\expanded\decoders\AI01AndOtherAIs.cs" /> <Compile Include="oned\rss\expanded\decoders\AI01decoder.cs" /> <Compile Include="oned\rss\expanded\decoders\AI01weightDecoder.cs" /> <Compile Include="oned\rss\expanded\decoders\AbstractExpandedDecoder.cs" /> <Compile Include="oned\rss\expanded\decoders\AnyAIDecoder.cs" /> <Compile Include="oned\rss\expanded\decoders\BlockParsedResult.cs" /> <Compile Include="oned\rss\expanded\decoders\CurrentParsingState.cs" /> <Compile Include="oned\rss\expanded\decoders\DecodedChar.cs" /> <Compile Include="oned\rss\expanded\decoders\DecodedInformation.cs" /> <Compile Include="oned\rss\expanded\decoders\DecodedNumeric.cs" /> <Compile Include="oned\rss\expanded\decoders\DecodedObject.cs" /> <Compile Include="oned\rss\expanded\decoders\FieldParser.cs" /> <Compile Include="oned\rss\expanded\decoders\GeneralAppIdDecoder.cs" /> <Compile Include="pdf417\decoder\BarcodeMetadata.cs" /> <Compile Include="pdf417\decoder\BarcodeValue.cs" /> <Compile Include="pdf417\decoder\BoundingBox.cs" /> <Compile Include="pdf417\decoder\Codeword.cs" /> <Compile Include="pdf417\decoder\DecodedBitStreamParser.cs" /> <Compile Include="pdf417\decoder\DetectionResult.cs" /> <Compile Include="pdf417\decoder\DetectionResultColumn.cs" /> <Compile Include="pdf417\decoder\DetectionResultRowIndicatorColumn.cs" /> <Compile Include="pdf417\decoder\ec\ErrorCorrection.cs" /> <Compile Include="pdf417\decoder\ec\ModulusGF.cs" /> <Compile Include="pdf417\decoder\ec\ModulusPoly.cs" /> <Compile Include="pdf417\decoder\PDF417CodewordDecoder.cs" /> <Compile Include="pdf417\decoder\PDF417ScanningDecoder.cs" /> <Compile Include="pdf417\detector\Detector.cs" /> <Compile Include="pdf417\detector\PDF417DetectorResult.cs" /> <Compile Include="pdf417\encoder\PDF417AspectRatio.cs" /> <Compile Include="pdf417\encoder\BarcodeMatrix.cs" /> <Compile Include="pdf417\encoder\BarcodeRow.cs" /> <Compile Include="pdf417\encoder\Compaction.cs" /> <Compile Include="pdf417\encoder\Dimensions.cs" /> <Compile Include="pdf417\encoder\PDF417.cs" /> <Compile Include="pdf417\encoder\PDF417EncodingOptions.cs" /> <Compile Include="pdf417\encoder\PDF417ErrorCorrection.cs" /> <Compile Include="pdf417\encoder\PDF417HighLevelEncoder.cs" /> <Compile Include="pdf417\encoder\PDF417OptionalMacroFields.cs" /> <Compile Include="pdf417\PDF417Common.cs" /> <Compile Include="pdf417\PDF417MacroMetadata.cs" /> <Compile Include="pdf417\PDF417Reader.cs" /> <Compile Include="pdf417\PDF417ResultMetadata.cs" /> <Compile Include="pdf417\PDF417Writer.cs" /> <Compile Include="qrcode\QRCodeReader.cs" /> <Compile Include="qrcode\QRCodeWriter.cs" /> <Compile Include="qrcode\decoder\BitMatrixParser.cs" /> <Compile Include="qrcode\decoder\DataBlock.cs" /> <Compile Include="qrcode\decoder\DataMask.cs" /> <Compile Include="qrcode\decoder\DecodedBitStreamParser.cs" /> <Compile Include="qrcode\decoder\Decoder.cs" /> <Compile Include="qrcode\decoder\ErrorCorrectionLevel.cs" /> <Compile Include="qrcode\decoder\FormatInformation.cs" /> <Compile Include="qrcode\decoder\Mode.cs" /> <Compile Include="qrcode\decoder\QRCodeDecoderMetaData.cs" /> <Compile Include="qrcode\decoder\Version.cs" /> <Compile Include="qrcode\detector\AlignmentPattern.cs" /> <Compile Include="qrcode\detector\AlignmentPatternFinder.cs" /> <Compile Include="qrcode\detector\Detector.cs" /> <Compile Include="qrcode\detector\FinderPattern.cs" /> <Compile Include="qrcode\detector\FinderPatternFinder.cs" /> <Compile Include="qrcode\detector\FinderPatternInfo.cs" /> <Compile Include="qrcode\encoder\BlockPair.cs" /> <Compile Include="qrcode\encoder\ByteMatrix.cs" /> <Compile Include="qrcode\encoder\Encoder.cs" /> <Compile Include="qrcode\encoder\MaskUtil.cs" /> <Compile Include="qrcode\encoder\MatrixUtil.cs" /> <Compile Include="qrcode\encoder\QRCode.cs" /> <Compile Include="qrcode\encoder\QrCodeEncodingOptions.cs" /> <Compile Include="renderer\IBarcodeRenderer.cs" /> <Compile Include="renderer\PixelData.cs" /> <Compile Include="renderer\PixelDataRenderer.cs" /> <Compile Include="renderer\SVGRenderer.cs" /> <Compile Include="xamarin\Color.cs" /> <Compile Include="xamarin\ColorConverter.cs" /> <Compile Include="xamarin\ColorTranslator.cs" /> <Compile Include="xamarin\KnownColor.cs" /> <Compile Include="xamarin\KnownColors.cs" /> <Compile Include="xamarin\RGBLuminanceSource.monotouch.cs" /> <Compile Include="xamarin\SystemColors.cs" /> <Compile Include="xamarin\BitmapRenderer.monotouch.cs" /> </ItemGroup> </Project> ```
/content/code_sandbox/Source/lib/zxing.ios.csproj
xml
2016-10-27T20:15:17
2024-08-16T02:15:03
ZXing.Net
micjahn/ZXing.Net
2,676
4,867
```xml export default function (size: number): string { const i: number = Math.floor(Math.log(size) / Math.log(1024)); return (size / Math.pow(1024, i)).toFixed(2) + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i]; } ```
/content/code_sandbox/frontend/functions/formatFileSize.ts
xml
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
69
```xml import { jsx, Line } from '../../../src'; import Geometry from '../../../src/components/geometry'; import { createContext, delay, gestureSimulator } from '../../util'; import { Canvas, Chart, Interval, Axis } from '../../../src'; const context = createContext(); const data = [{ genre: 'Sports', sold: 275, type: 'a' }]; const data1 = [ { genre: 'Sports', sold: 275, type: 'a' }, { genre: 'Strategy', sold: 115, type: 'a' }, ]; class GeometryTest extends Geometry { render() { const records = this.mapping(); return ( <group> {records.map((record) => { const { children } = record; return children.map((item) => { const { x, y } = item; return ( <circle attrs={{ // @ts-ignore cx: x, cy: y, r: '20px', fill: '#000', }} /> ); }); })} </group> ); } } describe('geometry', () => { let canvas; const chartRef = { current: null }; const componentRef = { current: null }; it('geometry render', async () => { const { props } = ( <Canvas context={context} pixelRatio={1}> <Chart ref={chartRef} data={data}> <GeometryTest ref={componentRef} x="genre" y="sold" /> </Chart> </Canvas> ); canvas = new Canvas(props); await canvas.render(); await delay(0); expect(chartRef.current.scale.scales.genre.values).toEqual(['Sports']); const container = componentRef.current.container; const group = container.children[0]; expect(group.children.length).toBe(1); expect(group.children[0].config.type).toBe('circle'); }); it('geometry update', async () => { const newChart = ( <Chart data={data1}> <GeometryTest ref={componentRef} x="genre" y="sold" /> </Chart> ); await delay(50); expect(context).toMatchImageSnapshot(); canvas.update({ children: newChart, }); await delay(0); expect(chartRef.current.scale.scales.genre.values).toEqual(['Sports', 'Strategy']); const container = componentRef.current.container; const group = container.children[0]; expect(group.children.length).toBe(2); await delay(50); expect(context).toMatchImageSnapshot(); }); it('', async () => { const data = [ { type: 'FULFILLMENT', y: 171, x: '' }, { type: 'BEHAVIOR', y: 180, x: '' }, { type: 'CHARACTERISTICS', y: 179, x: '' }, { type: 'CAPITAL', y: 160, x: '' }, { type: 'RELATIONSHIP', y: 146, x: '' }, ]; const { props } = ( <Canvas context={context} pixelRatio={1} animate={false}> <Chart data={data}> <Line x="x" y="y" /> </Chart> </Canvas> ); const canvas = new Canvas(props); await canvas.render(); const newChart = ( <Chart data={data}> <Line x="x" y="y" /> <circle style={{ cx: 100, cy: 100, r: 20, fill: 'red', }} /> </Chart> ); await canvas.update({ children: newChart, }); await delay(50); expect(context).toMatchImageSnapshot(); }); it('geometry event', async () => { const onPress = jest.fn(); const { props } = ( <Canvas context={context} pixelRatio={1}> <Chart ref={chartRef} data={data}> <GeometryTest ref={componentRef} x="genre" y="sold" onPress={onPress} /> </Chart> </Canvas> ); canvas = new Canvas(props); await canvas.render(); await delay(100); gestureSimulator(context.canvas, 'touchstart', { x: 60, y: 70 }); gestureSimulator(context.canvas, 'touchmove', { x: 93, y: 35 }); expect(onPress.mock.calls.length).toBe(1); }); }); ```
/content/code_sandbox/packages/f2/test/components/geometry/index.test.tsx
xml
2016-08-29T06:26:23
2024-08-16T15:50:14
F2
antvis/F2
7,877
974
```xml import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { global } from '@storybook/global'; import { composeConfigs } from './composeConfigs'; vi.mock('@storybook/global', () => ({ global: { FEATURES: {}, }, })); describe('composeConfigs', () => { it('sets default (empty) values for fields', () => { expect(composeConfigs([])).toEqual({ parameters: {}, decorators: [], args: {}, argsEnhancers: [], argTypes: {}, argTypesEnhancers: [], globals: {}, initialGlobals: {}, globalTypes: {}, loaders: [], beforeAll: expect.any(Function), beforeEach: [], runStep: expect.any(Function), tags: [], }); }); it('composes parameters', () => { expect( composeConfigs([ { parameters: { obj: { a: '1', b: '1' } }, }, { parameters: { obj: { a: '2', c: '2' } }, }, ]) ).toEqual({ parameters: { obj: { a: '2', b: '1', c: '2' } }, decorators: [], args: {}, argsEnhancers: [], argTypes: {}, argTypesEnhancers: [], globals: {}, initialGlobals: {}, globalTypes: {}, loaders: [], beforeAll: expect.any(Function), beforeEach: [], runStep: expect.any(Function), tags: [], }); }); it('composes export defaults', () => { expect( composeConfigs([ { default: { parameters: { obj: { a: '1', b: '1' } }, }, }, { default: { parameters: { obj: { a: '2', c: '2' } }, }, }, ]) ).toEqual({ parameters: { obj: { a: '2', b: '1', c: '2' } }, decorators: [], args: {}, argsEnhancers: [], argTypes: {}, argTypesEnhancers: [], globals: {}, initialGlobals: {}, globalTypes: {}, loaders: [], beforeAll: expect.any(Function), beforeEach: [], runStep: expect.any(Function), tags: [], }); }); it('overrides object fields by key', () => { expect( composeConfigs([ { default: { args: { x: '1', y: '1', obj: { a: '1', b: '1' } }, argTypes: { x: '1', y: '1', obj: { a: '1', b: '1' } }, globals: { x: '1', y: '1', obj: { a: '1', b: '1' } }, globalTypes: { x: '1', y: '1', obj: { a: '1', b: '1' } }, }, }, { default: { args: { x: '2', z: '2', obj: { a: '2', c: '2' } }, argTypes: { x: '2', z: '2', obj: { a: '2', c: '2' } }, globals: { x: '2', z: '2', obj: { a: '2', c: '2' } }, globalTypes: { x: '2', z: '2', obj: { a: '2', c: '2' } }, }, }, ]) ).toEqual({ parameters: {}, decorators: [], args: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } }, argsEnhancers: [], argTypes: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } }, argTypesEnhancers: [], globals: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } }, initialGlobals: {}, globalTypes: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } }, loaders: [], beforeAll: expect.any(Function), beforeEach: [], runStep: expect.any(Function), tags: [], }); }); it('overrides object fields by key with mixed named and default exports', () => { expect( // configs could come from user, addons, presets, frameworks.. so they will likely be mixed in format composeConfigs([ { default: { args: { x: '1', y: '1', obj: { a: '1', b: '1' } }, argTypes: { x: '1', y: '1', obj: { a: '1', b: '1' } }, globals: { x: '1', y: '1', obj: { a: '1', b: '1' } }, globalTypes: { x: '1', y: '1', obj: { a: '1', b: '1' } }, }, }, { args: { x: '2', z: '2', obj: { a: '2', c: '2' } }, argTypes: { x: '2', z: '2', obj: { a: '2', c: '2' } }, globals: { x: '2', z: '2', obj: { a: '2', c: '2' } }, }, { default: { globalTypes: { x: '2', z: '2', obj: { a: '2', c: '2' } }, }, }, ]) ).toEqual({ parameters: {}, decorators: [], args: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } }, argsEnhancers: [], argTypes: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } }, argTypesEnhancers: [], globals: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } }, initialGlobals: {}, globalTypes: { x: '2', y: '1', z: '2', obj: { a: '2', c: '2' } }, loaders: [], beforeAll: expect.any(Function), beforeEach: [], runStep: expect.any(Function), tags: [], }); }); it('concats array fields', () => { expect( composeConfigs([ { argsEnhancers: ['1', '2'], argTypesEnhancers: ['1', '2'], loaders: ['1', '2'], }, { argsEnhancers: ['3', '4'], argTypesEnhancers: ['3', '4'], loaders: ['3', '4'], }, ]) ).toEqual({ parameters: {}, decorators: [], args: {}, argsEnhancers: ['1', '2', '3', '4'], argTypes: {}, argTypesEnhancers: ['1', '2', '3', '4'], globals: {}, initialGlobals: {}, globalTypes: {}, loaders: ['1', '2', '3', '4'], beforeAll: expect.any(Function), beforeEach: [], runStep: expect.any(Function), tags: [], }); }); it('allows single array to be written without array', () => { expect( composeConfigs([ { argsEnhancers: ['1', '2'], argTypesEnhancers: ['1', '2'], loaders: '1', }, { argsEnhancers: '3', argTypesEnhancers: '3', loaders: ['2', '3'], }, ]) ).toEqual({ parameters: {}, decorators: [], args: {}, argsEnhancers: ['1', '2', '3'], argTypes: {}, argTypesEnhancers: ['1', '2', '3'], globals: {}, initialGlobals: {}, globalTypes: {}, loaders: ['1', '2', '3'], beforeAll: expect.any(Function), beforeEach: [], runStep: expect.any(Function), tags: [], }); }); it('combines decorators in reverse file order', () => { expect( composeConfigs([ { decorators: ['1', '2'], }, { decorators: ['3', '4'], }, ]) ).toEqual({ parameters: {}, decorators: ['3', '4', '1', '2'], args: {}, argsEnhancers: [], argTypes: {}, argTypesEnhancers: [], globals: {}, initialGlobals: {}, globalTypes: {}, loaders: [], beforeAll: expect.any(Function), beforeEach: [], runStep: expect.any(Function), tags: [], }); }); it('concats argTypesEnhancers in two passes', () => { expect( composeConfigs([ { argTypesEnhancers: [{ a: '1' }, { a: '2', secondPass: true }] }, { argTypesEnhancers: [{ a: '3' }, { a: '4', secondPass: true }] }, ]) ).toEqual({ parameters: {}, decorators: [], args: {}, argsEnhancers: [], argTypes: {}, argTypesEnhancers: [ { a: '1' }, { a: '3' }, { a: '2', secondPass: true }, { a: '4', secondPass: true }, ], globals: {}, initialGlobals: {}, globalTypes: {}, loaders: [], beforeAll: expect.any(Function), beforeEach: [], runStep: expect.any(Function), tags: [], }); }); it('concats chooses scalar fields', () => { expect( composeConfigs([ { render: 'render-1', renderToCanvas: 'renderToCanvas-1', applyDecorators: 'applyDecorators-1', }, { render: 'render-2', renderToCanvas: 'renderToCanvas-2', applyDecorators: 'applyDecorators-2', }, ]) ).toEqual({ parameters: {}, decorators: [], args: {}, argsEnhancers: [], argTypes: {}, argTypesEnhancers: [], globals: {}, initialGlobals: {}, globalTypes: {}, loaders: [], beforeAll: expect.any(Function), beforeEach: [], render: 'render-2', renderToCanvas: 'renderToCanvas-2', applyDecorators: 'applyDecorators-2', runStep: expect.any(Function), tags: [], }); }); it('composes beforeAll hooks', async () => { const one = vi.fn(); const two = vi.fn(); const three = vi.fn(); const { beforeAll } = composeConfigs([ { beforeAll: one }, { beforeAll: two }, { beforeAll: three }, ]); await beforeAll?.(); expect(one).toHaveBeenCalled(); expect(two).toHaveBeenCalled(); expect(three).toHaveBeenCalled(); }); it('composes step runners', () => { const fn = vi.fn(); const { runStep } = composeConfigs([ // @ts-expect-error (not defined) { runStep: (label, play, context) => fn(`${label}1`, play(context)) }, // @ts-expect-error (not defined) { runStep: (label, play, context) => fn(`${label}2`, play(context)) }, // @ts-expect-error (not defined) { runStep: (label, play, context) => fn(`${label}3`, play(context)) }, ]); // @ts-expect-error We don't care about the context value here runStep('Label', () => {}, {}); expect(fn).toHaveBeenCalledTimes(3); expect(fn).toHaveBeenNthCalledWith(1, 'Label3', expect.anything()); expect(fn).toHaveBeenNthCalledWith(2, 'Label2', expect.anything()); expect(fn).toHaveBeenNthCalledWith(3, 'Label1', expect.anything()); }); describe('FEATURES.legacyDecoratorFileOrder set to true', () => { beforeEach(() => { global.FEATURES!.legacyDecoratorFileOrder = true; }); afterEach(() => { global.FEATURES!.legacyDecoratorFileOrder = false; }); it('should merge decorators in the order they are defined file-wise', () => { expect( composeConfigs([ { decorators: ['1', '2'], }, { decorators: ['3', '4'], }, ]) ).toMatchObject({ decorators: ['1', '2', '3', '4'], }); }); }); }); ```
/content/code_sandbox/code/core/src/preview-api/modules/store/csf/composeConfigs.test.ts
xml
2016-03-18T04:23:44
2024-08-16T19:22:08
storybook
storybookjs/storybook
83,755
2,901
```xml <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="path_to_url"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <ItemGroup> <ClCompile Include="..\..\programs\pkey\key_app_writer.c" /> </ItemGroup> <ItemGroup> <ProjectReference Include="mbedTLS.vcxproj"> <Project>{46cf2d25-6a36-4189-b59c-e4815388e554}</Project> <LinkLibraryDependencies>true</LinkLibraryDependencies> </ProjectReference> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{E8ED79F9-8034-1B09-263E-D3F8C4C5C4A8}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>key_app_writer</RootNamespace> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>Unicode</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <LinkIncremental>true</LinkIncremental> <IntDir>$(Configuration)\$(TargetName)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <LinkIncremental>true</LinkIncremental> <IntDir>$(Configuration)\$(TargetName)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <LinkIncremental>false</LinkIncremental> <IntDir>$(Configuration)\$(TargetName)\</IntDir> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <LinkIncremental>false</LinkIncremental> <IntDir>$(Configuration)\$(TargetName)\</IntDir> </PropertyGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>../../include</AdditionalIncludeDirectories> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <ShowProgress>NotSet</ShowProgress> <AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>Debug</AdditionalLibraryDirectories> </Link> <ProjectReference> <LinkLibraryDependencies>false</LinkLibraryDependencies> </ProjectReference> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PrecompiledHeader> </PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>../../include</AdditionalIncludeDirectories> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <ShowProgress>NotSet</ShowProgress> <AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalLibraryDirectories>Debug</AdditionalLibraryDirectories> </Link> <ProjectReference> <LinkLibraryDependencies>false</LinkLibraryDependencies> </ProjectReference> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>../../include</AdditionalIncludeDirectories> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalLibraryDirectories>Release</AdditionalLibraryDirectories> <AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <PrecompiledHeader> </PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>WIN64;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions> <AdditionalIncludeDirectories>../../include</AdditionalIncludeDirectories> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> <AdditionalLibraryDirectories>Release</AdditionalLibraryDirectories> <AdditionalDependencies>%(AdditionalDependencies);</AdditionalDependencies> </Link> </ItemDefinitionGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project> ```
/content/code_sandbox/components/security/mbedtls/mbedtls-2.16.8/visualc/VS2010/key_app_writer.vcxproj
xml
2016-09-11T14:25:51
2024-08-16T10:12:43
LiteOS
LiteOS/LiteOS
4,794
2,164
```xml /* Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at path_to_url */ import {assert} from 'workbox-core/_private/assert.js'; import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.js'; import { RouteHandler, RouteHandlerObject, RouteHandlerCallbackOptions, RouteMatchCallbackOptions, } from 'workbox-core/types.js'; import {HTTPMethod, defaultMethod} from './utils/constants.js'; import {logger} from 'workbox-core/_private/logger.js'; import {normalizeHandler} from './utils/normalizeHandler.js'; import {Route} from './Route.js'; import {WorkboxError} from 'workbox-core/_private/WorkboxError.js'; import './_version.js'; type RequestArgs = string | [string, RequestInit?]; interface CacheURLsMessageData { type: string; payload: { urlsToCache: RequestArgs[]; }; } /** * The Router can be used to process a `FetchEvent` using one or more * {@link workbox-routing.Route}, responding with a `Response` if * a matching route exists. * * If no route matches a given a request, the Router will use a "default" * handler if one is defined. * * Should the matching Route throw an error, the Router will use a "catch" * handler if one is defined to gracefully deal with issues and respond with a * Request. * * If a request matches multiple routes, the **earliest** registered route will * be used to respond to the request. * * @memberof workbox-routing */ class Router { private readonly _routes: Map<HTTPMethod, Route[]>; private readonly _defaultHandlerMap: Map<HTTPMethod, RouteHandlerObject>; private _catchHandler?: RouteHandlerObject; /** * Initializes a new Router. */ constructor() { this._routes = new Map(); this._defaultHandlerMap = new Map(); } /** * @return {Map<string, Array<workbox-routing.Route>>} routes A `Map` of HTTP * method name ('GET', etc.) to an array of all the corresponding `Route` * instances that are registered. */ get routes(): Map<HTTPMethod, Route[]> { return this._routes; } /** * Adds a fetch event listener to respond to events when a route matches * the event's request. */ addFetchListener(): void { // See path_to_url#issuecomment-436484705 self.addEventListener('fetch', ((event: FetchEvent) => { const {request} = event; const responsePromise = this.handleRequest({request, event}); if (responsePromise) { event.respondWith(responsePromise); } }) as EventListener); } /** * Adds a message event listener for URLs to cache from the window. * This is useful to cache resources loaded on the page prior to when the * service worker started controlling it. * * The format of the message data sent from the window should be as follows. * Where the `urlsToCache` array may consist of URL strings or an array of * URL string + `requestInit` object (the same as you'd pass to `fetch()`). * * ``` * { * type: 'CACHE_URLS', * payload: { * urlsToCache: [ * './script1.js', * './script2.js', * ['./script3.js', {mode: 'no-cors'}], * ], * }, * } * ``` */ addCacheListener(): void { // See path_to_url#issuecomment-436484705 self.addEventListener('message', ((event: ExtendableMessageEvent) => { // event.data is type 'any' // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (event.data && event.data.type === 'CACHE_URLS') { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const {payload}: CacheURLsMessageData = event.data; if (process.env.NODE_ENV !== 'production') { logger.debug(`Caching URLs from the window`, payload.urlsToCache); } const requestPromises = Promise.all( payload.urlsToCache.map((entry: string | [string, RequestInit?]) => { if (typeof entry === 'string') { entry = [entry]; } const request = new Request(...entry); return this.handleRequest({request, event}); // TODO(philipwalton): TypeScript errors without this typecast for // some reason (probably a bug). The real type here should work but // doesn't: `Array<Promise<Response> | undefined>`. }) as any[], ); // TypeScript event.waitUntil(requestPromises); // If a MessageChannel was used, reply to the message on success. if (event.ports && event.ports[0]) { void requestPromises.then(() => event.ports[0].postMessage(true)); } } }) as EventListener); } /** * Apply the routing rules to a FetchEvent object to get a Response from an * appropriate Route's handler. * * @param {Object} options * @param {Request} options.request The request to handle. * @param {ExtendableEvent} options.event The event that triggered the * request. * @return {Promise<Response>|undefined} A promise is returned if a * registered route can handle the request. If there is no matching * route and there's no `defaultHandler`, `undefined` is returned. */ handleRequest({ request, event, }: { request: Request; event: ExtendableEvent; }): Promise<Response> | undefined { if (process.env.NODE_ENV !== 'production') { assert!.isInstance(request, Request, { moduleName: 'workbox-routing', className: 'Router', funcName: 'handleRequest', paramName: 'options.request', }); } const url = new URL(request.url, location.href); if (!url.protocol.startsWith('http')) { if (process.env.NODE_ENV !== 'production') { logger.debug( `Workbox Router only supports URLs that start with 'http'.`, ); } return; } const sameOrigin = url.origin === location.origin; const {params, route} = this.findMatchingRoute({ event, request, sameOrigin, url, }); let handler = route && route.handler; const debugMessages = []; if (process.env.NODE_ENV !== 'production') { if (handler) { debugMessages.push([`Found a route to handle this request:`, route]); if (params) { debugMessages.push([ `Passing the following params to the route's handler:`, params, ]); } } } // If we don't have a handler because there was no matching route, then // fall back to defaultHandler if that's defined. const method = request.method as HTTPMethod; if (!handler && this._defaultHandlerMap.has(method)) { if (process.env.NODE_ENV !== 'production') { debugMessages.push( `Failed to find a matching route. Falling ` + `back to the default handler for ${method}.`, ); } handler = this._defaultHandlerMap.get(method); } if (!handler) { if (process.env.NODE_ENV !== 'production') { // No handler so Workbox will do nothing. If logs is set of debug // i.e. verbose, we should print out this information. logger.debug(`No route found for: ${getFriendlyURL(url)}`); } return; } if (process.env.NODE_ENV !== 'production') { // We have a handler, meaning Workbox is going to handle the route. // print the routing details to the console. logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`); debugMessages.forEach((msg) => { if (Array.isArray(msg)) { logger.log(...msg); } else { logger.log(msg); } }); logger.groupEnd(); } // Wrap in try and catch in case the handle method throws a synchronous // error. It should still callback to the catch handler. let responsePromise; try { responsePromise = handler.handle({url, request, event, params}); } catch (err) { responsePromise = Promise.reject(err); } // Get route's catch handler, if it exists const catchHandler = route && route.catchHandler; if ( responsePromise instanceof Promise && (this._catchHandler || catchHandler) ) { responsePromise = responsePromise.catch(async (err) => { // If there's a route catch handler, process that first if (catchHandler) { if (process.env.NODE_ENV !== 'production') { // Still include URL here as it will be async from the console group // and may not make sense without the URL logger.groupCollapsed( `Error thrown when responding to: ` + ` ${getFriendlyURL( url, )}. Falling back to route's Catch Handler.`, ); logger.error(`Error thrown by:`, route); logger.error(err); logger.groupEnd(); } try { return await catchHandler.handle({url, request, event, params}); } catch (catchErr) { if (catchErr instanceof Error) { err = catchErr; } } } if (this._catchHandler) { if (process.env.NODE_ENV !== 'production') { // Still include URL here as it will be async from the console group // and may not make sense without the URL logger.groupCollapsed( `Error thrown when responding to: ` + ` ${getFriendlyURL( url, )}. Falling back to global Catch Handler.`, ); logger.error(`Error thrown by:`, route); logger.error(err); logger.groupEnd(); } return this._catchHandler.handle({url, request, event}); } throw err; }); } return responsePromise; } /** * Checks a request and URL (and optionally an event) against the list of * registered routes, and if there's a match, returns the corresponding * route along with any params generated by the match. * * @param {Object} options * @param {URL} options.url * @param {boolean} options.sameOrigin The result of comparing `url.origin` * against the current origin. * @param {Request} options.request The request to match. * @param {Event} options.event The corresponding event. * @return {Object} An object with `route` and `params` properties. * They are populated if a matching route was found or `undefined` * otherwise. */ findMatchingRoute({ url, sameOrigin, request, event, }: RouteMatchCallbackOptions): { route?: Route; params?: RouteHandlerCallbackOptions['params']; } { const routes = this._routes.get(request.method as HTTPMethod) || []; for (const route of routes) { let params: Promise<any> | undefined; // route.match returns type any, not possible to change right now. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const matchResult = route.match({url, sameOrigin, request, event}); if (matchResult) { if (process.env.NODE_ENV !== 'production') { // Warn developers that using an async matchCallback is almost always // not the right thing to do. if (matchResult instanceof Promise) { logger.warn( `While routing ${getFriendlyURL(url)}, an async ` + `matchCallback function was used. Please convert the ` + `following route to use a synchronous matchCallback function:`, route, ); } } // See path_to_url // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment params = matchResult; if (Array.isArray(params) && params.length === 0) { // Instead of passing an empty array in as params, use undefined. params = undefined; } else if ( matchResult.constructor === Object && // eslint-disable-line Object.keys(matchResult).length === 0 ) { // Instead of passing an empty object in as params, use undefined. params = undefined; } else if (typeof matchResult === 'boolean') { // For the boolean value true (rather than just something truth-y), // don't set params. // See path_to_url#issuecomment-513924353 params = undefined; } // Return early if have a match. return {route, params}; } } // If no match was found above, return and empty object. return {}; } /** * Define a default `handler` that's called when no routes explicitly * match the incoming request. * * Each HTTP method ('GET', 'POST', etc.) gets its own default handler. * * Without a default handler, unmatched requests will go against the * network as if there were no service worker present. * * @param {workbox-routing~handlerCallback} handler A callback * function that returns a Promise resulting in a Response. * @param {string} [method='GET'] The HTTP method to associate with this * default handler. Each method has its own default. */ setDefaultHandler( handler: RouteHandler, method: HTTPMethod = defaultMethod, ): void { this._defaultHandlerMap.set(method, normalizeHandler(handler)); } /** * If a Route throws an error while handling a request, this `handler` * will be called and given a chance to provide a response. * * @param {workbox-routing~handlerCallback} handler A callback * function that returns a Promise resulting in a Response. */ setCatchHandler(handler: RouteHandler): void { this._catchHandler = normalizeHandler(handler); } /** * Registers a route with the router. * * @param {workbox-routing.Route} route The route to register. */ registerRoute(route: Route): void { if (process.env.NODE_ENV !== 'production') { assert!.isType(route, 'object', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route', }); assert!.hasMethod(route, 'match', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route', }); assert!.isType(route.handler, 'object', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route', }); assert!.hasMethod(route.handler, 'handle', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route.handler', }); assert!.isType(route.method, 'string', { moduleName: 'workbox-routing', className: 'Router', funcName: 'registerRoute', paramName: 'route.method', }); } if (!this._routes.has(route.method)) { this._routes.set(route.method, []); } // Give precedence to all of the earlier routes by adding this additional // route to the end of the array. this._routes.get(route.method)!.push(route); } /** * Unregisters a route with the router. * * @param {workbox-routing.Route} route The route to unregister. */ unregisterRoute(route: Route): void { if (!this._routes.has(route.method)) { throw new WorkboxError('unregister-route-but-not-found-with-method', { method: route.method, }); } const routeIndex = this._routes.get(route.method)!.indexOf(route); if (routeIndex > -1) { this._routes.get(route.method)!.splice(routeIndex, 1); } else { throw new WorkboxError('unregister-route-route-not-registered'); } } } export {Router}; ```
/content/code_sandbox/packages/workbox-routing/src/Router.ts
xml
2016-04-04T15:55:19
2024-08-16T08:33:26
workbox
GoogleChrome/workbox
12,245
3,587
```xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="path_to_url" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> </FrameLayout> ```
/content/code_sandbox/app/src/main/res/layout/simple_fragment_layout.xml
xml
2016-06-26T08:20:43
2024-08-16T18:33:28
MagicIndicator
hackware1993/MagicIndicator
9,699
89
```xml /** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in path_to_url */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** IE10 and IE11 requires the following for NgClass support on SVG elements */ // import 'classlist.js'; // Run `npm install --save classlist.js`. /** * Web Animations `@angular/platform-browser/animations` * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). */ // import 'web-animations-js'; // Run `npm install --save web-animations-js`. /** * By default, zone.js will patch all possible macroTask and DomEvents * user can disable parts of macroTask/DomEvents patch by setting following flags * because those flags need to be set before `zone.js` being loaded, and webpack * will put import in the top of bundle, so user need to create a separate file * in this directory (for example: zone-flags.ts), and put the following flags * into that file, and then add the following code before importing zone.js. * import './zone-flags'; * * The flags allowed in zone-flags.ts are listed here. * * The following flags will work for all browsers. * * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames * * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js * with the following flag, it will bypass `zone.js` patch for IE/Edge * * (window as any).__Zone_enable_cross_context_check = true; * */ /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */ ```
/content/code_sandbox/projects/docs-app/src/polyfills.ts
xml
2016-03-10T21:29:15
2024-08-15T07:07:30
angular-tree-component
CirclonGroup/angular-tree-component
1,093
583
```xml import { Matrix } from '.'; import { randomN } from '../../utilities/random'; export class RandomNMatrix extends Matrix { std: number; mu: number; constructor(rows: number, columns: number, mu: number, std: number) { super(rows, columns); this.std = std; this.mu = mu; this.fillRandN(); } // fill matrix with random gaussian numbers fillRandN(): void { for (let i = 0, max = this.weights.length; i < max; i++) { this.weights[i] = randomN(this.mu, this.std); } } } ```
/content/code_sandbox/src/recurrent/matrix/random-n-matrix.ts
xml
2016-02-13T18:09:44
2024-08-15T20:41:49
brain.js
BrainJS/brain.js
14,300
137
```xml import fs from 'fs/promises'; import debounce from 'lodash.debounce'; import { Server } from 'metro'; import path from 'path'; import resolveFrom from 'resolve-from'; import { directoryExistsAsync } from '../../../utils/dir'; import { unsafeTemplate } from '../../../utils/template'; import { ServerLike } from '../BundlerDevServer'; import { metroWatchTypeScriptFiles } from '../metro/metroWatchTypeScriptFiles'; // /test/[...param1]/[param2]/[param3] - captures ["param1", "param2", "param3"] export const CAPTURE_DYNAMIC_PARAMS = /\[(?:\.{3})?(\w*?)[\]$]/g; // /[...param1]/ - Match [...param1] export const CATCH_ALL = /\[\.\.\..+?\]/g; // /[param1] - Match [param1] export const SLUG = /\[.+?\]/g; // /(group1,group2,group3)/test - match (group1,group2,group3) export const ARRAY_GROUP_REGEX = /\(\s*\w[\w\s]*?,.*?\)/g; // /(group1,group2,group3)/test - captures ["group1", "group2", "group3"] export const CAPTURE_GROUP_REGEX = /[\\(,]\s*(\w[\w\s]*?)\s*(?=[,\\)])/g; /** * Match: * - _layout files, +html, +not-found, string+api, etc * - Routes can still use `+`, but it cannot be in the last segment. */ export const TYPED_ROUTES_EXCLUSION_REGEX = /(_layout|[^/]*?\+[^/]*?)\.[tj]sx?$/; export interface SetupTypedRoutesOptions { server?: ServerLike; metro?: Server | null; typesDirectory: string; projectRoot: string; /** Absolute expo router routes directory. */ routerDirectory: string; } export async function setupTypedRoutes(options: SetupTypedRoutesOptions) { const typedRoutesModule = resolveFrom.silent( options.projectRoot, 'expo-router/build/typed-routes' ); return typedRoutesModule ? typedRoutes(typedRoutesModule, options) : legacyTypedRoutes(options); } async function typedRoutes( typedRoutesModulePath: any, { server, metro, typesDirectory, projectRoot, routerDirectory }: SetupTypedRoutesOptions ) { /** * Expo Router uses EXPO_ROUTER_APP_ROOT in multiple places to determine the root of the project. * In apps compiled by Metro, this code is compiled away. But Typed Routes run in NodeJS with no compilation * so we need to explicitly set it. */ process.env.EXPO_ROUTER_APP_ROOT = routerDirectory; const typedRoutesModule = require(typedRoutesModulePath); /** * Typed Routes can be run with out Metro or a Server, e.g. `expo customize tsconfig.json` */ if (metro && server) { // Setup out watcher first metroWatchTypeScriptFiles({ projectRoot, server, metro, eventTypes: ['add', 'delete', 'change'], callback: typedRoutesModule.getWatchHandler(typesDirectory), }); } typedRoutesModule.regenerateDeclarations(typesDirectory); } async function legacyTypedRoutes({ server, metro, typesDirectory, projectRoot, routerDirectory, }: SetupTypedRoutesOptions) { const { filePathToRoute, staticRoutes, dynamicRoutes, addFilePath, isRouteFile } = getTypedRoutesUtils(routerDirectory); // Typed Routes can be run with out Metro or a Server, e.g. `expo customize tsconfig.json` if (metro && server) { metroWatchTypeScriptFiles({ projectRoot, server, metro, eventTypes: ['add', 'delete', 'change'], async callback({ filePath, type }) { if (!isRouteFile(filePath)) { return; } let shouldRegenerate = false; if (type === 'delete') { const route = filePathToRoute(filePath); staticRoutes.delete(route); dynamicRoutes.delete(route); shouldRegenerate = true; } else { shouldRegenerate = addFilePath(filePath); } if (shouldRegenerate) { regenerateRouterDotTS( typesDirectory, new Set([...staticRoutes.values()].flatMap((v) => Array.from(v))), new Set([...dynamicRoutes.values()].flatMap((v) => Array.from(v))), new Set(dynamicRoutes.keys()) ); } }, }); } if (await directoryExistsAsync(routerDirectory)) { // Do we need to walk the entire tree on startup? // Idea: Store the list of files in the last write, then simply check Git for what files have changed await walk(routerDirectory, addFilePath); } regenerateRouterDotTS( typesDirectory, new Set([...staticRoutes.values()].flatMap((v) => Array.from(v))), new Set([...dynamicRoutes.values()].flatMap((v) => Array.from(v))), new Set(dynamicRoutes.keys()) ); } /** * Generate a router.d.ts file that contains all of the routes in the project. * Should be debounced as its very common for developers to make changes to multiple files at once (eg Save All) */ const regenerateRouterDotTS = debounce( async ( typesDir: string, staticRoutes: Set<string>, dynamicRoutes: Set<string>, dynamicRouteTemplates: Set<string> ) => { await fs.mkdir(typesDir, { recursive: true }); await fs.writeFile( path.resolve(typesDir, './router.d.ts'), getTemplateString(staticRoutes, dynamicRoutes, dynamicRouteTemplates) ); }, 100 ); /* * This is exported for testing purposes */ export function getTemplateString( staticRoutes: Set<string>, dynamicRoutes: Set<string>, dynamicRouteTemplates: Set<string> ) { return routerDotTSTemplate({ staticRoutes: setToUnionType(staticRoutes), dynamicRoutes: setToUnionType(dynamicRoutes), dynamicRouteParams: setToUnionType(dynamicRouteTemplates), }); } /** * Utility functions for typed routes * * These are extracted for easier testing */ export function getTypedRoutesUtils(appRoot: string, filePathSeperator = path.sep) { /* * staticRoutes are a map where the key if the route without groups and the value * is another set of all group versions of the route. e.g, * Map([ * ["/", ["/(app)/(notes)", "/(app)/(profile)"] * ]) */ const staticRoutes = new Map<string, Set<string>>([['/', new Set('/')]]); /* * dynamicRoutes are the same as staticRoutes (key if the resolved route, * and the value is a set of possible routes). e.g: * * /[...fruits] -> /${CatchAllRoutePart<T>} * /color/[color] -> /color/${SingleRoutePart<T>} * * The keys of this map are also important, as they can be used as "static" types * <Link href={{ pathname: "/[...fruits]",params: { fruits: ["apple"] } }} /> */ const dynamicRoutes = new Map<string, Set<string>>(); function normalizedFilePath(filePath: string) { return filePath.replaceAll(filePathSeperator, '/'); } const normalizedAppRoot = normalizedFilePath(appRoot); const filePathToRoute = (filePath: string) => { return normalizedFilePath(filePath) .replace(normalizedAppRoot, '') .replace(/index\.[jt]sx?/, '') .replace(/\.[jt]sx?$/, ''); }; const isRouteFile = (filePath: string) => { if (filePath.match(TYPED_ROUTES_EXCLUSION_REGEX)) { return false; } // Route files must be nested with in the appRoot const relative = path.relative(appRoot, filePath); return relative && !relative.startsWith('..') && !path.isAbsolute(relative); }; const addFilePath = (filePath: string): boolean => { if (!isRouteFile(filePath)) { return false; } const route = filePathToRoute(filePath); // We have already processed this file if (staticRoutes.has(route) || dynamicRoutes.has(route)) { return false; } const dynamicParams = new Set( [...route.matchAll(CAPTURE_DYNAMIC_PARAMS)].map((match) => match[1]) ); const isDynamic = dynamicParams.size > 0; const addRoute = (originalRoute: string, route: string) => { if (isDynamic) { let set = dynamicRoutes.get(originalRoute); if (!set) { set = new Set(); dynamicRoutes.set(originalRoute, set); } set.add( route .replaceAll(CATCH_ALL, '${CatchAllRoutePart<T>}') .replaceAll(SLUG, '${SingleRoutePart<T>}') ); } else { let set = staticRoutes.get(originalRoute); if (!set) { set = new Set(); staticRoutes.set(originalRoute, set); } set.add(route); } }; if (!route.match(ARRAY_GROUP_REGEX)) { addRoute(route, route); } // Does this route have a group? eg /(group) if (route.includes('/(')) { const routeWithoutGroups = route.replace(/\/\(.+?\)/g, ''); addRoute(route, routeWithoutGroups); // If there are multiple groups, we need to expand them // eg /(test1,test2)/page => /test1/page & /test2/page for (const routeWithSingleGroup of extrapolateGroupRoutes(route)) { addRoute(route, routeWithSingleGroup); } } return true; }; return { staticRoutes, dynamicRoutes, filePathToRoute, addFilePath, isRouteFile, }; } export const setToUnionType = <T>(set: Set<T>) => { return set.size > 0 ? [...set].map((s) => `\`${s}\``).join(' | ') : 'never'; }; /** * Recursively walk a directory and call the callback with the file path. */ async function walk(directory: string, callback: (filePath: string) => void) { const files = await fs.readdir(directory); for (const file of files) { const p = path.join(directory, file); if ((await fs.stat(p)).isDirectory()) { await walk(p, callback); } else { // Normalise the paths so they are easier to convert to URLs const normalizedPath = p.replaceAll(path.sep, '/'); callback(normalizedPath); } } } /** * Given a route, return all possible routes that could be generated from it. */ export function extrapolateGroupRoutes( route: string, routes: Set<string> = new Set() ): Set<string> { // Create a version with no groups. We will then need to cleanup double and/or trailing slashes routes.add(route.replaceAll(ARRAY_GROUP_REGEX, '').replaceAll(/\/+/g, '/').replace(/\/$/, '')); const match = route.match(ARRAY_GROUP_REGEX); if (!match) { routes.add(route); return routes; } const groupsMatch = match[0]; for (const group of groupsMatch.matchAll(CAPTURE_GROUP_REGEX)) { extrapolateGroupRoutes(route.replace(groupsMatch, `(${group[1].trim()})`), routes); } return routes; } /** * NOTE: This code refers to a specific version of `expo-router` and is therefore unsafe to * mix with arbitrary versions. * TODO: Version this code with `expo-router` or version expo-router with `@expo/cli`. */ const routerDotTSTemplate = unsafeTemplate`/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable import/export */ /* eslint-disable @typescript-eslint/ban-types */ declare module "expo-router" { import type { LinkProps as OriginalLinkProps } from 'expo-router/build/link/Link'; import type { Router as OriginalRouter } from 'expo-router/build/types'; export * from 'expo-router/build'; // prettier-ignore type StaticRoutes = ${'staticRoutes'}; // prettier-ignore type DynamicRoutes<T extends string> = ${'dynamicRoutes'}; // prettier-ignore type DynamicRouteTemplate = ${'dynamicRouteParams'}; type RelativePathString = \`./\${string}\` | \`../\${string}\` | '..'; type AbsoluteRoute = DynamicRouteTemplate | StaticRoutes; type ExternalPathString = \`\${string}:\${string}\`; type ExpoRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString; export type AllRoutes = ExpoRouterRoutes | ExternalPathString; /**************** * Route Utils * ****************/ type SearchOrHash = \`?\${string}\` | \`#\${string}\`; type UnknownInputParams = Record<string, string | number | (string | number)[]>; type UnknownOutputParams = Record<string, string | string[]>; /** * Return only the RoutePart of a string. If the string has multiple parts return never * * string | type * ---------|------ * 123 | 123 * /123/abc | never * 123?abc | never * ./123 | never * /123 | never * 123/../ | never */ type SingleRoutePart<S extends string> = S extends \`\${string}/\${string}\` ? never : S extends \`\${string}\${SearchOrHash}\` ? never : S extends '' ? never : S extends \`(\${string})\` ? never : S extends \`[\${string}]\` ? never : S; /** * Return only the CatchAll router part. If the string has search parameters or a hash return never */ type CatchAllRoutePart<S extends string> = S extends \`\${string}\${SearchOrHash}\` ? never : S extends '' ? never : S extends \`\${string}(\${string})\${string}\` ? never : S extends \`\${string}[\${string}]\${string}\` ? never : S; // type OptionalCatchAllRoutePart<S extends string> = S extends \`\${string}\${SearchOrHash}\` ? never : S /** * Return the name of a route parameter * '[test]' -> 'test' * 'test' -> never * '[...test]' -> '...test' */ type IsParameter<Part> = Part extends \`[\${infer ParamName}]\` ? ParamName : never; /** * Return a union of all parameter names. If there are no names return never * * /[test] -> 'test' * /[abc]/[...def] -> 'abc'|'...def' */ type ParameterNames<Path> = Path extends \`\${infer PartA}/\${infer PartB}\` ? IsParameter<PartA> | ParameterNames<PartB> : IsParameter<Path>; /** * Returns all segements of a route. * * /(group)/123/abc/[id]/[...rest] -> ['(group)', '123', 'abc', '[id]', '[...rest]' */ type RouteSegments<Path> = Path extends \`\${infer PartA}/\${infer PartB}\` ? PartA extends '' | '.' ? [...RouteSegments<PartB>] : [PartA, ...RouteSegments<PartB>] : Path extends '' ? [] : [Path]; /** * Returns a Record of the routes parameters as strings and CatchAll parameters * * There are two versions, input and output, as you can input 'string | number' but * the output will always be 'string' * * /[id]/[...rest] -> { id: string, rest: string[] } * /no-params -> {} */ type InputRouteParams<Path> = { [Key in ParameterNames<Path> as Key extends \`...\${infer Name}\` ? Name : Key]: Key extends \`...\${string}\` ? (string | number)[] : string | number; } & UnknownInputParams; type OutputRouteParams<Path> = { [Key in ParameterNames<Path> as Key extends \`...\${infer Name}\` ? Name : Key]: Key extends \`...\${string}\` ? string[] : string; } & UnknownOutputParams; /** * Returns the search parameters for a route. */ export type SearchParams<T extends AllRoutes> = T extends DynamicRouteTemplate ? OutputRouteParams<T> : T extends StaticRoutes ? never : UnknownOutputParams; /** * Route is mostly used as part of Href to ensure that a valid route is provided * * Given a dynamic route, this will return never. This is helpful for conditional logic * * /test -> /test, /test2, etc * /test/[abc] -> never * /test/resolve -> /test, /test2, etc * * Note that if we provide a value for [abc] then the route is allowed * * This is named Route to prevent confusion, as users they will often see it in tooltips */ export type Route<T> = T extends string ? T extends DynamicRouteTemplate ? never : | StaticRoutes | RelativePathString | ExternalPathString | (T extends \`\${infer P}\${SearchOrHash}\` ? P extends DynamicRoutes<infer _> ? T : never : T extends DynamicRoutes<infer _> ? T : never) : never; /********* * Href * *********/ export type Href<T> = T extends Record<'pathname', string> ? HrefObject<T> : Route<T>; export type HrefObject< R extends Record<'pathname', string>, P = R['pathname'], > = P extends DynamicRouteTemplate ? { pathname: P; params: InputRouteParams<P> } : P extends Route<P> ? { pathname: Route<P> | DynamicRouteTemplate; params?: never | InputRouteParams<never> } : never; /*********************** * Expo Router Exports * ***********************/ export type Router = Omit<OriginalRouter, 'push' | 'replace' | 'setParams'> & { /** Navigate to the provided href. */ push: <T>(href: Href<T>) => void; /** Navigate to route without appending to the history. */ replace: <T>(href: Href<T>) => void; /** Update the current route query params. */ setParams: <T = ''>(params?: T extends '' ? Record<string, string> : InputRouteParams<T>) => void; }; /** The imperative router. */ export const router: Router; /************ * <Link /> * ************/ export interface LinkProps<T> extends OriginalLinkProps { href: Href<T>; } export interface LinkComponent { <T>(props: React.PropsWithChildren<LinkProps<T>>): JSX.Element; /** Helper method to resolve an Href object into a string. */ resolveHref: <T>(href: Href<T>) => string; } /** * Component to render link to another route using a path. * Uses an anchor tag on the web. * * @param props.href Absolute path to route (e.g. \`/feeds/hot\`). * @param props.replace Should replace the current route without adding to the history. * @param props.asChild Forward props to child component. Useful for custom buttons. * @param props.children Child elements to render the content. * @param props.className On web, this sets the HTML \`class\` directly. On native, this can be used with CSS interop tools like Nativewind. */ export const Link: LinkComponent; /** Redirects to the href as soon as the component is mounted. */ export const Redirect: <T>( props: React.PropsWithChildren<{ href: Href<T> }> ) => JSX.Element; /************ * Hooks * ************/ export function useRouter(): Router; export function useLocalSearchParams< T extends AllRoutes | UnknownOutputParams = UnknownOutputParams, >(): T extends AllRoutes ? SearchParams<T> : T; /** @deprecated renamed to \`useGlobalSearchParams\` */ export function useSearchParams< T extends AllRoutes | UnknownOutputParams = UnknownOutputParams, >(): T extends AllRoutes ? SearchParams<T> : T; export function useGlobalSearchParams< T extends AllRoutes | UnknownOutputParams = UnknownOutputParams, >(): T extends AllRoutes ? SearchParams<T> : T; export function useSegments< T extends AbsoluteRoute | RouteSegments<AbsoluteRoute> | RelativePathString, >(): T extends AbsoluteRoute ? RouteSegments<T> : T extends string ? string[] : T; } `; ```
/content/code_sandbox/packages/@expo/cli/src/start/server/type-generation/routes.ts
xml
2016-08-15T17:14:25
2024-08-16T19:54:44
expo
expo/expo
32,004
4,671
```xml export { default as InputFieldStacked } from './InputFieldStacked'; ```
/content/code_sandbox/packages/components/components/inputFieldStacked/index.ts
xml
2016-06-08T11:16:51
2024-08-16T14:14:27
WebClients
ProtonMail/WebClients
4,300
17
```xml import { createDisposable, disposeOf } from 'utils-disposables'; import { describe, expect, test, vi } from 'vitest'; import { createSubscribable } from '../createFunctions'; import { toSubscriberFn } from '../helpers/toSubscriber'; import { rx } from '../rx'; import type { SubscribeFn, SubscriberFn, SubscriberLike } from '../Subscribables'; import { delayUnsubscribe } from './delayUnsubscribe'; describe('delayUnsubscribe', () => { test('delayUnsubscribe', () => { const receiver = vi.fn(); const defaultEmitter = () => undefined; let emitter: SubscriberFn<number> = defaultEmitter; const resetEmitter = vi.fn(() => (emitter = defaultEmitter)); expect(emitter).toBe(defaultEmitter); const source: SubscribeFn<number> = (subscriber: SubscriberLike<number>) => { emitter = toSubscriberFn(subscriber); return createDisposable(resetEmitter); }; const sub = createSubscribable<number>(source); // Since there haven't been any subscribers, do not expect the emitter to change. expect(emitter).toBe(defaultEmitter); const dispose1 = sub.subscribe(receiver); expect(emitter).not.toBe(defaultEmitter); // There should be a new emitter. expect(emitter).not.toBe(defaultEmitter); disposeOf(dispose1); // Expect the emitter to be restored. expect(emitter).toBe(defaultEmitter); const opDelayUnsubscribe = delayUnsubscribe<number>(10000); const subDelayed = opDelayUnsubscribe(sub); // Expect the emitter to still be the default. expect(emitter).toBe(defaultEmitter); const dispose2 = subDelayed.subscribe(receiver); // There should be a new emitter. expect(emitter).not.toBe(defaultEmitter); const emitter2 = emitter; emitter(42); expect(receiver).toHaveBeenLastCalledWith(42); disposeOf(dispose2); // The emitter should still be emitter2; expect(emitter).toBe(emitter2); emitter(27); expect(receiver).toHaveBeenLastCalledWith(42); disposeOf(subDelayed); expect(emitter).toBe(defaultEmitter); }); test('delayUnsubscribe rx', () => { const receiver = vi.fn(); const defaultEmitter = () => undefined; let emitter: SubscriberFn<number> = defaultEmitter; const resetEmitter = vi.fn(() => (emitter = defaultEmitter)); expect(emitter).toBe(defaultEmitter); const source: SubscribeFn<number> = (subscriber: SubscriberLike<number>) => { emitter = toSubscriberFn(subscriber); return createDisposable(resetEmitter); }; const sub = createSubscribable<number>(source); // Since there haven't been any subscribers, do not expect the emitter to change. expect(emitter).toBe(defaultEmitter); const dispose1 = sub.subscribe(receiver); expect(emitter).not.toBe(defaultEmitter); // There should be a new emitter. expect(emitter).not.toBe(defaultEmitter); disposeOf(dispose1); // Expect the emitter to be restored. expect(emitter).toBe(defaultEmitter); const subDelayed = rx(sub, delayUnsubscribe(10000)); // Expect the emitter to still be the default. expect(emitter).toBe(defaultEmitter); const dispose2 = subDelayed.subscribe(receiver); // There should be a new emitter. expect(emitter).not.toBe(defaultEmitter); const emitter2 = emitter; emitter(42); expect(receiver).toHaveBeenLastCalledWith(42); disposeOf(dispose2); // The emitter should still be emitter2; expect(emitter).toBe(emitter2); emitter(27); expect(receiver).toHaveBeenLastCalledWith(42); disposeOf(subDelayed); expect(emitter).toBe(defaultEmitter); }); }); ```
/content/code_sandbox/packages/client/src/Subscribables/operators/delayUnsubscribe.test.ts
xml
2016-05-16T10:42:22
2024-08-16T02:29:06
vscode-spell-checker
streetsidesoftware/vscode-spell-checker
1,377
817
```xml <controls:CorePage x:Class="Telegram.Views.Authorization.AuthorizationEmailAddressPage" xmlns="path_to_url" xmlns:x="path_to_url" xmlns:local="using:Telegram.Views" xmlns:common="using:Telegram.Common" xmlns:controls="using:Telegram.Controls" xmlns:muxc="using:Microsoft.UI.Xaml.Controls" xmlns:d="path_to_url" xmlns:mc="path_to_url" Loaded="OnLoaded" mc:Ignorable="d"> <Page.Transitions> <TransitionCollection> <NavigationThemeTransition> <SlideNavigationTransitionInfo Effect="FromRight" /> </NavigationThemeTransition> </TransitionCollection> </Page.Transitions> <Grid Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="40" /> <RowDefinition /> </Grid.RowDefinitions> <StackPanel x:Name="ContentPanel" VerticalAlignment="Center" Padding="12,20" Margin="0,-80,0,0" MaxWidth="360" Grid.Row="1"> <controls:AnimatedImage FrameSize="160,160" DecodeFrameType="Logical" Source="ms-appx:///Assets/Animations/AuthorizationStateWaitEmailAddress.tgs" AutoPlay="True" LoopCount="1" IsCachingEnabled="False" Width="160" Height="160" /> <TextBlock x:Name="TitleLabel" Text="{CustomResource AddEmailTitle}" Style="{StaticResource TitleTextBlockStyle}" TextAlignment="Center" /> <TextBlock Text="{CustomResource AddEmailSubtitle}" Style="{StaticResource BodyTextBlockStyle}" TextAlignment="Center" Padding="0,8,0,16" /> <TextBox x:Name="PrimaryInput" Text="{x:Bind ViewModel.Address, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" KeyDown="PrimaryInput_KeyDown" Margin="0,12,0,4" InputScope="EmailNameOrAddress" PlaceholderText="{CustomResource YourEmail}" /> <muxc:ProgressBar IsIndeterminate="{x:Bind ViewModel.IsLoading, Mode=OneWay}" Background="Transparent" /> <Button x:Name="NextButton" Content="{CustomResource OK}" Command="{x:Bind ViewModel.SendCommand}" Style="{StaticResource AccentButtonStyle}" HorizontalAlignment="Stretch" Margin="0,4,0,8" /> </StackPanel> <controls:VersionLabel VerticalAlignment="Bottom" HorizontalAlignment="Center" Grid.Row="1" /> <Border x:Name="TitleBar" Background="Transparent" /> <controls:BackButton x:Name="Back" /> </Grid> </controls:CorePage> ```
/content/code_sandbox/Telegram/Views/Authorization/AuthorizationEmailAddressPage.xaml
xml
2016-05-23T09:03:33
2024-08-16T16:17:48
Unigram
UnigramDev/Unigram
3,744
596
```xml import { __, Button, DataWithLoader, Icon, ModalTrigger, router, Tip, Wrapper, SidebarList } from "@erxes/ui/src"; import { Header } from "@erxes/ui-settings/src/styles"; import { isEnabled } from "@erxes/ui/src/utils/core"; import React from "react"; import CategoryForm from "../../containers/carCategory/CategoryForm"; import SegmentFilter from "../../containers/SegmentFilter"; import TagFilter from "../../containers/TagFilter"; import { ICarCategory } from "../../types"; import CollapsibleList from "@erxes/ui/src/components/collapsibleList/CollapsibleList"; import { useNavigate, useLocation } from "react-router-dom"; type Props = { queryParams: any; refetch: any; remove: (carCategoryId: string) => void; carCategories: ICarCategory[]; totalCount: number; loading: boolean; }; const { Section } = Wrapper.Sidebar; const CategoryList = (props: Props) => { const { queryParams, remove, carCategories, totalCount, loading } = props; const location = useLocation(); const navigate = useNavigate(); const clearCategoryFilter = () => { router.setParams(navigate, location, { categoryId: null }); }; const renderFormTrigger = ( trigger: React.ReactNode, category?: ICarCategory ) => { const content = props => ( <CategoryForm {...props} category={category} categories={carCategories} /> ); return ( <ModalTrigger title="Add category" trigger={trigger} content={content} /> ); }; const renderEditAction = (category: ICarCategory) => { const trigger = ( <Button btnStyle="link"> <Tip text={__("Edit")} placement="bottom"> <Icon icon="edit" /> </Tip> </Button> ); return renderFormTrigger(trigger, category); }; const renderRemoveAction = (category: ICarCategory) => { return ( <Button btnStyle="link" onClick={remove.bind(null, category._id)}> <Tip text={__("Remove")} placement="bottom"> <Icon icon="cancel-1" /> </Tip> </Button> ); }; const handleClick = categoryId => { router.setParams(navigate, location, { categoryId: categoryId }); router.removeParams(navigate, location, "page"); }; const renderContent = () => { return ( <SidebarList> <CollapsibleList items={carCategories} editAction={renderEditAction} removeAction={renderRemoveAction} loading={loading} queryParams={queryParams} queryParamName="categoryId" treeView={true} keyCount="carCount" onClick={handleClick} /> </SidebarList> ); }; const renderCategoryList = () => { return ( <DataWithLoader data={renderContent()} loading={loading} count={totalCount} emptyText="There is no car category" emptyIcon="folder-2" size="small" /> ); }; const renderCategoryHeader = () => { const trigger = ( <Button btnStyle="success" uppercase={false} icon="plus-circle" block={true} > Add category </Button> ); return ( <> <Header>{renderFormTrigger(trigger)}</Header> <Section.Title> {__("Categories")} <Section.QuickButtons> {router.getParam(location, "categoryId") && ( <a href="#cancel" tabIndex={0} onClick={clearCategoryFilter}> <Tip text={__("Clear filter")} placement="bottom"> <Icon icon="times-circle" /> </Tip> </a> )} </Section.QuickButtons> </Section.Title> </> ); }; return ( <> {renderCategoryHeader()} {renderCategoryList()} <SegmentFilter loadingMainQuery={loading} /> <TagFilter /> </> ); }; export default CategoryList; ```
/content/code_sandbox/packages/plugin-cars-ui/src/components/carCategory/CategoryList.tsx
xml
2016-11-11T06:54:50
2024-08-16T10:26:06
erxes
erxes/erxes
3,479
881
```xml <?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11542" systemVersion="16B2555" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="WcY-qb-h1c"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11524"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--Navigation Controller--> <scene sceneID="Y4f-fz-n2F"> <objects> <navigationController automaticallyAdjustsScrollViewInsets="NO" id="WcY-qb-h1c" sceneMemberID="viewController"> <toolbarItems/> <navigationBar key="navigationBar" contentMode="scaleToFill" id="7iS-cS-hhf"> <rect key="frame" x="0.0" y="0.0" width="320" height="44"/> <autoresizingMask key="autoresizingMask"/> </navigationBar> <nil name="viewControllers"/> <connections> <segue destination="YVe-4b-3rP" kind="relationship" relationship="rootViewController" id="5Ce-Ni-YpM"/> </connections> </navigationController> <placeholder placeholderIdentifier="IBFirstResponder" id="TPT-xF-Ac2" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="437" y="408"/> </scene> <!--Laps--> <scene sceneID="a6N-Ca-nv4"> <objects> <viewController storyboardIdentifier="ViewController" id="YVe-4b-3rP" customClass="ViewController" customModule="RxRealm_Example" customModuleProvider="target" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="JJ0-TM-QJn"/> <viewControllerLayoutGuide type="bottom" id="AIK-tK-GZH"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="ZAV-fX-81n"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="grouped" separatorStyle="default" rowHeight="44" sectionHeaderHeight="18" sectionFooterHeight="18" translatesAutoresizingMaskIntoConstraints="NO" id="qxX-wD-rRB"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/> <prototypes> <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="Cell" textLabel="ijb-6x-RWc" style="IBUITableViewCellStyleDefault" id="v8l-Hj-YG1"> <rect key="frame" x="0.0" y="55.5" width="375" height="44"/> <autoresizingMask key="autoresizingMask"/> <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="v8l-Hj-YG1" id="vN7-1S-thk"> <rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/> <autoresizingMask key="autoresizingMask"/> <subviews> <label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="ijb-6x-RWc"> <rect key="frame" x="15" y="0.0" width="345" height="43.5"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/> <fontDescription key="fontDescription" type="system" pointSize="16"/> <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <nil key="highlightedColor"/> </label> </subviews> </tableViewCellContentView> </tableViewCell> </prototypes> <connections> <outlet property="dataSource" destination="YVe-4b-3rP" id="qj4-kp-ElX"/> <outlet property="delegate" destination="YVe-4b-3rP" id="fu2-km-rcd"/> </connections> </tableView> </subviews> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <constraints> <constraint firstItem="qxX-wD-rRB" firstAttribute="leading" secondItem="ZAV-fX-81n" secondAttribute="leading" id="1aU-PO-R9K"/> <constraint firstItem="AIK-tK-GZH" firstAttribute="top" secondItem="qxX-wD-rRB" secondAttribute="bottom" id="F5G-hJ-0eb"/> <constraint firstItem="qxX-wD-rRB" firstAttribute="top" secondItem="ZAV-fX-81n" secondAttribute="top" id="g6g-na-0Ni"/> <constraint firstAttribute="trailing" secondItem="qxX-wD-rRB" secondAttribute="trailing" id="up0-J9-hv1"/> </constraints> </view> <navigationItem key="navigationItem" title="Laps" id="jFi-RK-D49"> <barButtonItem key="leftBarButtonItem" title="Add 2 Items" id="p1A-1o-I0K"/> <barButtonItem key="rightBarButtonItem" title="Tick" id="uD5-Ry-VOl"/> </navigationItem> <connections> <outlet property="addTwoItemsButton" destination="p1A-1o-I0K" id="PMh-Po-uvs"/> <outlet property="tableView" destination="qxX-wD-rRB" id="tPk-dL-JBY"/> <outlet property="tickItemButton" destination="uD5-Ry-VOl" id="UC9-Vn-R9b"/> </connections> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="1kG-gj-JQg" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="1428" y="408"/> </scene> </scenes> </document> ```
/content/code_sandbox/Examples/RxRealmDemo-iOS/Base.lproj/Main.storyboard
xml
2016-04-19T10:53:02
2024-08-16T13:25:09
RxRealm
RxSwiftCommunity/RxRealm
1,153
1,676
```xml <?xml version="1.0" encoding="utf-8"?> <WixLocalization Culture="de-de" xmlns="path_to_url"> <!-- See path_to_url --> <String Id="LocaleId">1031</String> <String Id="WelcomeDlgDescription">Dieser Installationsassistent wird [ProductName] auf Ihrem Computer installieren.</String> <String Id="InstallDirDlgDescription">Whlen Sie einen anderen Installationsort oder klicken Sie auf Weiter zum installieren.</String> <String Id="MajorUpgrade_DowngradeErrorMessage">Eine neuere Version von [ProductName] ist bereits installiert. Der Installationsassistent wird jetzt geschlossen.</String> <!-- References like [ProductName] or $(var.ProductName) don't seem to work in Title attributes --> <String Id="NodeRuntime_Title">Node.js-Laufzeitumgebung</String> <String Id="NodeRuntime_Description">Installation der [ProductName]-Laufzeitumgebung (node.exe).</String> <String Id="NodeEtwSupport_Title">Event Tracing (ETW)</String> <String Id="NodeEtwSupport_Description">Installiert Untersttzung fr Event Tracing (ETW)-Events, generiert von [ProductName].</String> <String Id="npm_Title">npm-Paketmanager</String> <String Id="npm_Description">Installiert npm, den empfohlenen Paketmanager fr [ProductName].</String> <String Id="DocumentationShortcuts_Title">Link zur Online-Dokumentation</String> <String Id="DocumentationShortcuts_Description">Fgt Startmen-Eintrge zur Online-Dokumentation von [ProductName] [FullVersion] und zur [ProductName]-Website hinzu.</String> <String Id="EnvironmentPath_Title">Hinzufgen zu PATH</String> <String Id="EnvironmentPath_Description">Fgt [ProductName], npm und globale durch npm installierte Module zur PATH-Umgebungsvariable hinzu.</String> <String Id="EnvironmentPathNode_Title">Node.js und npm</String> <String Id="EnvironmentPathNode_Description">Fgt [ProductName] und npm (falls installiert) zur PATH-Umgebungsvariable hinzu.</String> <String Id="EnvironmentPathNpmModules_Title">npm-Module</String> <String Id="EnvironmentPathNpmModules_Description">Fgt globale durch npm installierte Module zur PATH-Umgebungsvariable hinzu. Diese Option funktioniert nur fr den aktuellen Benutzer, andere Benutzer mssen ihre PATH-Umgebungsvariable selbst manuell aktualisieren.</String> <!-- References like [ProductName] are not resolved for Property tags --> <String Id="WIXUI_EXITDIALOGOPTIONALTEXT">Node.js wurde erfolgreich installiert.</String> </WixLocalization> ```
/content/code_sandbox/lts/tools/msvs/msi/i18n/de-de.wxl
xml
2016-10-10T12:09:49
2024-08-11T15:13:17
node-packer
pmq20/node-packer
3,069
598
```xml /* * Wire * * This program is free software: you can redistribute it and/or modify * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * along with this program. If not, see path_to_url * */ export type ConfigGeneratorParams = { env: string; urls: { base: string; api: string; ws: string; }; commit: string; version: string; }; ```
/content/code_sandbox/server/config/config.types.ts
xml
2016-07-21T15:34:05
2024-08-16T11:40:13
wire-webapp
wireapp/wire-webapp
1,125
132
```xml /* eslint global-require: 0 */ import utf7 from 'utf7'; import { Model, AttributeValues } from './model'; import * as Attributes from '../attributes'; import { localized } from '../../intl'; // We look for a few standard categories and display them in the Mailboxes // portion of the left sidebar. Note that these may not all be present on // a particular account. const ToObject = arr => { return arr.reduce((o, v) => { o[v] = v; return o; }, {}); }; const StandardRoleMap = ToObject([ 'inbox', 'important', 'snoozed', 'sent', 'drafts', 'all', 'spam', 'archive', 'trash', ]); const LockedRoleMap = ToObject(['sent', 'drafts']); const HiddenRoleMap = ToObject([ 'sent', 'drafts', 'all', 'archive', 'starred', 'important', 'snoozed', '[Mailspring]', ]); /* Why not just call localized(cat.role)? We want to hardcode each of the localized(xxx) calls so that a static analysis can identify all strings that are passed to localize(). */ const LocalizedStringForRole = { sent: localized('Sent Mail'), inbox: localized('Inbox'), important: localized('Important'), snoozed: localized('Snoozed'), drafts: localized('Drafts'), all: localized('All Mail'), spam: localized('Spam'), archive: localized('Archive'), trash: localized('Trash'), }; /** Private: This abstract class has only two concrete implementations: - `Folder` - `Label` See the equivalent models for details. Folders and Labels have different semantics. The `Category` class only exists to help DRY code where they happen to behave the same ## Attributes `role`: {AttributeString} The internal role of the label or folder. Queryable. `path`: {AttributeString} The IMAP path name of the label or folder. Queryable. Section: Models */ export class Category extends Model { get displayName() { const decoded = utf7.imap.decode(this.path) as string; for (const prefix of ['INBOX', '[Gmail]', '[Mailspring]']) { if (decoded.startsWith(prefix) && decoded.length > prefix.length + 1) { return decoded.substr(prefix.length + 1); // + delimiter } } if (decoded.startsWith('Mailspring/') || decoded.startsWith('Mailspring.')) { return decoded.substr(11); } if (decoded === 'INBOX') { return 'Inbox'; } return decoded; } /* Available for historical reasons, do not use. */ get name() { return this.role; } static attributes = { ...Model.attributes, role: Attributes.String({ queryable: true, modelKey: 'role', }), path: Attributes.String({ queryable: true, modelKey: 'path', }), localStatus: Attributes.Obj({ modelKey: 'localStatus', }), }; static Types = { Standard: 'standard', Locked: 'locked', User: 'user', Hidden: 'hidden', }; static StandardRoles = Object.keys(StandardRoleMap); static LockedRoles = Object.keys(LockedRoleMap); static HiddenRoles = Object.keys(HiddenRoleMap); static LocalizedStringForRole = LocalizedStringForRole; static categoriesSharedRole(cats) { if (!cats || cats.length === 0) { return null; } const role = cats[0].role; if (!cats.every(cat => cat.role === role)) { return null; } return role; } public role: string; public path: string; public localStatus: { syncedMinUID: number; bodiesPresent: number; bodiesWanted: number; uidnext: number; busy: boolean; }; constructor(data: AttributeValues<typeof Category.attributes>) { super(data); } displayType() { throw new Error('Base class'); } hue() { if (!this.displayName) { return 0; } let hue = 0; for (let i = 0; i < this.displayName.length; i++) { hue += this.displayName.charCodeAt(i); } hue *= 396.0 / 512.0; return hue; } isStandardCategory(forceShowImportant = undefined) { let showImportant = forceShowImportant; if (showImportant === undefined) { showImportant = AppEnv.config.get('core.workspace.showImportant'); } if (showImportant === true) { return !!StandardRoleMap[this.role]; } return !!StandardRoleMap[this.role] && this.role !== 'important'; } isLockedCategory() { return !!LockedRoleMap[this.role] || !!LockedRoleMap[this.path]; } isHiddenCategory() { return !!HiddenRoleMap[this.role] || !!HiddenRoleMap[this.path]; } isUserCategory() { return !this.isStandardCategory() && !this.isHiddenCategory(); } isArchive() { return ['all', 'archive'].includes(this.role); } } ```
/content/code_sandbox/app/src/flux/models/category.ts
xml
2016-10-13T06:45:50
2024-08-16T18:14:37
Mailspring
Foundry376/Mailspring
15,331
1,157
```xml import chalk from 'chalk'; import psl from 'psl'; import * as ERRORS from '../../util/errors-ts'; import Client from '../../util/client'; import getDomainPrice from '../../util/domains/get-domain-price'; import getDomainStatus from '../../util/domains/get-domain-status'; import getScope from '../../util/get-scope'; import param from '../../util/output/param'; import confirm from '../../util/input/confirm'; import purchaseDomain from '../../util/domains/purchase-domain'; import stamp from '../../util/output/stamp'; import { getCommandName } from '../../util/pkg-name'; import { errorToString } from '@vercel/error-utils'; type Options = {}; export default async function buy( client: Client, opts: Partial<Options>, args: string[] ) { const { output } = client; const { contextName } = await getScope(client); const skipConfirmation = !!process.env.CI; const [domainName] = args; if (!domainName) { output.error( `Missing domain name. Run ${getCommandName(`domains --help`)}` ); return 1; } const parsedDomain = psl.parse(domainName); if (parsedDomain.error) { output.error(`The provided domain name ${param(domainName)} is invalid`); return 1; } const { domain: rootDomain, subdomain } = parsedDomain; if (subdomain || !rootDomain) { output.error( `Invalid domain name "${domainName}". Run ${getCommandName( `domains --help` )}` ); return 1; } const availableStamp = stamp(); const [domainPrice, renewalPrice] = await Promise.all([ getDomainPrice(client, domainName), getDomainPrice(client, domainName, 'renewal'), ]); if (domainPrice instanceof Error) { output.prettyError(domainPrice); return 1; } if (renewalPrice instanceof Error) { output.prettyError(renewalPrice); return 1; } if (!(await getDomainStatus(client, domainName)).available) { output.error( `The domain ${param(domainName)} is ${chalk.underline( 'unavailable' )}! ${availableStamp()}` ); return 1; } const { period, price } = domainPrice; output.log( `The domain ${param(domainName)} is ${chalk.underline( 'available' )} to buy under ${chalk.bold(contextName)}! ${availableStamp()}` ); let autoRenew; if (skipConfirmation) { autoRenew = true; } else { if ( !(await confirm( client, `Buy now for ${chalk.bold(`$${price}`)} (${`${period}yr${ period > 1 ? 's' : '' }`})?`, false )) ) { return 0; } autoRenew = await confirm( client, renewalPrice.period === 1 ? `Auto renew yearly for ${chalk.bold(`$${price}`)}?` : `Auto renew every ${renewalPrice.period} years for ${chalk.bold( `$${price}` )}?`, true ); } let buyResult; const purchaseStamp = stamp(); output.spinner('Purchasing'); try { buyResult = await purchaseDomain(client, domainName, price, autoRenew); } catch (err: unknown) { output.error( 'An unexpected error occurred while purchasing your domain. Please try again later.' ); output.debug(`Server response: ${errorToString(err)}`); return 1; } output.stopSpinner(); if (buyResult instanceof ERRORS.SourceNotFound) { output.error( `Could not purchase domain. Please add a payment method using the dashboard.` ); return 1; } if (buyResult instanceof ERRORS.UnsupportedTLD) { output.error( `The TLD for domain name ${buyResult.meta.domain} is not supported.` ); return 1; } if (buyResult instanceof ERRORS.InvalidDomain) { output.error(`The domain ${buyResult.meta.domain} is not valid.`); return 1; } if (buyResult instanceof ERRORS.DomainNotAvailable) { output.error(`The domain ${buyResult.meta.domain} is not available.`); return 1; } if (buyResult instanceof ERRORS.DomainServiceNotAvailable) { output.error( `The domain purchase service is not available. Please try again later.` ); return 1; } if (buyResult instanceof ERRORS.UnexpectedDomainPurchaseError) { output.error(`An unexpected error happened while performing the purchase.`); return 1; } if (buyResult instanceof ERRORS.DomainPaymentError) { output.error(`Your card was declined.`); return 1; } if (buyResult.pending) { output.success( `Domain ${param(domainName)} order was submitted ${purchaseStamp()}` ); output.note( `Your domain is processing and will be available once the order is completed.` ); output.print( ` An email will be sent upon completion for you to start using your new domain.\n` ); } else { output.success(`Domain ${param(domainName)} purchased ${purchaseStamp()}`); if (!buyResult.verified) { output.note( `Your domain is not fully configured yet so it may appear as not verified.` ); output.print( ` It might take a few minutes, but you will get an email as soon as it is ready.\n` ); } else { output.note( `You may now use your domain as an alias to your deployments. Run ${getCommandName( `alias --help` )}` ); } } return 0; } ```
/content/code_sandbox/packages/cli/src/commands/domains/buy.ts
xml
2016-09-09T01:12:08
2024-08-16T17:39:45
vercel
vercel/vercel
12,545
1,287
```xml import { IterableX } from '../../iterable/iterablex.js'; import { min } from '../../iterable/min.js'; import { ExtremaOptions } from '../../iterable/extremaoptions.js'; /** * @ignore */ export function minProto<TSource, TResult = TSource>( this: IterableX<TSource>, options?: ExtremaOptions<TSource, TResult> ): TResult { return min(this, options); } IterableX.prototype.min = minProto; declare module '../../iterable/iterablex' { interface IterableX<T> { min: typeof minProto; } } ```
/content/code_sandbox/src/add/iterable-operators/min.ts
xml
2016-02-22T20:04:19
2024-08-09T18:46:41
IxJS
ReactiveX/IxJS
1,319
123
```xml import classNames from 'classnames'; import React, { ReactNode, useState } from 'react'; import styles from '../index.module.css'; export type TogglerItem = { component?: ReactNode; icon: ReactNode; tooltipText: string; }; export type TogglerHeaderItemProps = JSX.IntrinsicElements['span'] & TogglerItem & { active: boolean }; export function TogglerHeaderItem({ active, icon, tooltipText, ...rest }: TogglerHeaderItemProps) { return ( <span {...rest} className={classNames( styles.tooltip, styles.item, active && styles.active, )} > {tooltipText && ( <span className={styles['tooltip-text']}>{tooltipText}</span> )} {icon} </span> ); } export type TogglerHeaderProps<T extends TogglerItem> = { activeToggle: number; items: T[]; onClick: (tab: number) => () => void; }; export function TogglerHeader<T extends TogglerItem>({ activeToggle, items, onClick, }: TogglerHeaderProps<T>) { return ( <section className={classNames(styles.toggler, styles.header)}> {items.map((item, key) => { return ( <TogglerHeaderItem active={activeToggle === key} key={key} onClick={onClick(key)} {...item} /> ); })} </section> ); } export type TogglerProps<T extends TogglerItem> = { items: T[]; }; export function Toggler<T extends TogglerItem>({ items }: TogglerProps<T>) { const [activeToggle, setState] = useState(0); const toggleClick = (toggle: number) => () => { setState(toggle); }; return ( <> <TogglerHeader activeToggle={activeToggle} items={items} onClick={toggleClick} /> <section>{items[activeToggle].component}</section> </> ); } ```
/content/code_sandbox/website/components/Toggler.tsx
xml
2016-05-10T13:08:50
2024-08-13T11:27:18
uniforms
vazco/uniforms
1,934
439
```xml /* * @license Apache-2.0 * * * * path_to_url * * Unless required by applicable law or agreed to in writing, software * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ // TypeScript Version: 4.1 /// <reference types="@stdlib/types"/> import { NumericArray } from '@stdlib/types/array'; /** * Interface describing `stdevpn`. */ interface Routine { /** * Computes the standard deviation of a strided array using a two-pass algorithm. * * @param N - number of indexed elements * @param correction - degrees of freedom adjustment * @param x - input array * @param stride - stride length * @returns standard deviation * * @example * var x = [ 1.0, -2.0, 2.0 ]; * * var v = stdevpn( x.length, 1, x, 1 ); * // returns ~2.0817 */ ( N: number, correction: number, x: NumericArray, stride: number ): number; /** * Computes the standard deviation of a strided array using a two-pass algorithm and alternative indexing semantics. * * @param N - number of indexed elements * @param correction - degrees of freedom adjustment * @param x - input array * @param stride - stride length * @param offset - starting index * @returns standard deviation * * @example * var x = [ 1.0, -2.0, 2.0 ]; * * var v = stdevpn.ndarray( x.length, 1, x, 1, 0 ); * // returns ~2.0817 */ ndarray( N: number, correction: number, x: NumericArray, stride: number, offset: number ): number; } /** * Computes the standard deviation of a strided array using a two-pass algorithm. * * @param N - number of indexed elements * @param correction - degrees of freedom adjustment * @param x - input array * @param stride - stride length * @returns standard deviation * * @example * var x = [ 1.0, -2.0, 2.0 ]; * * var v = stdevpn( x.length, 1, x, 1 ); * // returns ~2.0817 * * @example * var x = [ 1.0, -2.0, 2.0 ]; * * var v = stdevpn.ndarray( x.length, 1, x, 1, 0 ); * // returns ~2.0817 */ declare var stdevpn: Routine; // EXPORTS // export = stdevpn; ```
/content/code_sandbox/lib/node_modules/@stdlib/stats/base/stdevpn/docs/types/index.d.ts
xml
2016-03-24T04:19:52
2024-08-16T09:03:19
stdlib
stdlib-js/stdlib
4,266
608
```xml import { $ } from '../$.js'; import { unique } from '../functions/unique.js'; import { JQ } from '../shared/core.js'; import { isElement, eachArray } from '../shared/helper.js'; import './each.js'; import './is.js'; import type { Selector } from '../shared/helper.js'; declare module '../shared/core.js' { // eslint-disable-next-line @typescript-eslint/no-unused-vars interface JQ<T = HTMLElement> { /** * * @param selector CSS * @example ```js // #box $('#box').children() ``` * @example ```js // #box .box $('#box').children('.box') ``` */ children(selector?: Selector): this; } } $.fn.children = function (this: JQ, selector?: Selector): JQ { const children: HTMLElement[] = []; this.each((_, element) => { eachArray(element.childNodes, (childNode) => { if (!isElement(childNode)) { return; } if (!selector || $(childNode).is(selector)) { children.push(childNode as HTMLElement); } }); }); return new JQ(unique(children)); }; ```
/content/code_sandbox/packages/jq/src/methods/children.ts
xml
2016-07-11T17:39:02
2024-08-16T07:12:34
mdui
zdhxiong/mdui
4,077
264
```xml export const getDateUint8Array = ( year: number, month: number, day: number, hour: number, minute: number, second: number ) => { const yearFirstByte = year >> 8 const yearSecondByte = year - 2 ** 16 return new Uint8Array([yearFirstByte, yearSecondByte, month, day, hour, minute, second]) } ```
/content/code_sandbox/example/src/utils/getDateUint8Array.ts
xml
2016-07-27T10:57:27
2024-08-14T16:51:53
react-native-ble-plx
dotintent/react-native-ble-plx
3,006
93
```xml export * from './components/StackedBarChart/index'; ```
/content/code_sandbox/packages/react-charting/src/StackedBarChart.ts
xml
2016-06-06T15:03:44
2024-08-16T18:49:29
fluentui
microsoft/fluentui
18,221
13
```xml import { Component, OnInit } from '@angular/core'; import { Code } from '@domain/code'; interface City { name: string; code: string; } @Component({ selector: 'dropdown-loading-state-demo', template: ` <app-docsectiontext> <p>Loading state can be used <i>loading</i> property.</p> </app-docsectiontext> <div class="card flex justify-content-center"> <p-dropdown [options]="cities" [(ngModel)]="selectedCity" [loading]="true" optionLabel="name" placeholder="Loading..." /> </div> <app-code [code]="code" selector="dropdown-loading-state-demo"></app-code> ` }) export class LoadingStateDoc implements OnInit { cities: City[]; selectedCity: City | undefined; ngOnInit() { this.cities = [ { name: 'New York', code: 'NY' }, { name: 'Rome', code: 'RM' }, { name: 'London', code: 'LDN' }, { name: 'Istanbul', code: 'IST' }, { name: 'Paris', code: 'PRS' } ]; } code: Code = { basic: `<p-dropdown [options]="cities" [(ngModel)]="selectedCity" [loading]="true" optionLabel="name" placeholder="Select a City" />`, html: `<div class="card flex justify-content-center"> <p-dropdown [options]="cities" [(ngModel)]="selectedCity" [loading]="true" optionLabel="name" placeholder="Select a City" /> </div>`, typescript: `import { Component, OnInit } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { DropdownModule } from 'primeng/dropdown'; interface City { name: string; code: string; } @Component({ selector: 'dropdown-loading-state-demo', templateUrl: './dropdown-loading-state-demo.html', standalone: true, imports: [FormsModule, DropdownModule] }) export class DropdownLoadingStateDemo implements OnInit { cities: City[] | undefined; selectedCity: City | undefined; ngOnInit() { this.cities = [ { name: 'New York', code: 'NY' }, { name: 'Rome', code: 'RM' }, { name: 'London', code: 'LDN' }, { name: 'Istanbul', code: 'IST' }, { name: 'Paris', code: 'PRS' } ]; } }` }; } ```
/content/code_sandbox/src/app/showcase/doc/dropdown/loadingstatedoc.ts
xml
2016-01-16T09:23:28
2024-08-16T19:58:20
primeng
primefaces/primeng
9,969
567
```xml // See LICENSE in the project root for license information. import type { IMinifierConnection } from '../types'; let terserVersion: string = '1.0.0'; jest.mock('terser/package.json', () => { return { get version(): string { return terserVersion; } }; }); describe('WorkerPoolMinifier', () => { it('Includes terserOptions in config hash', async () => { const { WorkerPoolMinifier } = await import('../WorkerPoolMinifier'); // eslint-disable-next-line @typescript-eslint/no-redeclare type WorkerPoolMinifier = typeof WorkerPoolMinifier.prototype; const minifier1: WorkerPoolMinifier = new WorkerPoolMinifier({ terserOptions: { ecma: 5 } }); const minifier2: WorkerPoolMinifier = new WorkerPoolMinifier({ terserOptions: { ecma: 2015 } }); const connection1: IMinifierConnection = await minifier1.connectAsync(); await connection1.disconnectAsync(); const connection2: IMinifierConnection = await minifier2.connectAsync(); await connection2.disconnectAsync(); expect(connection1.configHash).toMatchSnapshot('ecma5'); expect(connection2.configHash).toMatchSnapshot('ecma2015'); expect(connection1.configHash !== connection2.configHash); }); it('Includes terser package version in config hash', async () => { const { WorkerPoolMinifier } = await import('../WorkerPoolMinifier'); // eslint-disable-next-line @typescript-eslint/no-redeclare type WorkerPoolMinifier = typeof WorkerPoolMinifier.prototype; terserVersion = '5.9.1'; const minifier1: WorkerPoolMinifier = new WorkerPoolMinifier({}); terserVersion = '5.16.2'; const minifier2: WorkerPoolMinifier = new WorkerPoolMinifier({}); const connection1: IMinifierConnection = await minifier1.connectAsync(); await connection1.disconnectAsync(); const connection2: IMinifierConnection = await minifier2.connectAsync(); await connection2.disconnectAsync(); expect(connection1.configHash).toMatchSnapshot('terser-5.9.1'); expect(connection2.configHash).toMatchSnapshot('terser-5.16.1'); expect(connection1.configHash !== connection2.configHash); }); }); ```
/content/code_sandbox/libraries/module-minifier/src/test/WorkerPoolMinifier.test.ts
xml
2016-09-30T00:28:20
2024-08-16T18:54:35
rushstack
microsoft/rushstack
5,790
514
```xml <?xml version="1.0" encoding="UTF-8"?> <definitions id="definitions" xmlns="path_to_url" xmlns:activiti="path_to_url" targetNamespace="Examples"> <process id=your_sha256_hash> <startEvent id="theStart" /> <sequenceFlow id="flow1" sourceRef="theStart" targetRef="serviceTask" /> <serviceTask id="serviceTask" activiti:class="org.flowable.engine.test.bpmn.event.error.ThrowBpmnErrorDelegate"> <multiInstanceLoopCharacteristics isSequential="false"> <loopCardinality>3</loopCardinality> </multiInstanceLoopCharacteristics> </serviceTask> <boundaryEvent id="catchError" attachedToRef="serviceTask"> <errorEventDefinition /> </boundaryEvent> <sequenceFlow id="flow3" sourceRef="catchError" targetRef="escalatedTask" /> <userTask id="escalatedTask" name="Escalated Task" /> <sequenceFlow id="flow4" sourceRef="serviceTask" targetRef="theEnd" /> <endEvent id="theEnd" /> </process> </definitions> ```
/content/code_sandbox/modules/flowable-engine/src/test/resources/org/flowable/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorThrownByJavaDelegateOnMultiInstanceServiceTaskParallel.bpmn20.xml
xml
2016-10-13T07:21:43
2024-08-16T15:23:14
flowable-engine
flowable/flowable-engine
7,715
268
```xml import { Component } from '@angular/core'; import { MatDialogRef } from '@angular/material/dialog'; @Component({ selector: 'td-confirm-dialog', templateUrl: './confirm-dialog.component.html', styleUrls: ['./confirm-dialog.component.scss'], }) export class TdConfirmDialogComponent { title?: string; message?: string; cancelButton = 'CANCEL'; acceptButton = 'ACCEPT'; isDestructive = false; constructor(private _dialogRef: MatDialogRef<TdConfirmDialogComponent>) {} cancel(): void { this._dialogRef.close(false); } accept(): void { this._dialogRef.close(true); } } ```
/content/code_sandbox/libs/angular/dialogs/src/confirm-dialog/confirm-dialog.component.ts
xml
2016-07-11T23:30:52
2024-08-15T15:20:45
covalent
Teradata/covalent
2,228
136
```xml import { IdentityAssigner } from "./identity.assigner"; import { Node, NodeSocket } from "@openremote/model"; export class CopyMachine { public static copy(node: Node): Node { const minimalNode: Node = {}; minimalNode.inputs = (node.inputs || []).map((i: NodeSocket) => { return { name: i.name, type: i.type }; }); minimalNode.internals = node.internals || []; minimalNode.name = node.name; minimalNode.displayCharacter = node.displayCharacter; minimalNode.outputs = (node.outputs || []).map((i) => { return { name: i.name, type: i.type }; }); minimalNode.type = node.type; minimalNode.position = { x: 0, y: 0 }; minimalNode.size = { x: 0, y: 0 }; const clone: Node = JSON.parse(JSON.stringify(minimalNode)); clone.id = IdentityAssigner.generateIdentity(); clone.inputs!.forEach((socket) => { socket.nodeId = clone.id; socket.id = IdentityAssigner.generateIdentity(); }); clone.outputs!.forEach((socket) => { socket.nodeId = clone.id; socket.id = IdentityAssigner.generateIdentity(); }); return clone; } } ```
/content/code_sandbox/ui/component/or-rules/src/flow-viewer/node-structure/copy.machine.ts
xml
2016-02-03T11:14:02
2024-08-16T12:45:50
openremote
openremote/openremote
1,184
280