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
<Page x:Class="Microsoft.Toolkit.Uwp.SampleApp.SamplePages.SystemInformationPage"
xmlns="path_to_url"
xmlns:x="path_to_url"
xmlns:d="path_to_url"
xmlns:local="using:Microsoft.Toolkit.Uwp.SampleApp.SamplePages"
xmlns:mc="path_to_url"
mc:Ignorable="d">
<Grid>
<ScrollViewer HorizontalScrollMode="Disabled"
VerticalScrollBarVisibility="Auto"
VerticalScrollMode="Auto">
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Center">
<StackPanel x:Name="Stack0"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Application name:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind ApplicationName}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack1"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Application version:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind ApplicationVersion}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack2"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="User's culture:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind Culture}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack3"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Operating system:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind OperatingSystem}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack4"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Operating system architecture:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind OperatingSystemArchitecture}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack5"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Operating system version:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind OperatingSystemVersion}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack6"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Device family:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind DeviceFamily}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack7"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Device model:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind DeviceModel}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack8"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Device manufacturer:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind DeviceManufacturer}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack9"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Available memory (MB):"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind AvailableMemory}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack10"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Is first use:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind IsFirstUse}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack11"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Is app updated:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind IsAppUpdated}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack12"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="First version installed:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind FirstVersionInstalled}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack13"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Previous version installed:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind PreviousVersionInstalled}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack14"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="First use time:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind FirstUseTime}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack15"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Launch time:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind LaunchTime}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack16"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Last launch time:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind LastLaunchTime}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack17"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Last reset time:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind LastResetTime, Mode=OneWay}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack18"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Current launch count:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind LaunchCount, Mode=OneWay}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack19"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="Total launch count:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind TotalLaunchCount}"
TextWrapping="Wrap" />
</StackPanel>
<StackPanel x:Name="Stack20"
Margin="10"
Orientation="Horizontal">
<TextBlock FontSize="18"
FontWeight="Bold"
Text="App uptime:"
TextWrapping="Wrap" />
<TextBlock Margin="20,0"
FontSize="18"
Text="{x:Bind AppUptime}"
TextWrapping="Wrap" />
</StackPanel>
</StackPanel>
</ScrollViewer>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="Full">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="600" />
</VisualState.StateTriggers>
</VisualState>
<VisualState x:Name="Small">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="0" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="Stack0.Orientation" Value="Vertical" />
<Setter Target="Stack1.Orientation" Value="Vertical" />
<Setter Target="Stack2.Orientation" Value="Vertical" />
<Setter Target="Stack3.Orientation" Value="Vertical" />
<Setter Target="Stack4.Orientation" Value="Vertical" />
<Setter Target="Stack5.Orientation" Value="Vertical" />
<Setter Target="Stack6.Orientation" Value="Vertical" />
<Setter Target="Stack7.Orientation" Value="Vertical" />
<Setter Target="Stack8.Orientation" Value="Vertical" />
<Setter Target="Stack9.Orientation" Value="Vertical" />
<Setter Target="Stack10.Orientation" Value="Vertical" />
<Setter Target="Stack11.Orientation" Value="Vertical" />
<Setter Target="Stack12.Orientation" Value="Vertical" />
<Setter Target="Stack13.Orientation" Value="Vertical" />
<Setter Target="Stack14.Orientation" Value="Vertical" />
<Setter Target="Stack15.Orientation" Value="Vertical" />
<Setter Target="Stack16.Orientation" Value="Vertical" />
<Setter Target="Stack17.Orientation" Value="Vertical" />
<Setter Target="Stack18.Orientation" Value="Vertical" />
<Setter Target="Stack19.Orientation" Value="Vertical" />
<Setter Target="Stack20.Orientation" Value="Vertical" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</Page>
``` | /content/code_sandbox/Microsoft.Toolkit.Uwp.SampleApp/SamplePages/SystemInformation/SystemInformationPage.xaml | xml | 2016-06-17T21:29:46 | 2024-08-16T09:32:00 | WindowsCommunityToolkit | CommunityToolkit/WindowsCommunityToolkit | 5,842 | 2,419 |
```xml
import { IObservableJSON, ObservableJSON } from '@jupyterlab/observables';
describe('@jupyterlab/observables', () => {
describe('ObservableJSON', () => {
describe('#constructor()', () => {
it('should create an observable JSON object', () => {
const item = new ObservableJSON();
expect(item).toBeInstanceOf(ObservableJSON);
});
it('should accept initial values', () => {
const item = new ObservableJSON({
values: { foo: 1, bar: 'baz' }
});
expect(item).toBeInstanceOf(ObservableJSON);
});
});
describe('#toJSON()', () => {
it('should serialize the model to JSON', () => {
const item = new ObservableJSON();
item.set('foo', 1);
expect(item.toJSON()['foo']).toBe(1);
});
it('should return a copy of the data', () => {
const item = new ObservableJSON();
item.set('foo', { bar: 1 });
const value = item.toJSON();
value['bar'] = 2;
expect((item.get('foo') as any)['bar']).toBe(1);
});
});
});
describe('ObservableJSON.ChangeMessage', () => {
describe('#constructor()', () => {
it('should create a new message', () => {
const message = new ObservableJSON.ChangeMessage('jsonvalue-changed', {
key: 'foo',
type: 'add',
oldValue: 1,
newValue: 2
});
expect(message).toBeInstanceOf(ObservableJSON.ChangeMessage);
});
});
describe('#args', () => {
it('should be the args of the message', () => {
const args: IObservableJSON.IChangedArgs = {
key: 'foo',
type: 'add',
oldValue: 'ho',
newValue: 'hi'
};
const message = new ObservableJSON.ChangeMessage(
'jsonvalue-changed',
args
);
expect(message.args).toBe(args);
});
});
});
});
``` | /content/code_sandbox/packages/observables/test/observablejson.spec.ts | xml | 2016-06-03T20:09:17 | 2024-08-16T19:12:44 | jupyterlab | jupyterlab/jupyterlab | 14,019 | 443 |
```xml
import { useState, useEffect } from 'react';
type ScriptStatus = 'idle' | 'loading' | 'ready' | 'error';
// Ref: path_to_url
export function useScript(src: string): ScriptStatus {
// Keep track of script status ("idle", "loading", "ready", "error")
const [status, setStatus] = useState<ScriptStatus>(src ? 'loading' : 'idle');
useEffect(
() => {
// Allow falsy src value if waiting on other data needed for
// constructing the script URL passed to this hook.
if (!src) {
setStatus('idle');
return;
}
// Fetch existing script element by src
// It may have been added by another intance of this hook
let script: HTMLScriptElement = document.querySelector(`script[src="${src}"]`);
if (!script) {
// Create script
script = document.createElement('script');
script.src = src;
script.async = true;
script.setAttribute('data-status', 'loading');
// Add script to document body
document.body.appendChild(script);
// Store status in attribute on script
// This can be read by other instances of this hook
const setAttributeFromEvent = event => {
script.setAttribute('data-status', event.type === 'load' ? 'ready' : 'error');
};
script.addEventListener('load', setAttributeFromEvent);
script.addEventListener('error', setAttributeFromEvent);
} else {
// Grab existing script status from attribute and set to state.
setStatus(script.getAttribute('data-status') as ScriptStatus);
}
// Script event handler to update status in state
// Note: Even if the script already exists we still need to add
// event handlers to update the state for *this* hook instance.
const setStateFromEvent = event => {
setStatus(event.type === 'load' ? 'ready' : 'error');
};
// Add event listeners
script.addEventListener('load', setStateFromEvent);
script.addEventListener('error', setStateFromEvent);
// Remove event listeners on cleanup
return () => {
if (script) {
script.removeEventListener('load', setStateFromEvent);
script.removeEventListener('error', setStateFromEvent);
}
};
},
[src] // Only re-run effect if script src changes
);
return status;
}
``` | /content/code_sandbox/docs/utils/useScript.ts | xml | 2016-06-06T02:27:46 | 2024-08-16T16:41:54 | rsuite | rsuite/rsuite | 8,263 | 504 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="path_to_url">
<ItemGroup>
<Filter Include="">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
<Filter Include="\vc">
<UniqueIdentifier>{8c1bb663-d9c1-45e1-b556-287f00f87ce7}</UniqueIdentifier>
</Filter>
<Filter Include="\ltl">
<UniqueIdentifier>{dcb5545f-77e6-40a3-b5a1-095ecc58eeaf}</UniqueIdentifier>
</Filter>
<Filter Include="\ltl\objs">
<UniqueIdentifier>{0372228d-b4b3-43e6-afe3-0cf326b8323a}</UniqueIdentifier>
</Filter>
<Filter Include="\ltl\objs\x86">
<UniqueIdentifier>{5fa2c38a-86b2-4848-ab1e-ab04d5b2e53a}</UniqueIdentifier>
</Filter>
<Filter Include="\vc\WinXP">
<UniqueIdentifier>{701896c0-0079-4333-b210-05959b6cd994}</UniqueIdentifier>
</Filter>
<Filter Include="\vc\WinXP\x86">
<UniqueIdentifier>{a3b856d7-4c37-43e7-aa2f-41d3c442e8bc}</UniqueIdentifier>
</Filter>
<Filter Include="\ltl\x86">
<UniqueIdentifier>{7b30014f-12e3-446e-a6e4-79869428a88c}</UniqueIdentifier>
</Filter>
<Filter Include="\ltl\amd64">
<UniqueIdentifier>{a0cee9a9-1e56-4ff7-ae9b-e1edd592e15e}</UniqueIdentifier>
</Filter>
<Filter Include="\vc\Others">
<UniqueIdentifier>{c1046655-4051-4747-9111-c5584e3e333e}</UniqueIdentifier>
</Filter>
<Filter Include="\vc\x86">
<UniqueIdentifier>{61e7f4ae-68bb-42e5-8313-d44855c42809}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\vcruntime\unexpected.cpp">
<Filter>\vc</Filter>
</ClCompile>
<ClCompile Include="..\..\vcruntime\purevirt.cpp">
<Filter>\vc</Filter>
</ClCompile>
<ClCompile Include="..\..\..\frame_thunks.cpp">
<Filter>\ltl</Filter>
</ClCompile>
<ClCompile Include="..\..\..\vc_msvcrt_IAT.cpp">
<Filter>\ltl</Filter>
</ClCompile>
<ClCompile Include="..\..\..\vc_msvcrt_winxp.cpp">
<Filter>\ltl</Filter>
</ClCompile>
<ClCompile Include="..\..\vcruntime\std_type_info.cpp">
<Filter>\vc</Filter>
</ClCompile>
<ClCompile Include="..\..\vcruntime\jbcxrval.c">
<Filter>\vc\WinXP</Filter>
</ClCompile>
<ClCompile Include="..\..\..\exsup4_downlevel.cpp">
<Filter>\ltl\x86</Filter>
</ClCompile>
<ClCompile Include="..\..\..\chandler3_noexcept.cpp">
<Filter>\ltl\x86</Filter>
</ClCompile>
<ClCompile Include="..\..\..\amd64\chandler_noexcept.cpp">
<Filter>\ltl\amd64</Filter>
</ClCompile>
<ClCompile Include="..\..\vcruntime\mgdframe.cpp">
<Filter>\vc</Filter>
</ClCompile>
<ClCompile Include="..\..\vcruntime\frame.cpp">
<Filter>\vc</Filter>
</ClCompile>
<ClCompile Include="..\..\vcruntime\ehhelpers.cpp">
<Filter>\vc</Filter>
</ClCompile>
<ClCompile Include="..\..\vcruntime\uncaught_exceptions.cpp">
<Filter>\vc</Filter>
</ClCompile>
<ClCompile Include="..\..\vcruntime\risctrnsctrl.cpp">
<Filter>\vc\Others</Filter>
</ClCompile>
<ClCompile Include="..\..\i386\trnsctrl.cpp">
<Filter>\vc\x86</Filter>
</ClCompile>
<ClCompile Include="..\..\..\ptd_downlevel.cpp">
<Filter>\ltl</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="vcruntime.rc">
<Filter></Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<None Include="vcruntime.def">
<Filter></Filter>
</None>
</ItemGroup>
</Project>
``` | /content/code_sandbox/src/14.14.26428/Build/vcruntime/vcruntime.vcxproj.filters | xml | 2016-06-14T03:01:16 | 2024-08-12T19:23:19 | VC-LTL | Chuyu-Team/VC-LTL | 1,052 | 1,318 |
```xml
<Documentation>
<Docs DocId="T:UIKit.NSDataAsset">
<summary>Platform-specific data object stored in an asset catalog.</summary>
<remarks>
<para>Asset catalogs are often used for icons and images, but may be used to deliver any kind of data in a platform-specific manner.</para>
<para>Within an asset catalog, there is one folder per data object. That folder contains platform-specific data files and a <c>Contents.json</c> file that maps platform characteristics to specific datafiles. For example:</para>
<para>
<img href="~/UIKit/_images/UIKit.NSDataAsset_FolderStructure.png" alt="Image showing the folder structure." />
</para>
<para>Where <c>Contents.json</c> contains:</para>
<example>
<code lang="json"><![CDATA[
{
"info" : {
"version" : 1,
"author" : "xcode"
},
"data" : [
{
"idiom" : "iphone",
"filename" : "iphone.wav",
"universal-type-identifier" : "com.microsoft.waveform-audio"
},
{
"idiom" : "ipad",
"filename" : "ipad.wav",
"universal-type-identifier" : "com.microsoft.waveform-audio"
}
]
}
]]></code>
</example>
<para>To load an asset, call <format type="text/html"><a href="path_to_url" title="C:UIKit.NSDataAsset(String)">C:UIKit.NSDataAsset(String)</a></format> or <format type="text/html"><a href="path_to_url" title="C:UIKit.NSDataAsset(String,Foundation.NSBundle)">C:UIKit.NSDataAsset(String,Foundation.NSBundle)</a></format> passing the name of the folder. For instance:</para>
<example>
<code lang="csharp lang-csharp"><![CDATA[
var assetCatalog = new NSDataAsset ("FolderName");
var data = assetCatalog.Data;
var uti = assetCatalog.TypeIdentifier;
NSError error = null;
var player = new AVAudioPlayer (data, uti, out error);
if (player != null) { //...etc
]]></code>
</example>
<para>The appropriate datafile for the hardware device will be loaded.</para>
</remarks>
<related type="externalDocumentation" href="path_to_url">Apple documentation for <c>NSDataAsset</c></related>
</Docs>
</Documentation>
``` | /content/code_sandbox/docs/api/UIKit/NSDataAsset.xml | xml | 2016-04-20T18:24:26 | 2024-08-16T13:29:19 | xamarin-macios | xamarin/xamarin-macios | 2,436 | 559 |
```xml
/**
* This file is part of OpenMediaVault.
*
* @license path_to_url GPL Version 3
* @author Volker Theile <volker.theile@openmediavault.org>
*
* OpenMediaVault is free software: you can redistribute it and/or modify
* any later version.
*
* OpenMediaVault 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
*/
import { Component } from '@angular/core';
import { marker as gettext } from '@ngneat/transloco-keys-manager/marker';
import { FormPageConfig } from '~/app/core/components/intuition/models/form-page-config.type';
import { BaseFormPageComponent } from '~/app/pages/base-page-component';
@Component({
template: '<omv-intuition-form-page [config]="this.config"></omv-intuition-form-page>'
})
export class RsyncTaskFormPageComponent extends BaseFormPageComponent {
public config: FormPageConfig = {
request: {
service: 'Rsync',
get: {
method: 'get',
params: {
uuid: '{{ _routeParams.uuid }}'
}
},
post: {
method: 'set'
}
},
fields: [
/* eslint-disable max-len */
{
type: 'confObjUuid'
},
{
type: 'checkbox',
name: 'enable',
label: gettext('Enabled'),
value: true
},
{
type: 'select',
name: 'type',
label: gettext('Type'),
value: 'local',
store: {
data: [
['local', gettext('Local')],
['remote', gettext('Remote')]
]
}
},
{
type: 'select',
name: 'mode',
label: gettext('Mode'),
value: 'push',
store: {
data: [
['push', gettext('Push')],
['pull', gettext('Pull')]
]
},
modifiers: [
{
type: 'visible',
constraint: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' }
}
]
},
{
type: 'sharedFolderSelect',
name: 'srcsharedfolderref',
hasEmptyOption: true,
value: '',
label: gettext('Source shared folder'),
modifiers: [
{
type: 'hidden',
constraint: {
operator: 'not',
arg0: {
operator: 'or',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'local' },
arg1: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'mode' }, arg1: 'push' }
}
}
}
}
],
validators: {
requiredIf: {
operator: 'or',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'local' },
arg1: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'mode' }, arg1: 'push' }
}
}
}
},
{
type: 'textInput',
name: 'srcuri',
label: gettext('Source server'),
value: '',
hint: gettext(
'The source remote server, e.g. [USER@]HOST:SRC, [USER@]HOST::SRC or rsync://[USER@]HOST[:PORT]/SRC.'
),
modifiers: [
{
type: 'hidden',
constraint: {
operator: 'not',
arg0: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'mode' }, arg1: 'pull' }
}
}
}
],
validators: {
requiredIf: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'mode' }, arg1: 'pull' }
}
}
},
{
type: 'sharedFolderSelect',
name: 'destsharedfolderref',
hasEmptyOption: true,
value: '',
label: gettext('Destination shared folder'),
modifiers: [
{
type: 'hidden',
constraint: {
operator: 'not',
arg0: {
operator: 'or',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'local' },
arg1: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'mode' }, arg1: 'pull' }
}
}
}
}
],
validators: {
requiredIf: {
operator: 'or',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'local' },
arg1: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'mode' }, arg1: 'pull' }
}
}
}
},
{
type: 'textInput',
name: 'desturi',
label: gettext('Destination server'),
value: '',
hint: gettext(
'The destination remote server, e.g. [USER@]HOST:DEST, [USER@]HOST::DEST or rsync://[USER@]HOST[:PORT]/DEST.'
),
modifiers: [
{
type: 'hidden',
constraint: {
operator: 'not',
arg0: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'mode' }, arg1: 'push' }
}
}
}
],
validators: {
requiredIf: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'mode' }, arg1: 'push' }
}
}
},
{
type: 'select',
name: 'authentication',
label: gettext('Authentication'),
placeholder: gettext('Select an authentication mode ...'),
value: 'password',
store: {
data: [
['password', gettext('Password')],
['pubkey', gettext('Public key')]
]
},
modifiers: [
{
type: 'hidden',
constraint: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'local' }
}
]
},
{
type: 'numberInput',
name: 'sshport',
label: gettext('SSH port'),
value: 22,
modifiers: [
{
type: 'hidden',
constraint: {
operator: 'or',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'local' },
arg1: { operator: 'eq', arg0: { prop: 'authentication' }, arg1: 'password' }
}
}
],
validators: {
min: 1,
max: 65535,
requiredIf: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'authentication' }, arg1: 'pubkey' }
}
}
},
{
type: 'sshCertSelect',
name: 'sshcertificateref',
hasEmptyOption: true,
value: '',
label: gettext('SSH certificate'),
hint: gettext('The SSH certificate used for authentication.'),
modifiers: [
{
type: 'hidden',
constraint: {
operator: 'or',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'local' },
arg1: { operator: 'eq', arg0: { prop: 'authentication' }, arg1: 'password' }
}
}
],
validators: {
requiredIf: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'authentication' }, arg1: 'pubkey' }
}
}
},
{
type: 'passwordInput',
name: 'password',
label: gettext('Password'),
hint: gettext(
'The password that is used for access via rsync daemon. Note, this is not used for remote shell transport such as SSH.'
),
value: '',
autocomplete: 'new-password',
modifiers: [
{
type: 'hidden',
constraint: {
operator: 'or',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'local' },
arg1: { operator: 'eq', arg0: { prop: 'authentication' }, arg1: 'pubkey' }
}
}
],
validators: {
requiredIf: {
operator: 'and',
arg0: { operator: 'eq', arg0: { prop: 'type' }, arg1: 'remote' },
arg1: { operator: 'eq', arg0: { prop: 'authentication' }, arg1: 'password' }
}
}
},
{
type: 'textInput',
name: 'cronexprdesc',
label: gettext('Time of execution'),
disabled: true,
submitValue: false,
value: '',
modifiers: [
{
type: 'value',
typeConfig:
'{% set _minute = minute %}' +
'{% set _hour = hour %}' +
'{% set _dayofmonth = dayofmonth %}' +
'{% if everynminute %}{% set _minute %}*/{{ minute }}{% endset %}{% endif %}' +
'{% if everynhour %}{% set _hour %}*/{{ hour }}{% endset %}{% endif %}' +
'{% if everyndayofmonth %}{% set _dayofmonth %}*/{{ dayofmonth }}{% endset %}{% endif %}' +
'{{ [_minute, _hour, _dayofmonth, month, dayofweek] | join(" ") | cron2human }}',
deps: [
'minute',
'everynminute',
'hour',
'everynhour',
'dayofmonth',
'everyndayofmonth',
'month',
'dayofweek'
]
}
]
},
{
type: 'container',
fields: [
{
type: 'select',
name: 'minute',
label: gettext('Minute'),
value: ['{{ moment("m") }}'],
store: {
data: [
['*', '*'],
['0', '0'],
['1', '1'],
['2', '2'],
['3', '3'],
['4', '4'],
['5', '5'],
['6', '6'],
['7', '7'],
['8', '8'],
['9', '9'],
['10', '10'],
['11', '11'],
['12', '12'],
['13', '13'],
['14', '14'],
['15', '15'],
['16', '16'],
['17', '17'],
['18', '18'],
['19', '19'],
['20', '20'],
['21', '21'],
['22', '22'],
['23', '23'],
['24', '24'],
['25', '25'],
['26', '26'],
['27', '27'],
['28', '28'],
['29', '29'],
['30', '30'],
['31', '31'],
['32', '32'],
['33', '33'],
['34', '34'],
['35', '35'],
['36', '36'],
['37', '37'],
['38', '38'],
['39', '39'],
['40', '40'],
['41', '41'],
['42', '42'],
['43', '43'],
['44', '44'],
['45', '45'],
['46', '46'],
['47', '47'],
['48', '48'],
['49', '49'],
['50', '50'],
['51', '51'],
['52', '52'],
['53', '53'],
['54', '54'],
['55', '55'],
['56', '56'],
['57', '57'],
['58', '58'],
['59', '59']
]
},
multiple: true,
validators: {
required: true,
pattern: {
pattern: '^(\\*|(([0-9]|[1-5][0-9]),)*([0-9]|[1-5][0-9]))$',
errorData: gettext(
'The field should only contain * or a comma separated list of values.'
)
}
}
},
{
type: 'checkbox',
name: 'everynminute',
label: gettext('Every N minute'),
value: false,
modifiers: [
{
type: 'unchecked',
opposite: false,
constraint: {
operator: '<>',
arg0: {
operator: 'length',
arg0: { prop: 'minute' }
},
arg1: 1
}
},
{
type: 'disabled',
constraint: {
operator: 'or',
arg0: {
operator: '<>',
arg0: {
operator: 'length',
arg0: { prop: 'minute' }
},
arg1: 1
},
arg1: {
operator: 'in',
arg0: { value: '*' },
arg1: { prop: 'minute' }
}
}
}
]
}
]
},
{
type: 'container',
fields: [
{
type: 'select',
name: 'hour',
label: gettext('Hour'),
value: ['{{ moment("H") }}'],
store: {
data: [
['*', '*'],
['0', '0'],
['1', '1'],
['2', '2'],
['3', '3'],
['4', '4'],
['5', '5'],
['6', '6'],
['7', '7'],
['8', '8'],
['9', '9'],
['10', '10'],
['11', '11'],
['12', '12'],
['13', '13'],
['14', '14'],
['15', '15'],
['16', '16'],
['17', '17'],
['18', '18'],
['19', '19'],
['20', '20'],
['21', '21'],
['22', '22'],
['23', '23']
]
},
multiple: true,
validators: {
required: true,
pattern: {
pattern: '^(\\*|(([0-9]|1[0-9]|2[0-3]),)*([0-9]|1[0-9]|2[0-3]))$',
errorData: gettext(
'The field should only contain * or a comma separated list of values.'
)
}
}
},
{
type: 'checkbox',
name: 'everynhour',
label: gettext('Every N hour'),
value: false,
modifiers: [
{
type: 'unchecked',
opposite: false,
constraint: {
operator: '<>',
arg0: {
operator: 'length',
arg0: { prop: 'hour' }
},
arg1: 1
}
},
{
type: 'disabled',
constraint: {
operator: 'or',
arg0: {
operator: '<>',
arg0: {
operator: 'length',
arg0: { prop: 'hour' }
},
arg1: 1
},
arg1: {
operator: 'in',
arg0: { value: '*' },
arg1: { prop: 'hour' }
}
}
}
]
}
]
},
{
type: 'container',
fields: [
{
type: 'select',
name: 'dayofmonth',
label: gettext('Day of month'),
value: ['*'],
store: {
data: [
['*', '*'],
['1', '1'],
['2', '2'],
['3', '3'],
['4', '4'],
['5', '5'],
['6', '6'],
['7', '7'],
['8', '8'],
['9', '9'],
['10', '10'],
['11', '11'],
['12', '12'],
['13', '13'],
['14', '14'],
['15', '15'],
['16', '16'],
['17', '17'],
['18', '18'],
['19', '19'],
['20', '20'],
['21', '21'],
['22', '22'],
['23', '23'],
['24', '24'],
['25', '25'],
['26', '26'],
['27', '27'],
['28', '28'],
['29', '29'],
['30', '30'],
['31', '31']
]
},
multiple: true,
validators: {
required: true,
pattern: {
pattern: '^(\\*|(([1-9]|[12][0-9]|3[01]),)*([1-9]|[12][0-9]|3[01]))$',
errorData: gettext(
'The field should only contain * or a comma separated list of values.'
)
}
}
},
{
type: 'checkbox',
name: 'everyndayofmonth',
label: gettext('Every N day of month'),
value: false,
modifiers: [
{
type: 'unchecked',
opposite: false,
constraint: {
operator: '<>',
arg0: {
operator: 'length',
arg0: { prop: 'dayofmonth' }
},
arg1: 1
}
},
{
type: 'disabled',
constraint: {
operator: 'or',
arg0: {
operator: '<>',
arg0: {
operator: 'length',
arg0: { prop: 'dayofmonth' }
},
arg1: 1
},
arg1: {
operator: 'in',
arg0: { value: '*' },
arg1: { prop: 'dayofmonth' }
}
}
}
]
}
]
},
{
type: 'select',
name: 'month',
label: gettext('Month'),
value: ['*'],
store: {
data: [
['*', '*'],
['1', gettext('January')],
['2', gettext('February')],
['3', gettext('March')],
['4', gettext('April')],
['5', gettext('May')],
['6', gettext('June')],
['7', gettext('July')],
['8', gettext('August')],
['9', gettext('September')],
['10', gettext('October')],
['11', gettext('November')],
['12', gettext('December')]
]
},
multiple: true,
validators: {
required: true,
pattern: {
pattern: '^(\\*|(([1-9]|1[0-2]),)*([1-9]|1[0-2]))$',
errorData: gettext(
'The field should only contain * or a comma separated list of values.'
)
}
}
},
{
type: 'select',
name: 'dayofweek',
label: gettext('Day of week'),
value: ['*'],
store: {
data: [
['*', '*'],
['1', gettext('Monday')],
['2', gettext('Tuesday')],
['3', gettext('Wednesday')],
['4', gettext('Thursday')],
['5', gettext('Friday')],
['6', gettext('Saturday')],
['7', gettext('Sunday')]
]
},
multiple: true,
validators: {
required: true,
pattern: {
pattern: '^(\\*|([1-7],)*[1-7])$',
errorData: gettext(
'The field should only contain * or a comma separated list of values.'
)
}
}
},
{
type: 'checkbox',
name: 'sendemail',
label: gettext('Send command output via email'),
value: false,
hint: gettext(
'An email message with the command output (if any produced) is send to the administrator.'
)
},
{
type: 'checkbox',
name: 'optiondryrun',
label: gettext('Trial run'),
hint: gettext('Perform a trial run with no changes made'),
value: false
},
{
type: 'checkbox',
name: 'optionquiet',
label: gettext('Suppress non-error messages'),
value: false
},
{
type: 'checkbox',
name: 'optionarchive',
label: gettext('Archive mode'),
value: true,
modifiers: [
{
type: 'unchecked',
opposite: false,
constraint: { operator: 'falsy', arg0: { prop: 'optionrecursive' } }
},
{
type: 'unchecked',
opposite: false,
constraint: { operator: 'falsy', arg0: { prop: 'optionperms' } }
},
{
type: 'unchecked',
opposite: false,
constraint: { operator: 'falsy', arg0: { prop: 'optiontimes' } }
},
{
type: 'unchecked',
opposite: false,
constraint: { operator: 'falsy', arg0: { prop: 'optiongroup' } }
},
{
type: 'unchecked',
opposite: false,
constraint: { operator: 'falsy', arg0: { prop: 'optionowner' } }
}
]
},
{
type: 'checkbox',
name: 'optionrecursive',
label: gettext('Recurse into directories'),
value: true,
modifiers: [
{
type: 'checked',
opposite: false,
constraint: { operator: 'truthy', arg0: { prop: 'optionarchive' } }
}
]
},
{
type: 'checkbox',
name: 'optionperms',
label: gettext('Preserve permissions'),
hint: gettext('Set the destination permissions to be the same as the source permissions.'),
value: true,
modifiers: [
{
type: 'checked',
opposite: false,
constraint: { operator: 'truthy', arg0: { prop: 'optionarchive' } }
}
]
},
{
type: 'checkbox',
name: 'optiontimes',
label: gettext('Preserve modification times'),
hint: gettext(
'Transfer modification times along with the files and update them on the remote system.'
),
value: true,
modifiers: [
{
type: 'checked',
opposite: false,
constraint: { operator: 'truthy', arg0: { prop: 'optionarchive' } }
}
]
},
{
type: 'checkbox',
name: 'optiongroup',
label: gettext('Preserve group'),
hint: gettext('Set the group of the destination file to be the same as the source file.'),
value: true,
modifiers: [
{
type: 'checked',
opposite: false,
constraint: { operator: 'truthy', arg0: { prop: 'optionarchive' } }
}
]
},
{
type: 'checkbox',
name: 'optionowner',
label: gettext('Preserve owner'),
hint: gettext(
'Set the owner of the destination file to be the same as the source file, but only if the receiving rsync is being run as the super-user.'
),
value: true,
modifiers: [
{
type: 'checked',
opposite: false,
constraint: { operator: 'truthy', arg0: { prop: 'optionarchive' } }
}
]
},
{
type: 'checkbox',
name: 'optioncompress',
label: gettext('Compress'),
hint: gettext('Compress file data during the transfer.'),
value: false
},
{
type: 'checkbox',
name: 'optionacls',
label: gettext('Preserve ACLs'),
hint: gettext('Update the destination ACLs to be the same as the source ACLs.'),
value: false
},
{
type: 'checkbox',
name: 'optionxattrs',
label: gettext('Preserve extended attributes'),
hint: gettext(
'Update the destination extended attributes to be the same as the local ones.'
),
value: false
},
{
type: 'checkbox',
name: 'optionpartial',
label: gettext('Keep partially transferred files'),
hint: gettext(
'Enable this option to keep partially transferred files, otherwise they will be deleted if the transfer is interrupted.'
),
value: false
},
{
type: 'checkbox',
name: 'optiondelete',
label: gettext('Delete'),
hint: gettext("Delete files on the receiving side that don't exist on sender."),
value: false
},
{
type: 'textInput',
name: 'extraoptions',
label: gettext('Extra options'),
hint: gettext(
'Please check the <a href="path_to_url" target="_blank">manual page</a> for more details.'
),
value: ''
},
{
type: 'tagInput',
name: 'comment',
label: gettext('Tags'),
value: ''
}
],
buttons: [
{
template: 'submit',
execute: {
type: 'url',
url: '/services/rsync/tasks'
}
},
{
template: 'cancel',
execute: {
type: 'url',
url: '/services/rsync/tasks'
}
}
]
};
}
``` | /content/code_sandbox/deb/openmediavault/workbench/src/app/pages/services/rsync/rsync-task-form-page.component.ts | xml | 2016-05-03T10:35:34 | 2024-08-16T08:03:04 | openmediavault | openmediavault/openmediavault | 4,954 | 6,069 |
```xml
export { default as crop } from './CropAction.web';
export { default as extent } from './ExtentAction.web';
export { default as flip } from './FlipAction.web';
export { default as resize } from './ResizeAction.web';
export { default as rotate } from './RotateAction.web';
``` | /content/code_sandbox/packages/expo-image-manipulator/src/web/actions/index.web.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 61 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net6.0;net8.0</TargetFrameworks>
<AssemblyName>Superpower.Tests</AssemblyName>
<AssemblyOriginatorKeyFile>../../asset/Superpower.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageId>Superpower.Tests</PackageId>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Superpower\Superpower.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.1.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit" Version="2.4.1" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/test/Superpower.Tests/Superpower.Tests.csproj | xml | 2016-09-01T06:29:59 | 2024-08-13T01:41:52 | superpower | datalust/superpower | 1,013 | 312 |
```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 replaceBefore = require( './index' );
// TESTS //
// The function returns a string...
{
replaceBefore( 'beep boop', ' ', 'foo', 0 ); // $ExpectType string
replaceBefore( 'beep boop', 'xyz', 'foo', 0 ); // $ExpectType string
replaceBefore( 'beep boop', '', 'foo', 0 ); // $ExpectType string
}
// The compiler throws an error if the function is provided arguments having invalid types...
{
replaceBefore( true, 'd', 'foo', 0 ); // $ExpectError
replaceBefore( false, 'd' , 'foo', 0 ); // $ExpectError
replaceBefore( 3, 'd' , 'foo', 0 ); // $ExpectError
replaceBefore( [], 'd' , 'foo', 0 ); // $ExpectError
replaceBefore( {}, 'd' , 'foo', 0 ); // $ExpectError
replaceBefore( ( x: number ): number => x, 'd', 'foo', 0 ); // $ExpectError
replaceBefore( 'abc', true, 'foo', 0 ); // $ExpectError
replaceBefore( 'abc', false, 'foo', 0 ); // $ExpectError
replaceBefore( 'abc', 5 , 'foo', 0 ); // $ExpectError
replaceBefore( 'abc', [], 'foo', 0 ); // $ExpectError
replaceBefore( 'abc', {} , 'foo', 0 ); // $ExpectError
replaceBefore( 'abc', ( x: number ): number => x , 'foo', 0 ); // $ExpectError
replaceBefore( 'abc', 'd', true, 0 ); // $ExpectError
replaceBefore( 'abc', 'd', false, 0 ); // $ExpectError
replaceBefore( 'abc', 'd', 5, 0 ); // $ExpectError
replaceBefore( 'abc', 'd', [], 0 ); // $ExpectError
replaceBefore( 'abc', 'd', {}, 0 ); // $ExpectError
replaceBefore( 'abc', 'd', ( x: number ): number => x, 0 ); // $ExpectError
replaceBefore( 'abc', 'd', 'foo', true ); // $ExpectError
replaceBefore( 'abc', 'd', 'foo', false ); // $ExpectError
replaceBefore( 'abc', 'd', 'foo', '5' ); // $ExpectError
replaceBefore( 'abc', 'd', 'foo', [] ); // $ExpectError
replaceBefore( 'abc', 'd', 'foo', {} ); // $ExpectError
replaceBefore( 'abc', 'd', 'foo', ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the function is provided insufficient arguments...
{
replaceBefore(); // $ExpectError
replaceBefore( 'abc' ); // $ExpectError
replaceBefore( 'abc', 'd' ); // $ExpectError
replaceBefore( 'abc', 'd', 'foo', 1, 1 ); // $ExpectError
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/string/base/replace-before/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 754 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
import {getProcessInstancesRequestFilters} from '../index';
describe('getProcessInstancesRequestFilters', () => {
const originalLocation = window.location;
afterEach(() => {
window.location = originalLocation;
});
it('should get process instances request filters', () => {
const mockLocation = {
search:
'?active=true&incidents=true&completed=true&canceled=true&operationId=92449c1a-9d7a-4743-aaa3-f0661ead1bce&ids=9007199254741677&parentInstanceId=9007199254741678&startDateAfter=2023-09-05T00%3A00%3A00.000%2B0200&startDateBefore=2023-09-22T23%3A59%3A59.000%2B0200&endDateAfter=2023-09-01T00%3A00%3A00.000%2B0200&endDateBefore=2023-09-02T23%3A59%3A59.000%2B0200&errorMessage=test&process=bigVarProcess&version=1&flowNodeId=ServiceTask_0kt6c5i',
};
Object.defineProperty(window, 'location', {
writable: true,
value: mockLocation,
});
expect(getProcessInstancesRequestFilters()).toEqual({
active: true,
activityId: 'ServiceTask_0kt6c5i',
batchOperationId: '92449c1a-9d7a-4743-aaa3-f0661ead1bce',
canceled: true,
completed: true,
endDateAfter: '2023-09-01T00:00:00.000+0200',
endDateBefore: '2023-09-02T23:59:59.000+0200',
errorMessage: 'test',
finished: true,
ids: ['9007199254741677'],
incidents: true,
parentInstanceId: '9007199254741678',
running: true,
startDateAfter: '2023-09-05T00:00:00.000+0200',
startDateBefore: '2023-09-22T23:59:59.000+0200',
});
});
it('should not include tenant in request filters if value is all', () => {
const mockLocation = {
search: '?active=true&incidents=true&tenant=all',
};
Object.defineProperty(window, 'location', {
writable: true,
value: mockLocation,
});
expect(getProcessInstancesRequestFilters()).toEqual({
active: true,
incidents: true,
running: true,
});
});
it('should include tenant in request filters', () => {
const mockLocation = {
search: '?active=true&incidents=true&tenant=tenant-A',
};
Object.defineProperty(window, 'location', {
writable: true,
value: mockLocation,
});
expect(getProcessInstancesRequestFilters()).toEqual({
active: true,
incidents: true,
running: true,
tenantId: 'tenant-A',
});
});
});
``` | /content/code_sandbox/operate/client/src/modules/utils/filter/tests/getProcessInstancesRequestFilters.test.ts | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 713 |
```xml
import { IIntegrationDocument } from '../../models/definitions/integrations';
import {
sendCommonMessage,
sendIntegrationsMessage,
} from '../../messageBroker';
import { IContext } from '../../connectionResolver';
import { isServiceRunning } from '../../utils';
export default {
async __resolveReference({ _id }, { models }: IContext) {
return models.Integrations.findOne({ _id });
},
brand(integration: IIntegrationDocument) {
if (!integration.brandId) {
return null;
}
return (
integration.brandId && {
__typename: 'Brand',
_id: integration.brandId,
}
);
},
async form(integration: IIntegrationDocument) {
if (!integration.formId) {
return null;
}
return { __typename: 'Form', _id: integration.formId };
},
async channels(integration: IIntegrationDocument, _args, { models }: IContext) {
return models.Channels.find({
integrationIds: { $in: [integration._id] },
});
},
async tags(integration: IIntegrationDocument) {
return (integration.tagIds || []).map((_id) => ({
__typename: 'Tag',
_id,
}));
},
async websiteMessengerApps(
integration: IIntegrationDocument,
_args,
{ models }: IContext,
) {
if (integration.kind === 'messenger') {
return models.MessengerApps.find({
kind: 'website',
'credentials.integrationId': integration._id,
});
}
return [];
},
async knowledgeBaseMessengerApps(
integration: IIntegrationDocument,
_args,
{ models }: IContext,
) {
if (integration.kind === 'messenger') {
return models.MessengerApps.find({
kind: 'knowledgebase',
'credentials.integrationId': integration._id,
});
}
return [];
},
async leadMessengerApps(
integration: IIntegrationDocument,
_args,
{ models }: IContext,
) {
if (integration.kind === 'messenger') {
return models.MessengerApps.find({
kind: 'lead',
'credentials.integrationId': integration._id,
});
}
return [];
},
async healthStatus(
integration: IIntegrationDocument,
_args,
{ subdomain }: IContext,
) {
const kind = integration.kind.includes('facebook')
? 'facebook'
: integration.kind.split('-')[0];
if (kind === 'messenger') {
return { status: 'healthy' };
}
const serviceRunning = await isServiceRunning(kind);
if (serviceRunning) {
try {
const status = await sendCommonMessage({
serviceName: kind,
subdomain,
action: 'getStatus',
data: {
integrationId: integration._id,
},
isRPC: true,
});
return status;
} catch (e) {
return { status: 'healthy' };
}
}
return { status: 'healthy' };
},
async details(
integration: IIntegrationDocument,
_args,
{ subdomain }: IContext,
) {
const inboxId: string = integration._id;
const serviceName = integration.kind.includes('facebook')
? 'facebook'
: integration.kind;
if (integration.kind === 'messenger') {
return null;
}
if (
integration.kind === 'callpro' &&
(await isServiceRunning('integrations'))
) {
return await sendIntegrationsMessage({
subdomain,
action: 'api_to_integrations',
data: { inboxId, action: 'getDetails', integrationId: inboxId },
isRPC: true,
});
}
const serviceRunning = await isServiceRunning(serviceName);
if (serviceRunning) {
try {
const a = await sendCommonMessage({
serviceName,
subdomain,
action: 'api_to_integrations',
data: { inboxId, integrationId: inboxId, action: 'getDetails' },
isRPC: true,
defaultValue: null,
});
return a;
} catch (e) {
console.error('error', e);
return null;
}
}
},
};
``` | /content/code_sandbox/packages/plugin-inbox-api/src/graphql/resolvers/integration.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 921 |
```xml
/** @public */
export declare class Item {
options: renamed_Options;
}
/** @public */
export declare interface renamed_Options {
name: string;
color: 'red' | 'blue';
}
export { }
``` | /content/code_sandbox/build-tests/api-extractor-scenarios/etc/docReferencesAlias/rollup.d.ts | xml | 2016-09-30T00:28:20 | 2024-08-16T18:54:35 | rushstack | microsoft/rushstack | 5,790 | 46 |
```xml
import { useState } from 'react';
import { Formik, Field, Form } from 'formik';
import { Laptop } from 'lucide-react';
import { OpenAMTConfiguration } from '@/react/edge/edge-devices/open-amt/types';
import { Switch } from '@@/form-components/SwitchField/Switch';
import { FormControl } from '@@/form-components/FormControl';
import { Widget, WidgetBody, WidgetTitle } from '@@/Widget';
import { LoadingButton } from '@@/buttons/LoadingButton';
import { TextTip } from '@@/Tip/TextTip';
import { Input } from '@@/form-components/Input';
import { FileUploadField } from '@@/form-components/FileUpload';
import { validationSchema } from './SettingsOpenAMT.validation';
export interface Settings {
openAMTConfiguration: OpenAMTConfiguration;
EnableEdgeComputeFeatures: boolean;
}
interface Props {
settings: Settings;
onSubmit(values: OpenAMTConfiguration): void;
}
export function SettingsOpenAMT({ settings, onSubmit }: Props) {
const [certFile, setCertFile] = useState<File>();
async function handleFileUpload(
file: File,
setFieldValue: (
field: string,
value: unknown,
shouldValidate?: boolean
) => void
) {
if (file) {
setCertFile(file);
const fileContent = await readFileContent(file);
setFieldValue('certFileContent', fileContent);
setFieldValue('certFileName', file.name);
}
}
function readFileContent(file: File) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (e) => {
if (e.target == null || e.target.result == null) {
resolve('');
return;
}
const base64 = e.target.result.toString();
// remove prefix of "data:application/x-pkcs12;base64," returned by "readAsDataURL()"
const index = base64.indexOf('base64,');
const cert = base64.substring(index + 7, base64.length);
resolve(cert);
};
fileReader.onerror = () => {
reject(new Error('error reading provisioning certificate file'));
};
fileReader.readAsDataURL(file);
});
}
const openAMTConfiguration = settings ? settings.openAMTConfiguration : null;
const initialValues = {
enabled: openAMTConfiguration ? openAMTConfiguration.enabled : false,
mpsServer: openAMTConfiguration ? openAMTConfiguration.mpsServer : '',
mpsUser: openAMTConfiguration ? openAMTConfiguration.mpsUser : '',
mpsPassword: openAMTConfiguration ? openAMTConfiguration.mpsPassword : '',
domainName: openAMTConfiguration ? openAMTConfiguration.domainName : '',
certFileContent: openAMTConfiguration
? openAMTConfiguration.certFileContent
: '',
certFileName: openAMTConfiguration ? openAMTConfiguration.certFileName : '',
certFilePassword: openAMTConfiguration
? openAMTConfiguration.certFilePassword
: '',
};
if (
initialValues.certFileContent &&
initialValues.certFileName &&
!certFile
) {
setCertFile(new File([], initialValues.certFileName));
}
const edgeComputeFeaturesEnabled = settings
? settings.EnableEdgeComputeFeatures
: false;
return (
<div className="row">
<Widget>
<WidgetTitle icon={Laptop} title="Intel OpenAMT" />
<WidgetBody>
<Formik
initialValues={initialValues}
onSubmit={onSubmit}
enableReinitialize
validationSchema={() => validationSchema()}
validateOnChange
validateOnMount
>
{({
values,
errors,
handleSubmit,
setFieldValue,
isSubmitting,
isValid,
dirty,
}) => (
<Form className="form-horizontal" onSubmit={handleSubmit}>
<FormControl
inputId="edge_enableOpenAMT"
label="Enable OpenAMT"
errors={errors.enabled}
size="small"
>
<Switch
id="edge_enableOpenAMT"
data-cy="edge-enableOpenAMT-switch"
name="edge_enableOpenAMT"
className="space-right"
disabled={!edgeComputeFeaturesEnabled}
checked={edgeComputeFeaturesEnabled && values.enabled}
onChange={(e) => setFieldValue('enabled', e)}
/>
</FormControl>
<TextTip color="blue" className="mb-2">
When enabled, this will allow Portainer to interact with an
OpenAMT MPS API.
</TextTip>
{edgeComputeFeaturesEnabled && values.enabled && (
<>
<hr />
<FormControl
inputId="mps_server"
label="MPS Server"
size="medium"
errors={errors.mpsServer}
>
<Field
as={Input}
name="mpsServer"
id="mps_server"
placeholder="Enter the MPS Server"
value={values.mpsServer}
data-cy="openAMT-serverInput"
/>
</FormControl>
<FormControl
inputId="mps_username"
label="MPS User"
size="medium"
errors={errors.mpsUser}
>
<Field
as={Input}
name="mpsUser"
id="mps_username"
placeholder="Enter the MPS User"
value={values.mpsUser}
data-cy="openAMT-usernameInput"
/>
</FormControl>
<FormControl
inputId="mps_password"
label="MPS Password"
size="medium"
tooltip="Needs to be 8-32 characters including one uppercase, one lowercase letters, one base-10 digit and one special character."
errors={errors.mpsPassword}
>
<Field
as={Input}
type="password"
name="mpsPassword"
id="mps_password"
placeholder="Enter the MPS Password"
value={values.mpsPassword}
data-cy="openAMT-passwordInput"
/>
</FormControl>
<hr />
<FormControl
inputId="domain_name"
label="Domain Name"
size="medium"
tooltip="Enter the FQDN that is associated with the provisioning certificate (i.e amtdomain.com)"
errors={errors.domainName}
>
<Field
as={Input}
name="domainName"
id="domain_name"
placeholder="Enter the Domain Name"
value={values.domainName}
data-cy="openAMT-domainInput"
/>
</FormControl>
<FormControl
inputId="certificate_file"
label="Provisioning Certificate File (.pfx)"
size="medium"
tooltip="Supported CAs are Comodo, DigiCert, Entrust and GoDaddy.<br>The certificate must contain the private key.<br>On AMT 15 based devices you need to use SHA2."
errors={errors.certFileContent}
setTooltipHtmlMessage
>
<FileUploadField
inputId="certificate_file"
data-cy="openAMT-certFileInput"
title="Upload file"
accept=".pfx"
value={certFile}
onChange={(file) =>
handleFileUpload(file, setFieldValue)
}
/>
</FormControl>
<FormControl
inputId="certificate_password"
label="Provisioning Certificate Password"
size="medium"
tooltip="Needs to be 8-32 characters including one uppercase, one lowercase letters, one base-10 digit and one special character."
errors={errors.certFilePassword}
>
<Field
as={Input}
type="password"
name="certFilePassword"
id="certificate_password"
placeholder="**********"
value={values.certFilePassword}
data-cy="openAMT-certPasswordInput"
/>
</FormControl>
</>
)}
<div className="form-group mt-5">
<div className="col-sm-12">
<LoadingButton
disabled={!isValid || !dirty}
data-cy="settings-OpenAMTButton"
isLoading={isSubmitting}
loadingText="Saving settings..."
>
Save settings
</LoadingButton>
</div>
</div>
</Form>
)}
</Formik>
</WidgetBody>
</Widget>
</div>
);
}
``` | /content/code_sandbox/app/react/portainer/settings/EdgeComputeView/SettingsOpenAMT/SettingsOpenAMT.tsx | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 1,805 |
```xml
import type { SignatureLike } from "../crypto/index.js";
/**
* Computes the [[link-eip-191]] personal-sign message digest to sign.
*
* This prefixes the message with [[MessagePrefix]] and the decimal length
* of %%message%% and computes the [[keccak256]] digest.
*
* If %%message%% is a string, it is converted to its UTF-8 bytes
* first. To compute the digest of a [[DataHexString]], it must be converted
* to [bytes](getBytes).
*
* @example:
* hashMessage("Hello World")
* //_result:
*
* // Hashes the SIX (6) string characters, i.e.
* // [ "0", "x", "4", "2", "4", "3" ]
* hashMessage("0x4243")
* //_result:
*
* // Hashes the TWO (2) bytes [ 0x42, 0x43 ]...
* hashMessage(getBytes("0x4243"))
* //_result:
*
* // ...which is equal to using data
* hashMessage(new Uint8Array([ 0x42, 0x43 ]))
* //_result:
*
*/
export declare function hashMessage(message: Uint8Array | string): string;
/**
* Return the address of the private key that produced
* the signature %%sig%% during signing for %%message%%.
*/
export declare function verifyMessage(message: Uint8Array | string, sig: SignatureLike): string;
//# sourceMappingURL=message.d.ts.map
``` | /content/code_sandbox/lib.commonjs/hash/message.d.ts | xml | 2016-07-16T04:35:37 | 2024-08-16T13:37:46 | ethers.js | ethers-io/ethers.js | 7,843 | 336 |
```xml
<test>
<settings>
<max_memory_usage>30000000000</max_memory_usage>
<!--
Because of random distribution of data between threads, the number
of unique keys per thread might differ. This means that sometimes
we switch to two-level aggregation, and sometimes we don't, based on
the "bytes" threshold. Two-level aggregation turns out to be twice
as fast, because it merges aggregation states in multiple threads.
Lower the threshold here, to avoid jitter. It is unclear whether it
would be beneficial to lower the default as well.
-->
<group_by_two_level_threshold_bytes>10000000</group_by_two_level_threshold_bytes>
</settings>
<substitutions>
<substitution>
<name>key</name>
<values>
<!--
1 as a key doesn't make much sense - the queries are either
too long in case of uniqExact or too short in case of limited
uniq, so the result is drowned by the noise.
<value>1</value>
-->
<value>SearchEngineID</value>
<value>RegionID</value>
<value>SearchPhrase</value>
<value>ClientIP</value>
</values>
</substitution>
<substitution>
<name>func</name>
<values>
<value>sum</value>
<value>uniq</value>
<value>uniqExact</value>
<value>uniqHLL12</value>
<value>uniqCombined(12)</value>
<value>uniqCombined(13)</value>
<value>uniqCombined(14)</value>
<value>uniqCombined(15)</value>
<value>uniqCombined(16)</value>
<value>uniqCombined(17)</value>
<value>uniqCombined(18)</value>
<value>uniqUpTo(3)</value>
<value>uniqUpTo(5)</value>
<value>uniqUpTo(10)</value>
<value>uniqUpTo(25)</value>
<value>uniqUpTo(100)</value>
</values>
</substitution>
</substitutions>
<query>SELECT {key} AS k, {func}(UserID) FROM hits_100m_single GROUP BY k FORMAT Null</query>
<query>SELECT {key} AS k, uniqTheta(UserID) FROM hits_10m_single GROUP BY k FORMAT Null</query>
</test>
``` | /content/code_sandbox/tests/performance/uniq.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 545 |
```xml
const jobRefersParamsDef = `
$categoryId: String,
$searchValue: String,
$ids: [String],
$types: [String],
`;
const jobRefersParams = `
categoryId: $categoryId,
searchValue: $searchValue,
ids: $ids,
types: $types,
`;
const jobRefersFields = `
_id
createdAt
code
name
type
status
duration
durationType
categoryId
needProducts
resultProducts
`;
const jobCategoryFields = `
_id
createdAt
name
code
order
description
parentId
status
productCount
`;
// JOB
const jobRefers = `
query jobRefers($page: Int, $perPage: Int, ${jobRefersParamsDef}) {
jobRefers(page: $page, perPage: $perPage, ${jobRefersParams}) {
${jobRefersFields}
}
}
`;
const jobReferTotalCount = `
query jobReferTotalCount(${jobRefersParamsDef}) {
jobReferTotalCount(${jobRefersParams})
}
`;
const jobReferDetail = `
query jobReferDetail($id: String!) {
jobReferDetail(_id: $id) {
${jobRefersFields}
needProductsData
resultProductsData
}
}
`;
const jobCategories = `
query jobCategories($status: String) {
jobCategories(status: $status) {
${jobCategoryFields}
}
}
`;
const jobCategoriesTotalCount = `
query jobCategoriesTotalCount {
jobCategoriesTotalCount
}
`;
export default {
jobRefers,
jobReferDetail,
jobReferTotalCount,
jobCategories,
jobCategoriesTotalCount
};
``` | /content/code_sandbox/packages/plugin-processes-ui/src/job/graphql/queries.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 385 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="path_to_url"
android:shape="rectangle">
<solid android:color="@android:color/holo_blue_light"/>
</shape>
``` | /content/code_sandbox/boommenu/src/main/res/drawable/piece.xml | xml | 2016-03-19T12:04:12 | 2024-08-12T03:29:06 | BoomMenu | Nightonke/BoomMenu | 5,806 | 50 |
```xml
import type { StyleProp, ViewStyle, ViewProps } from 'react-native';
// @needsAudit
export declare type AppleAuthenticationButtonProps = ViewProps & {
/**
* The method to call when the user presses the button. You should call [`AppleAuthentication.signInAsync`](#appleauthenticationisavailableasync)
* in here.
*/
onPress: () => void;
/**
* The type of button text to display ("Sign In with Apple" vs. "Continue with Apple").
*/
buttonType: AppleAuthenticationButtonType;
/**
* The Apple-defined color scheme to use to display the button.
*/
buttonStyle: AppleAuthenticationButtonStyle;
/**
* The border radius to use when rendering the button. This works similarly to
* `style.borderRadius` in other Views.
*/
cornerRadius?: number;
/**
* The custom style to apply to the button. Should not include `backgroundColor` or `borderRadius`
* properties.
*/
style?: StyleProp<Omit<ViewStyle, 'backgroundColor' | 'borderRadius'>>;
};
// @needsAudit
/**
* The options you can supply when making a call to [`AppleAuthentication.signInAsync()`](#appleauthenticationsigninasyncoptions).
* None of these options are required.
*
* @see [Apple
* Documentation](path_to_url
* for more details.
*/
export type AppleAuthenticationSignInOptions = {
/**
* Array of user information scopes to which your app is requesting access. Note that the user can
* choose to deny your app access to any scope at the time of logging in. You will still need to
* handle `null` values for any scopes you request. Additionally, note that the requested scopes
* will only be provided to you the first time each user signs into your app; in subsequent
* requests they will be `null`. Defaults to `[]` (no scopes).
*/
requestedScopes?: AppleAuthenticationScope[];
/**
* An arbitrary string that is returned unmodified in the corresponding credential after a
* successful authentication. This can be used to verify that the response was from the request
* you made and avoid replay attacks. More information on this property is available in the
* OAuth 2.0 protocol [RFC6749](path_to_url#section-10.12).
*/
state?: string;
/**
* An arbitrary string that is used to prevent replay attacks. See more information on this in the
* [OpenID Connect specification](path_to_url#CodeFlowSteps).
*/
nonce?: string;
};
// @needsAudit @docsMissing
/**
* The options you can supply when making a call to [`AppleAuthentication.refreshAsync()`](#appleauthenticationrefreshasyncoptions).
* You must include the ID string of the user whose credentials you'd like to refresh.
*
* @see [Apple
* Documentation](path_to_url
* for more details.
*/
export type AppleAuthenticationRefreshOptions = {
user: string;
/**
* Array of user information scopes to which your app is requesting access. Note that the user can
* choose to deny your app access to any scope at the time of logging in. You will still need to
* handle `null` values for any scopes you request. Additionally, note that the requested scopes
* will only be provided to you the first time each user signs into your app; in subsequent
* requests they will be `null`. Defaults to `[]` (no scopes).
*/
requestedScopes?: AppleAuthenticationScope[];
/**
* An arbitrary string that is returned unmodified in the corresponding credential after a
* successful authentication. This can be used to verify that the response was from the request
* you made and avoid replay attacks. More information on this property is available in the
* OAuth 2.0 protocol [RFC6749](path_to_url#section-10.12).
*/
state?: string;
};
// @needsAudit
/**
* The options you can supply when making a call to [`AppleAuthentication.signOutAsync()`](#appleauthenticationsignoutasyncoptions).
* You must include the ID string of the user to sign out.
*
* @see [Apple
* Documentation](path_to_url
* for more details.
*/
export type AppleAuthenticationSignOutOptions = {
user: string;
/**
* An arbitrary string that is returned unmodified in the corresponding credential after a
* successful authentication. This can be used to verify that the response was from the request
* you made and avoid replay attacks. More information on this property is available in the
* OAuth 2.0 protocol [RFC6749](path_to_url#section-10.12).
*/
state?: string;
};
// @needsAudit
/**
* The object type returned from a successful call to [`AppleAuthentication.signInAsync()`](#appleauthenticationsigninasyncoptions),
* [`AppleAuthentication.refreshAsync()`](#appleauthenticationrefreshasyncoptions), or [`AppleAuthentication.signOutAsync()`](#appleauthenticationsignoutasyncoptions)
* which contains all of the pertinent user and credential information.
*
* @see [Apple
* Documentation](path_to_url
* for more details.
*/
export type AppleAuthenticationCredential = {
/**
* An identifier associated with the authenticated user. You can use this to check if the user is
* still authenticated later. This is stable and can be shared across apps released under the same
* development team. The same user will have a different identifier for apps released by other
* developers.
*/
user: string;
/**
* An arbitrary string that your app provided as `state` in the request that generated the
* credential. Used to verify that the response was from the request you made. Can be used to
* avoid replay attacks. If you did not provide `state` when making the sign-in request, this field
* will be `null`.
*/
state: string | null;
/**
* The user's name. May be `null` or contain `null` values if you didn't request the `FULL_NAME`
* scope, if the user denied access, or if this is not the first time the user has signed into
* your app.
*/
fullName: AppleAuthenticationFullName | null;
/**
* The user's email address. Might not be present if you didn't request the `EMAIL` scope. May
* also be null if this is not the first time the user has signed into your app. If the user chose
* to withhold their email address, this field will instead contain an obscured email address with
* an Apple domain.
*/
email: string | null;
/**
* A value that indicates whether the user appears to the system to be a real person.
*/
realUserStatus: AppleAuthenticationUserDetectionStatus;
/**
* A JSON Web Token (JWT) that securely communicates information about the user to your app.
*/
identityToken: string | null;
/**
* A short-lived session token used by your app for proof of authorization when interacting with
* the app's server counterpart. Unlike `user`, this is ephemeral and will change each session.
*/
authorizationCode: string | null;
};
// @needsAudit @docsMissing
/**
* An object representing the tokenized portions of the user's full name. Any of all of the fields
* may be `null`. Only applicable fields that the user has allowed your app to access will be nonnull.
*/
export type AppleAuthenticationFullName = {
namePrefix: string | null;
givenName: string | null;
middleName: string | null;
familyName: string | null;
nameSuffix: string | null;
nickname: string | null;
};
// @needsAudit @docsMissing
/**
* An enum whose values specify scopes you can request when calling [`AppleAuthentication.signInAsync()`](#appleauthenticationsigninasyncoptions).
*
* > Note that it is possible that you will not be granted all of the scopes which you request.
* > You will still need to handle null values for any fields you request.
*
* @see [Apple
* Documentation](path_to_url
* for more details.
*/
export enum AppleAuthenticationScope {
FULL_NAME = 0,
EMAIL = 1,
}
// @needsAudit @docsMissing
export enum AppleAuthenticationOperation {
/**
* An operation that depends on the particular kind of credential provider.
*/
IMPLICIT = 0,
LOGIN = 1,
REFRESH = 2,
LOGOUT = 3,
}
// @needsAudit @docsMissing
/**
* An enum whose values specify state of the credential when checked with [`AppleAuthentication.getCredentialStateAsync()`](#appleauthenticationgetcredentialstateasyncuser).
*
* @see [Apple
* Documentation](path_to_url
* for more details.
*/
export enum AppleAuthenticationCredentialState {
REVOKED = 0,
AUTHORIZED = 1,
NOT_FOUND = 2,
TRANSFERRED = 3,
}
// @needsAudit
/**
* An enum whose values specify the system's best guess for how likely the current user is a real person.
*
* @see [Apple
* Documentation](path_to_url
* for more details.
*/
export enum AppleAuthenticationUserDetectionStatus {
/**
* The system does not support this determination and there is no data.
*/
UNSUPPORTED = 0,
/**
* The system has not determined whether the user might be a real person.
*/
UNKNOWN = 1,
/**
* The user appears to be a real person.
*/
LIKELY_REAL = 2,
}
// @needsAudit
/**
* An enum whose values control which pre-defined text to use when rendering an [`AppleAuthenticationButton`](#appleauthenticationbutton).
*/
export enum AppleAuthenticationButtonType {
/**
* "Sign in with Apple"
*/
SIGN_IN = 0,
/**
* "Continue with Apple"
*/
CONTINUE = 1,
/**
* "Sign up with Apple"
* @platform ios 13.2+
*/
SIGN_UP = 2,
}
// @needsAudit
/**
* An enum whose values control which pre-defined color scheme to use when rendering an [`AppleAuthenticationButton`](#appleauthenticationbutton).
*/
export enum AppleAuthenticationButtonStyle {
/**
* White button with black text.
*/
WHITE = 0,
/**
* White button with a black outline and black text.
*/
WHITE_OUTLINE = 1,
/**
* Black button with white text.
*/
BLACK = 2,
}
``` | /content/code_sandbox/packages/expo-apple-authentication/src/AppleAuthentication.types.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 2,286 |
```xml
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at path_to_url
*/
import {Observable} from 'rxjs';
import {ListRange} from '@angular/cdk/collections';
/**
* An item to be repeated by the VirtualScrollViewport
*/
export interface CdkVirtualScrollRepeater<T> {
readonly dataStream: Observable<readonly T[]>;
measureRangeSize(range: ListRange, orientation: 'horizontal' | 'vertical'): number;
}
``` | /content/code_sandbox/src/cdk/scrolling/virtual-scroll-repeater.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 114 |
```xml
/*
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
import { TransactionPool, PooledTransaction } from '@liskhq/lisk-transaction-pool';
import { dataStructures } from '@liskhq/lisk-utils';
import { Transaction, BlockHeader, BlockAssets, Event } from '@liskhq/lisk-chain';
import { address } from '@liskhq/lisk-cryptography';
import { ABI, TransactionExecutionResult, TransactionVerifyResult } from '../../abi';
export class HighFeeGenerationStrategy {
private readonly _abi: ABI;
private readonly _pool: TransactionPool;
private readonly _constants: {
readonly maxTransactionsSize: number;
};
public constructor({
// Modules
abi,
pool,
// constants
maxTransactionsSize,
}: {
readonly abi: ABI;
readonly pool: TransactionPool;
readonly maxTransactionsSize: number;
}) {
this._abi = abi;
this._pool = pool;
this._constants = { maxTransactionsSize };
}
public async getTransactionsForBlock(
contextID: Buffer,
header: BlockHeader,
assets: BlockAssets,
): Promise<{ transactions: Transaction[]; events: Event[] }> {
// Initialize array to select transactions
const readyTransactions = [];
// Get processable transactions from transaction pool
// transactions are sorted by lowest nonce per account
const transactionsMappedBySender = this._pool.getProcessableTransactions();
// Initialize block size with 0
let blockTransactionsSize = 0;
const feePriorityHeap = new dataStructures.MaxHeap();
for (const transactions of transactionsMappedBySender.values()) {
const lowestNonceTrx = transactions[0];
feePriorityHeap.push(lowestNonceTrx.feePriority as bigint, lowestNonceTrx);
}
const events = [];
// Loop till we have last account exhausted to pick transactions
while (transactionsMappedBySender.size > 0) {
// Get the transaction with highest fee and lowest nonce
const lowestNonceHighestFeeTrx = feePriorityHeap.pop()?.value as Transaction | undefined;
if (!lowestNonceHighestFeeTrx) {
throw new Error('lowest nonce tx must exist');
}
// If transaction byte size can't fit in max transactions length
// then discard all transactions from that account as
// other transactions will be higher nonce
const trsByteSize = lowestNonceHighestFeeTrx.getBytes().length;
if (blockTransactionsSize + trsByteSize > this._constants.maxTransactionsSize) {
// End up filling the block
break;
}
const senderId = address.getAddressFromPublicKey(lowestNonceHighestFeeTrx.senderPublicKey);
// Try to process transaction
try {
const { result: verifyResult } = await this._abi.verifyTransaction({
contextID,
transaction: lowestNonceHighestFeeTrx.toObject(),
header: header.toObject(),
onlyCommand: false,
});
if (verifyResult !== TransactionVerifyResult.OK) {
throw new Error('Transaction is not valid');
}
const { events: executedEvents, result: executeResult } =
await this._abi.executeTransaction({
contextID,
header: header.toObject(),
transaction: lowestNonceHighestFeeTrx.toObject(),
assets: assets.getAll(),
dryRun: false,
});
if (executeResult === TransactionExecutionResult.INVALID) {
this._pool.remove(lowestNonceHighestFeeTrx);
throw new Error('Transaction is not valid');
}
events.push(...executedEvents.map(e => new Event(e)));
} catch (error) {
// If transaction can't be processed then discard all transactions
// from that account as other transactions will be higher nonce
transactionsMappedBySender.delete(senderId);
continue;
}
// Select transaction as ready for forging
readyTransactions.push(lowestNonceHighestFeeTrx);
// Increase block size with updated transaction size
blockTransactionsSize += trsByteSize;
// Remove the selected transaction from the list
// as original array is readonly in future when we convert it to
// typescript the `splice` will not work so why used destruction
const [, ...choppedArray] = transactionsMappedBySender.get(senderId) as PooledTransaction[];
transactionsMappedBySender.set(senderId, choppedArray);
// If there is no transaction left in heap for that account
// then remove that account from map
const remainingTransactions = transactionsMappedBySender.get(senderId);
if (!remainingTransactions || remainingTransactions.length === 0) {
transactionsMappedBySender.delete(senderId);
continue;
}
// Pick next lowest transaction from same account and push to fee queue
const nextLowestNonceTransactions = transactionsMappedBySender.get(
senderId,
) as PooledTransaction[];
feePriorityHeap.push(
nextLowestNonceTransactions[0].feePriority as bigint,
nextLowestNonceTransactions[0],
);
}
return { transactions: readyTransactions, events };
}
}
``` | /content/code_sandbox/framework/src/engine/generator/strategies.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 1,197 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions
xmlns="path_to_url"
xmlns:activiti="path_to_url"
targetNamespace="Examples">
<process id="asyncService">
<startEvent id="theStart" />
<sequenceFlow sourceRef="theStart" targetRef="service" />
<serviceTask id="service" activiti:class="org.activiti.engine.test.bpmn.async.FailingAsyncService" activiti:async="true" />
<boundaryEvent attachedToRef="service" id="timer" cancelActivity="true">
<timerEventDefinition>
<timeDuration>PT5S</timeDuration>
</timerEventDefinition>
</boundaryEvent>
<sequenceFlow sourceRef="timer" targetRef="theEnd" />
<sequenceFlow sourceRef="service" targetRef="theEnd" />
<endEvent id="theEnd" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/engine/test/bpmn/async/AsyncTaskTest.testFailingAsyncServiceTimer.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 215 |
```xml
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { defineMessages, intlShape } from 'react-intl';
import SVGInline from 'react-svg-inline';
// @ts-ignore ts-migrate(2307) FIXME: Cannot find module '../../../assets/images/insecur... Remove this comment to see the full error message
import insecureWalletIcon from '../../../assets/images/insecure-wallet.inline.svg';
import styles from './SetWalletPassword.scss';
import ChangeSpendingPasswordDialogContainer from '../../../containers/wallet/dialogs/settings/ChangeSpendingPasswordDialogContainer';
const messages = defineMessages({
setPasswordButton: {
id: 'wallet.settings.setWalletPassword.dialog.setPasswordButton',
defaultMessage: '!!!Set a password',
description:
'Label for the "Set a password" button in the set wallet password dialog.',
},
setPasswordMessage: {
id: 'wallet.settings.setWalletPassword.dialog.setPasswordMessage',
defaultMessage:
'!!!To keep your wallet secure and start using it in Daedalus, you need to set a spending password.',
description:
'Message for the "Set a password" button in the set wallet password dialog.',
},
setPasswordTitle: {
id: 'wallet.settings.setWalletPassword.dialog.setPasswordTitle',
defaultMessage: '!!!Your wallet is not protected with a password',
description:
'Title for the "Set wallet password" dialog when there is not password set.',
},
});
type Props = {
isSetWalletPasswordDialogOpen: boolean;
onSetWalletPassword: (...args: Array<any>) => any;
};
@observer
class SetWalletPassword extends Component<Props> {
static contextTypes = {
intl: intlShape.isRequired,
};
render() {
const { intl } = this.context;
const { isSetWalletPasswordDialogOpen, onSetWalletPassword } = this.props;
return (
<>
<div className={styles.component}>
<div className={styles.setPasswordDialog}>
<div className={styles.setPasswordWrapper}>
<SVGInline
svg={insecureWalletIcon}
className={styles.insecureWalletIcon}
/>
<h2 className={styles.setPasswordTitle}>
{intl.formatMessage(messages.setPasswordTitle)}
</h2>
<p className={styles.setPasswordMessage}>
{intl.formatMessage(messages.setPasswordMessage)}
</p>
<button
className={styles.setPasswordButton}
onClick={onSetWalletPassword}
>
{intl.formatMessage(messages.setPasswordButton)}
</button>
</div>
</div>
</div>
{isSetWalletPasswordDialogOpen && (
<ChangeSpendingPasswordDialogContainer />
)}
</>
);
}
}
export default SetWalletPassword;
``` | /content/code_sandbox/source/renderer/app/components/wallet/settings/SetWalletPassword.tsx | xml | 2016-10-05T13:48:54 | 2024-08-13T22:03:19 | daedalus | input-output-hk/daedalus | 1,230 | 574 |
```xml
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AssemblyName>new-routing-12</AssemblyName>
<PackageId>new-routing-12</PackageId>
<ImplicitUsings>true</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Watch Include="**\*.cshtml" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/projects/endpoint-routing/new-routing-12/new-routing-12.csproj | xml | 2016-07-27T08:23:40 | 2024-08-16T19:15:21 | practical-aspnetcore | dodyg/practical-aspnetcore | 9,106 | 95 |
```xml
<TS language="lt" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Spustelkite deinj klavi norint keisti adres arba etiket</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Sukurti nauj adres</translation>
</message>
<message>
<source>&New</source>
<translation>&Naujas</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopijuoti esam adres main atmint</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Kopijuoti</translation>
</message>
<message>
<source>C&lose</source>
<translation>&Uverti</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Itrinti pasirinkt adres i srao</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Eksportuoti informacij i dabartins lentels fail</translation>
</message>
<message>
<source>&Export</source>
<translation>&Eksportuoti</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Trinti</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Address</source>
<translation>Adresas</translation>
</message>
</context>
<context>
<name>AskPasswordDialog</name>
<message>
<source>Password Dialog</source>
<translation>Slaptafrazs dialogas</translation>
</message>
<message>
<source>Enter password</source>
<translation>vesti slaptafraz</translation>
</message>
<message>
<source>New password</source>
<translation>Nauja slaptafraz</translation>
</message>
<message>
<source>Repeat new password</source>
<translation>Pakartokite nauj slaptafraz</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
<message>
<source>Banned Until</source>
<translation>Ublokuotas iki</translation>
</message>
</context>
<context>
<name>VERGEGUI</name>
<message>
<source>Sign &message...</source>
<translation>Pasirayti i&nut...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Sinchronizavimas su tinklu ...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Apvalga</translation>
</message>
<message>
<source>Node</source>
<translation>Takas</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Rodyti pinigins bendr apvalg</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Sandoriai</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Apvelgti sandori istorij</translation>
</message>
<message>
<source>E&xit</source>
<translation>&Ieiti</translation>
</message>
<message>
<source>Quit application</source>
<translation>Ijungti program</translation>
</message>
<message>
<source>&About %1</source>
<translation>&Apie %1</translation>
</message>
<message>
<source>Show information about %1</source>
<translation>Rodyti informacij apie %1</translation>
</message>
<message>
<source>About &Qt</source>
<translation>Apie &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Rodyti informacij apie Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Parinktys...</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&Uifruoti pinigin...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Backup pinigin...</translation>
</message>
<message>
<source>&Change Password...</source>
<translation>&Keisti slaptafraz...</translation>
</message>
<message>
<source>&Sending addresses...</source>
<translation>&Siuniami adresai...</translation>
</message>
<message>
<source>&Receiving addresses...</source>
<translation>&Gaunami adresai...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Atidaryti &URI...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Blokai i naujo indeksuojami...</translation>
</message>
<message>
<source>Send coins to a VERGE address</source>
<translation>Sisti monetas VERGE adresui</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Daryti pinigins atsargin kopij</translation>
</message>
<message>
<source>Change the password used for wallet encryption</source>
<translation>Pakeisti slaptafraz naudojam pinigins uifravimui</translation>
</message>
<message>
<source>&Debug window</source>
<translation>&Derinimo langas</translation>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation>Atverti derinimo ir diagnostikos konsol</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>&Tikrinti inut...</translation>
</message>
<message>
<source>VERGE</source>
<translation>VERGE</translation>
</message>
<message>
<source>Wallet</source>
<translation>Pinigin</translation>
</message>
<message>
<source>&Send</source>
<translation>&Sisti</translation>
</message>
<message>
<source>&Receive</source>
<translation>&Gauti</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Rodyti / Slpti</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Rodyti arba slpti pagrindin lang</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Uifruoti privaius raktus, kurie priklauso js piniginei</translation>
</message>
<message>
<source>&File</source>
<translation>&Failas</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Nustatymai</translation>
</message>
<message>
<source>&Help</source>
<translation>&Pagalba</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Korteli rankin</translation>
</message>
<message>
<source>&Command-line options</source>
<translation>Komandins eiluts parametrai</translation>
</message>
<message>
<source>Error</source>
<translation>Klaida</translation>
</message>
<message>
<source>Warning</source>
<translation>spjimas</translation>
</message>
<message>
<source>Information</source>
<translation>Informacija</translation>
</message>
<message>
<source>Up to date</source>
<translation>Atnaujinta</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Vejamasi...</translation>
</message>
<message>
<source>Date: %1
</source>
<translation>Data: %1
</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Sandoris nusistas</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Ateinantis sandoris</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Pinigin <b>uifruota</b> ir iuo metu <b>atrakinta</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Pinigin <b>uifruota</b> ir iuo metu <b>urakinta</b></translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Coin Selection</source>
<translation>Monet pasirinkimas</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Kiekis:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Baitai:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Suma:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Mokestis:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Po mokesio:</translation>
</message>
<message>
<source>Change:</source>
<translation>Graa:</translation>
</message>
<message>
<source>(un)select all</source>
<translation>(ne)pasirinkti visk</translation>
</message>
<message>
<source>Tree mode</source>
<translation>Medio reimas</translation>
</message>
<message>
<source>List mode</source>
<translation>Srao reimas</translation>
</message>
<message>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Patvirtinimai</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Patvirtintas</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Keisti adres</translation>
</message>
<message>
<source>&Label</source>
<translation>&ym</translation>
</message>
<message>
<source>&Address</source>
<translation>&Adresas</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>name</source>
<translation>pavadinimas</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>versija</translation>
</message>
<message>
<source>Command-line options</source>
<translation>Komandins eiluts parametrai</translation>
</message>
<message>
<source>Usage:</source>
<translation>Naudojimas:</translation>
</message>
<message>
<source>command-line options</source>
<translation>komandins eiluts parametrai</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Sveiki</translation>
</message>
<message>
<source>VERGE</source>
<translation>VERGE</translation>
</message>
<message>
<source>Error</source>
<translation>Klaida</translation>
</message>
</context>
<context>
<name>ModalOverlay</name>
<message>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<source>Last block time</source>
<translation>Paskutinio bloko laikas</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Parinktys</translation>
</message>
<message>
<source>&Main</source>
<translation>&Pagrindins</translation>
</message>
<message>
<source>MB</source>
<translation>MB</translation>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>Proxy IP adresas (Pvz. IPv4: 127.0.0.1 / IPv6: ::1)</translation>
</message>
<message>
<source>&Reset Options</source>
<translation>&Atstatyti Parinktis</translation>
</message>
<message>
<source>&Network</source>
<translation>&Tinklas</translation>
</message>
<message>
<source>W&allet</source>
<translation>Pinigin</translation>
</message>
<message>
<source>Automatically open the VERGE client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatikai atidaryti VERGE kliento prievad marrutizatoriuje. Tai veikia tik tada, kai js marrutizatorius palaiko UPnP ir ji jungta.</translation>
</message>
<message>
<source>Map port using &UPnP</source>
<translation>Persisti prievad naudojant &UPnP</translation>
</message>
<message>
<source>Proxy &IP:</source>
<translation>Tarpinio serverio &IP:</translation>
</message>
<message>
<source>&Port:</source>
<translation>&Prievadas:</translation>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Tarpinio serverio preivadas (pvz, 9050)</translation>
</message>
<message>
<source>IPv4</source>
<translation>IPv4</translation>
</message>
<message>
<source>IPv6</source>
<translation>IPv6</translation>
</message>
<message>
<source>Tor</source>
<translation>Tor</translation>
</message>
<message>
<source>&Window</source>
<translation>&Langas</translation>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Po programos lango sumainimo rodyti tik programos ikon.</translation>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&M sumainti lang bet ne uduoi juost</translation>
</message>
<message>
<source>M&inimize on close</source>
<translation>&Sumainti udarant</translation>
</message>
<message>
<source>&Display</source>
<translation>&Rodymas</translation>
</message>
<message>
<source>User Interface &language:</source>
<translation>Naudotojo ssajos &kalba:</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>&Vienetai, kuriais rodyti sumas:</translation>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Rodom ir siuniam monet kiekio matavimo vienetai</translation>
</message>
<message>
<source>&OK</source>
<translation>&Gerai</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Ataukti</translation>
</message>
<message>
<source>default</source>
<translation>numatyta</translation>
</message>
<message>
<source>none</source>
<translation>niekas</translation>
</message>
<message>
<source>Confirm options reset</source>
<translation>Patvirtinti nustatym atstatym</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>Kliento perkrovimas reikalingas nustatym aktyvavimui</translation>
</message>
<message>
<source>Error</source>
<translation>Klaida</translation>
</message>
<message>
<source>This change would require a client restart.</source>
<translation>is pakeitimas reikalaut kliento perkrovimo</translation>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation>Nurodytas tarpinio serverio adresas negalioja.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<source>Available:</source>
<translation>Galimi:</translation>
</message>
<message>
<source>Your current spendable balance</source>
<translation>Js dabartinis ileidiamas balansas</translation>
</message>
<message>
<source>Pending:</source>
<translation>Laukiantys:</translation>
</message>
<message>
<source>Immature:</source>
<translation>Nepribrend:</translation>
</message>
<message>
<source>Total:</source>
<translation>Viso:</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>Js balansas</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>Received</source>
<translation>Gauta</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 h</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 m</translation>
</message>
<message>
<source>N/A</source>
<translation>nra</translation>
</message>
<message>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<source>%1 KB</source>
<translation>%1 KB</translation>
</message>
<message>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<source>unknown</source>
<translation>neinomas</translation>
</message>
</context>
<context>
<name>QObject::QObject</name>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>nra</translation>
</message>
<message>
<source>Client version</source>
<translation>Kliento versija</translation>
</message>
<message>
<source>&Information</source>
<translation>&Informacija</translation>
</message>
<message>
<source>Debug window</source>
<translation>Derinimo langas</translation>
</message>
<message>
<source>Startup time</source>
<translation>Paleidimo laikas</translation>
</message>
<message>
<source>Network</source>
<translation>Tinklas</translation>
</message>
<message>
<source>Name</source>
<translation>Pavadinimas</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Prisijungim kiekis</translation>
</message>
<message>
<source>Block chain</source>
<translation>Blok grandin</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Dabartinis blok skaiius</translation>
</message>
<message>
<source>Received</source>
<translation>Gauta</translation>
</message>
<message>
<source>Direction</source>
<translation>Kryptis</translation>
</message>
<message>
<source>Version</source>
<translation>Versija</translation>
</message>
<message>
<source>Last block time</source>
<translation>Paskutinio bloko laikas</translation>
</message>
<message>
<source>&Open</source>
<translation>&Atverti</translation>
</message>
<message>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<source>Totals</source>
<translation>Viso:</translation>
</message>
<message>
<source>Debug log file</source>
<translation>Derinimo urnalo failas</translation>
</message>
<message>
<source>Clear console</source>
<translation>Ivalyti konsol</translation>
</message>
<message>
<source>never</source>
<translation>Niekada</translation>
</message>
<message>
<source>Yes</source>
<translation>Taip</translation>
</message>
<message>
<source>No</source>
<translation>Ne</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>Suma:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&ym:</translation>
</message>
<message>
<source>&Message:</source>
<translation>inut:</translation>
</message>
<message>
<source>Clear</source>
<translation>Ivalyti</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation>QR kodas</translation>
</message>
<message>
<source>Copy &Address</source>
<translation>&Kopijuoti adres</translation>
</message>
<message>
<source>Address</source>
<translation>Adresas</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Sisti monetas</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Nepakanka l</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Kiekis:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Baitai:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Suma:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Mokestis:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Po mokesio:</translation>
</message>
<message>
<source>Change:</source>
<translation>Graa:</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Sandorio mokestis:</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Sisti keliems gavjams vienu metu</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>&A Pridti gavj</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Ivalyti &visk</translation>
</message>
<message>
<source>Balance:</source>
<translation>Balansas:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Patvirtinti siuntimo veiksm</translation>
</message>
<message>
<source>S&end</source>
<translation>&Sisti</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Su&ma:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>Mokti &gavjui:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&ym:</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>vesti adres i main atminties</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Message:</source>
<translation>inut:</translation>
</message>
<message>
<source>Pay To:</source>
<translation>Mokti gavjui:</translation>
</message>
</context>
<context>
<name>SendConfirmationDialog</name>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>&Sign Message</source>
<translation>&Pasirayti inut</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>vesti adres i main atminties</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation>veskite praneim, kur norite pasirayti ia</translation>
</message>
<message>
<source>Sign the message to prove you own this VERGE address</source>
<translation>Registruotis inute rodymuii, kad turite adres</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Registruoti pranei&m</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Ivalyti &visk</translation>
</message>
<message>
<source>&Verify Message</source>
<translation>&Patikrinti inut</translation>
</message>
<message>
<source>Verify the message to ensure it was signed with the specified VERGE address</source>
<translation>Patikrinkite inut, jog sitikintumte, kad j pasira nurodytas VERGE adresas</translation>
</message>
<message>
<source>Verify &Message</source>
<translation>&Patikrinti inut</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testavimotinklas]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation>KB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>is langas sandorio detal apraym</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
</context>
<context>
<name>TransactionView</name>
<message>
<source>Address</source>
<translation>Adresas</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>verge-core</name>
<message>
<source>Options:</source>
<translation>Parinktys:</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>Nustatyti duomen aplank</translation>
</message>
<message>
<source>Specify your own public address</source>
<translation>Nurodykite savo nuosav vie adres</translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>Priimti komandin eilut ir JSON-RPC komandas</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>Dirbti fone kaip elyje ir priimti komandas</translation>
</message>
<message>
<source>VERGE Core</source>
<translation>VERGE branduolys</translation>
</message>
<message>
<source>Error opening block database</source>
<translation>Klaida atveriant blok duombaz</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>Tikrinami blokai...</translation>
</message>
<message>
<source>Information</source>
<translation>Informacija</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Sisti atsekimo/derinimo info konsol vietoj debug.log failo</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>Vartotojo vardas JSON-RPC jungimuisi</translation>
</message>
<message>
<source>Warning</source>
<translation>spjimas</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>Slaptaodis JSON-RPC sujungimams</translation>
</message>
<message>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Leisti DNS paiek sujungimui ir mazgo pridjimui</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Nepakanka l</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>keliamas blok indeksas...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Ukraunama pinigin...</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Perira</translation>
</message>
<message>
<source>Done loading</source>
<translation>klimas baigtas</translation>
</message>
<message>
<source>Error</source>
<translation>Klaida</translation>
</message>
</context>
</TS>
``` | /content/code_sandbox/src/qt/locale/verge_lt.ts | xml | 2016-01-23T04:20:14 | 2024-08-13T18:07:31 | verge | vergecurrency/verge | 1,402 | 7,934 |
```xml
<vector xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:width="611dp"
android:height="512dp"
android:viewportWidth="611.2"
android:viewportHeight="512.0"
tools:keep="@drawable/fa_amazon_pay">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M0,325.2c2.3,-4.2 5.2,-4.9 9.7,-2.5 10.4,5.6 20.6,11.4 31.2,16.7 40.7,20.4 83.2,35.6 127.4,46.3 20.9,5 41.9,9 63.2,11.8 31.5,4.2 63.2,6 95,5.2 17.4,-0.4 34.8,-1.8 52.1,-3.8 56.4,-6.7 110.9,-20.8 163.3,-42.8 2.9,-1.2 5.9,-2 9.1,-1.2 6.7,1.8 9,9 4.1,13.9 -2.8,2.8 -6.3,5.1 -9.6,7.4 -30.7,21.1 -64.2,36.4 -99.6,47.9 -24.6,7.9 -49.6,13.8 -75.1,17.6 -17.6,2.6 -35.4,4.4 -53.2,4.8 -0.8,0 -1.7,0.2 -2.5,0.3L294,446.8c-0.8,-0.1 -1.7,-0.3 -2.5,-0.3 -3.6,-0.2 -7.2,-0.3 -10.7,-0.4 -16.9,-0.7 -33.7,-2.6 -50.4,-5.3 -27.4,-4.5 -54.2,-11.4 -80.4,-20.9 -54.1,-19.6 -102.6,-48.6 -145.6,-87 -1.8,-1.6 -3,-3.8 -4.4,-5.7v-2zM158,65c-1.4,0.2 -2.9,0.4 -4.3,0.6 -14,1.7 -26.6,6.9 -38,15.1 -2.4,1.7 -4.6,3.5 -7.1,5.4 -0.2,-0.5 -0.4,-1 -0.4,-1.4 -0.4,-2.7 -0.8,-5.5 -1.3,-8.2 -0.7,-4.6 -3,-6.6 -7.6,-6.6L87.8,69.9c-6.9,0 -8.2,1.3 -8.2,8.2v209.3c0,1 0,2 0.1,3 0.2,3 2,4.9 4.9,5 7,0.1 14.1,0.1 21.1,0 2.9,0 4.7,-2 5,-5 0.1,-1 0.1,-2 0.1,-3L110.8,215c1.1,0.9 1.7,1.4 2.2,1.9 17.9,14.9 38.5,19.8 61,15.4 20.4,-4 34.6,-16.5 43.8,-34.9 7,-13.9 9.9,-28.7 10.3,-44.1 0.5,-17.1 -1.2,-33.9 -8.1,-49.8 -8.5,-19.6 -22.6,-32.5 -43.9,-36.9 -3.2,-0.7 -6.5,-1 -9.8,-1.5 -2.8,-0.1 -5.5,-0.1 -8.3,-0.1zM110.6,106.9c0,-1.5 0.4,-2.4 1.7,-3.3 13.7,-9.5 28.8,-14.5 45.6,-13.2 14.9,1.1 27.1,8.4 33.5,25.9 3.9,10.7 4.9,21.8 4.9,33 0,10.4 -0.8,20.6 -4,30.6 -6.8,21.3 -22.4,29.4 -42.6,28.5 -14,-0.6 -26.2,-6 -37.4,-13.9 -1.2,-0.9 -1.7,-1.7 -1.7,-3.3 0.1,-14.1 0,-28.1 0,-42.2 0,-14 0.1,-28 0,-42.1zM316.3,65c-1,0.1 -2,0.3 -2.9,0.4 -9.8,0.5 -19.4,1.7 -28.9,4.1 -6.1,1.6 -12,3.8 -17.9,5.8 -3.6,1.2 -5.4,3.8 -5.3,7.7 0.1,3.3 -0.1,6.6 0,9.9 0.1,4.8 2.1,6.1 6.8,4.9 7.8,-2 15.6,-4.2 23.5,-5.7 12.3,-2.3 24.7,-3.3 37.2,-1.4 6.5,1 12.6,2.9 16.8,8.4 3.7,4.8 5.1,10.5 5.3,16.4 0.3,8.3 0.2,16.6 0.3,24.9 0,0.4 -0.1,0.9 -0.2,1.4 -0.5,-0.1 -0.9,0 -1.3,-0.1 -10.5,-2.5 -21.1,-4.3 -32,-4.9 -11.3,-0.6 -22.5,0.1 -33.3,3.9 -12.9,4.5 -23.3,12.3 -29.4,24.9 -4.7,9.8 -5.4,20.2 -3.9,30.7 2,14 9,24.8 21.4,31.7 11.9,6.6 24.8,7.4 37.9,5.4 15.1,-2.3 28.5,-8.7 40.3,-18.4 0.4,-0.4 0.9,-0.7 1.6,-1.1 0.6,3.8 1.1,7.4 1.8,11 0.6,3.1 2.5,5.1 5.4,5.2 5.4,0.1 10.9,0.1 16.3,0 2.7,-0.1 4.5,-1.9 4.8,-4.7 0.1,-0.9 0.1,-1.9 0.1,-2.8v-106c0,-4.3 -0.2,-8.6 -0.9,-12.9 -1.9,-12.9 -7.4,-23.5 -19,-30.4 -6.7,-4 -14.1,-6 -21.8,-7.1 -3.6,-0.5 -7.2,-0.8 -10.8,-1.3 -3.9,0.1 -7.9,0.1 -11.9,0.1zM351.3,192.7c0,1.3 -0.4,2.2 -1.5,3 -11.2,8.1 -23.5,13.5 -37.4,14.9 -5.7,0.6 -11.4,0.4 -16.8,-1.8 -6.3,-2.5 -10.4,-6.9 -12.4,-13.3s-2,-13 -0.1,-19.4c2.5,-8.3 8.4,-13 16.4,-15.6 8.1,-2.6 16.5,-3 24.8,-2.2 8.4,0.7 16.6,2.3 25,3.4 1.6,0.2 2.1,1 2.1,2.6 -0.1,4.8 0,9.5 0,14.3 -0.1,4.7 -0.2,9.4 -0.1,14.1zM611.2,322.1c-1,-5 -4.8,-6.9 -9.1,-8.3 -6.8,-2.3 -13.9,-3.3 -21,-3.9 -13.1,-1.1 -26.2,-0.5 -39.2,1.9 -14.3,2.7 -27.9,7.3 -40,15.6 -1.4,1 -2.8,2.1 -3.7,3.5 -0.7,1.1 -0.9,2.8 -0.5,4 0.4,1.5 2.1,1.9 3.6,1.8 0.7,0 1.5,0 2.2,-0.1 7.8,-0.8 15.5,-1.7 23.3,-2.5 11.4,-1.1 22.9,-1.8 34.3,-0.9 4.8,0.3 9.7,1.4 14.4,2.7 5.1,1.4 7.4,5.2 7.6,10.4 0.4,8 -1.4,15.7 -3.5,23.3 -4.1,15.4 -10,30.3 -15.8,45.1 -0.4,1 -0.8,2 -1,3 -0.5,2.9 1.2,4.8 4.1,4.1 1.7,-0.4 3.6,-1.3 4.8,-2.5 4.4,-4.3 8.9,-8.6 12.7,-13.4 12.8,-16.4 20.3,-35.3 24.7,-55.6 0.8,-3.6 1.4,-7.3 2.1,-10.9v-17.3zM479.1,198.9c-12.9,-35.7 -25.8,-71.5 -38.7,-107.2 -2,-5.7 -4.2,-11.3 -6.3,-16.9 -1.1,-2.9 -3.2,-4.8 -6.4,-4.8 -7.6,-0.1 -15.2,-0.2 -22.9,-0.1 -2.5,0 -3.7,2 -3.2,4.5 0.5,2.1 1.1,4.1 1.9,6.1 19.6,48.5 39.3,97.1 59.1,145.5 1.7,4.1 2.1,7.6 0.2,11.8 -3.3,7.3 -5.9,15 -9.3,22.3 -3,6.5 -8,11.4 -15.2,13.3 -5.1,1.4 -10.2,1.6 -15.4,1.1 -2.5,-0.2 -5,-0.8 -7.5,-1 -3.4,-0.2 -5.1,1.3 -5.2,4.8 -0.1,3.3 -0.1,6.6 0,9.9 0.1,5.5 2,8 7.4,8.9 5.6,1 11.3,1.9 16.9,2 17.1,0.4 30.7,-6.5 39.5,-21.4 3.5,-5.9 6.7,-12.1 9.2,-18.4 23.7,-59.8 47.1,-119.7 70.6,-179.6 0.7,-1.8 1.3,-3.6 1.6,-5.5 0.4,-2.8 -0.9,-4.4 -3.7,-4.4 -6.6,-0.1 -13.3,0 -19.9,0 -3.7,0 -6.3,1.6 -7.7,5.2 -0.5,1.4 -1.1,2.7 -1.6,4.1 -11.6,33.3 -23.2,66.6 -34.8,100 -2.5,7.2 -5.1,14.5 -7.7,22.2 -0.4,-1.1 -0.6,-1.7 -0.9,-2.4z"/>
</vector>
``` | /content/code_sandbox/mobile/src/main/res/drawable/fa_amazon_pay.xml | xml | 2016-10-24T13:23:25 | 2024-08-16T07:20:37 | freeotp-android | freeotp/freeotp-android | 1,387 | 3,292 |
```xml
import { FieldType, SecureNoteType, CipherType } from "@bitwarden/common/vault/enums";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { FieldView } from "@bitwarden/common/vault/models/view/field.view";
import { FolderView } from "@bitwarden/common/vault/models/view/folder.view";
import { SecureNoteView } from "@bitwarden/common/vault/models/view/secure-note.view";
import { ImportResult } from "../models/import-result";
import { BaseImporter } from "./base-importer";
import { Importer } from "./importer";
export class SafeInCloudXmlImporter extends BaseImporter implements Importer {
parse(data: string): Promise<ImportResult> {
const result = new ImportResult();
const doc = this.parseXml(data);
if (doc == null) {
result.success = false;
return Promise.resolve(result);
}
const db = doc.querySelector("database");
if (db == null) {
result.errorMessage = "Missing `database` node.";
result.success = false;
return Promise.resolve(result);
}
const foldersMap = new Map<string, number>();
Array.from(doc.querySelectorAll("database > label")).forEach((labelEl) => {
const name = labelEl.getAttribute("name");
const id = labelEl.getAttribute("id");
if (!this.isNullOrWhitespace(name) && !this.isNullOrWhitespace(id)) {
foldersMap.set(id, result.folders.length);
const folder = new FolderView();
folder.name = name;
result.folders.push(folder);
}
});
Array.from(doc.querySelectorAll("database > card")).forEach((cardEl) => {
if (cardEl.getAttribute("template") === "true" || cardEl.getAttribute("deleted") === "true") {
return;
}
const labelIdEl = this.querySelectorDirectChild(cardEl, "label_id");
if (labelIdEl != null) {
const labelId = labelIdEl.textContent;
if (!this.isNullOrWhitespace(labelId) && foldersMap.has(labelId)) {
result.folderRelationships.push([result.ciphers.length, foldersMap.get(labelId)]);
}
}
const cipher = this.initLoginCipher();
cipher.name = this.getValueOrDefault(cardEl.getAttribute("title"), "--");
if (cardEl.getAttribute("star") === "true") {
cipher.favorite = true;
}
const cardType = cardEl.getAttribute("type");
if (cardType === "note") {
cipher.type = CipherType.SecureNote;
cipher.secureNote = new SecureNoteView();
cipher.secureNote.type = SecureNoteType.Generic;
} else {
Array.from(this.querySelectorAllDirectChild(cardEl, "field")).forEach((fieldEl) => {
const text = fieldEl.textContent;
if (this.isNullOrWhitespace(text)) {
return;
}
const name = fieldEl.getAttribute("name");
const fieldType = this.getValueOrDefault(fieldEl.getAttribute("type"), "").toLowerCase();
if (fieldType === "login") {
cipher.login.username = text;
} else if (fieldType === "password" || fieldType === "secret") {
// safeInCloud allows for more than one password. we just insert them here and find the one used as password later
this.processKvp(cipher, name, text, FieldType.Hidden);
} else if (fieldType === "one_time_password") {
cipher.login.totp = text;
} else if (fieldType === "notes") {
cipher.notes += text + "\n";
} else if (fieldType === "weblogin" || fieldType === "website") {
cipher.login.uris.push(...this.makeUriArray(text));
} else {
this.processKvp(cipher, name, text);
}
});
}
Array.from(this.querySelectorAllDirectChild(cardEl, "notes")).forEach((notesEl) => {
cipher.notes += notesEl.textContent + "\n";
});
this.setPassword(cipher);
this.cleanupCipher(cipher);
result.ciphers.push(cipher);
});
if (this.organization) {
this.moveFoldersToCollections(result);
}
result.success = true;
return Promise.resolve(result);
}
// Choose a password from all passwords. Take one that has password in its name, or the first one if there is no such entry
// if its name is password, we can safely remove it form the fields. otherwise, it would maybe be best to keep it as a hidden field
setPassword(cipher: CipherView) {
const candidates = cipher.fields.filter((field) => field.type === FieldType.Hidden);
if (!candidates.length) {
return;
}
let choice: FieldView;
for (const field of candidates) {
if (this.passwordFieldNames.includes(field.name.toLowerCase())) {
choice = field;
cipher.fields = cipher.fields.filter((f) => f !== choice);
break;
}
}
if (!choice) {
choice = candidates[0];
}
cipher.login.password = choice.value;
}
}
``` | /content/code_sandbox/libs/importer/src/importers/safeincloud-xml-importer.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 1,080 |
```xml
import { JSDOMCrawler, log, LogLevel } from 'crawlee';
// Crawlers come with various utilities, e.g. for logging.
// Here we use debug level of logging to improve the debugging experience.
// This functionality is optional!
log.setLevel(LogLevel.DEBUG);
// Create an instance of the JSDOMCrawler class - a crawler
// that automatically loads the URLs and parses their HTML using the jsdom library.
const crawler = new JSDOMCrawler({
// The crawler downloads and processes the web pages in parallel, with a concurrency
// automatically managed based on the available system memory and CPU (see AutoscaledPool class).
// Here we define some hard limits for the concurrency.
minConcurrency: 10,
maxConcurrency: 50,
// On error, retry each page at most once.
maxRequestRetries: 1,
// Increase the timeout for processing of each page.
requestHandlerTimeoutSecs: 30,
// Limit to 10 requests per one crawl
maxRequestsPerCrawl: 10,
// This function will be called for each URL to crawl.
// It accepts a single parameter, which is an object with options as:
// path_to_url#requestHandler
// We use for demonstration only 2 of them:
// - request: an instance of the Request class with information such as the URL that is being crawled and HTTP method
// - window: the JSDOM window object
async requestHandler({ pushData, request, window }) {
log.debug(`Processing ${request.url}...`);
// Extract data from the page
const title = window.document.title;
const h1texts: { text: string }[] = [];
window.document.querySelectorAll('h1').forEach((element) => {
h1texts.push({
text: element.textContent!,
});
});
// Store the results to the dataset. In local configuration,
// the data will be stored as JSON files in ./storage/datasets/default
await pushData({
url: request.url,
title,
h1texts,
});
},
// This function is called if the page processing failed more than maxRequestRetries + 1 times.
failedRequestHandler({ request }) {
log.debug(`Request ${request.url} failed twice.`);
},
});
// Run the crawler and wait for it to finish.
await crawler.run([
'path_to_url
]);
log.debug('Crawler finished.');
``` | /content/code_sandbox/website/versioned_docs/version-3.10/examples/jsdom_crawler.ts | xml | 2016-08-26T18:35:03 | 2024-08-16T16:40:08 | crawlee | apify/crawlee | 14,153 | 523 |
```xml
import '@percy/cypress'
import 'cypress-file-upload'
import 'cy-mobile-commands'
import 'cypress-real-events/support'
import '@mdi/font/css/materialdesignicons.css'
import './mount'
import './selector'
``` | /content/code_sandbox/packages/vuetify/cypress/support/index.ts | xml | 2016-09-12T00:39:35 | 2024-08-16T20:06:39 | vuetify | vuetifyjs/vuetify | 39,539 | 48 |
```xml
import { MAX_ATTENDEES } from '@proton/shared/lib/calendar/constants';
import { ADDRESS_SEND } from '@proton/shared/lib/constants';
import { addressBuilder } from '@proton/testing/lib/builders';
import {
getCanChangeCalendarOfEvent,
getCanDeleteEvent,
getCanDuplicateEvent,
getCanEditEvent,
getCanEditSharedEventData,
getCanReplyToEvent,
getCannotSaveEvent,
getIsAvailableCalendar,
} from './event';
describe('getCannotSaveEvent()', () => {
test('Member cannot create invites in a shared calendar', () => {
const isOwnedCalendar = false;
const isOrganizer = true;
const numberOfAttendees = MAX_ATTENDEES - 1;
const canEditSharedEventData = true;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
true
);
});
test('Owner can create invites in a personal calendar', () => {
const isOwnedCalendar = true;
const isOrganizer = true;
const numberOfAttendees = MAX_ATTENDEES - 1;
const canEditSharedEventData = true;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
false
);
});
test('Owner cannot create invites with too many participants', () => {
const isOwnedCalendar = true;
const isOrganizer = true;
const numberOfAttendees = MAX_ATTENDEES + 1;
const canEditSharedEventData = true;
expect(
getCannotSaveEvent({
isOwnedCalendar,
isOrganizer,
numberOfAttendees,
canEditSharedEventData,
maxAttendees: MAX_ATTENDEES,
})
).toEqual(true);
});
test('Attendee can add notifications to invite in a personal calendar', () => {
const isOwnedCalendar = true;
const isOrganizer = false;
const numberOfAttendees = MAX_ATTENDEES - 1;
const canEditSharedEventData = false;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
false
);
});
test('Attendee can add notifications to invite in a shared calendar', () => {
const isOwnedCalendar = false;
const isOrganizer = false;
const numberOfAttendees = MAX_ATTENDEES - 1;
const canEditSharedEventData = false;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
false
);
});
test('Member can add notifications to an invite she organized in a shared calendar', () => {
const isOwnedCalendar = false;
const isOrganizer = true;
const numberOfAttendees = 10;
const canEditSharedEventData = false;
expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual(
false
);
});
});
describe('getCanEditEvent()', () => {
test('User can edit events only if the calendar is of known type and is not disabled', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isUnknownCalendar = !!(1 & i);
const isCalendarDisabled = !!(2 & i);
combinations.push({ isUnknownCalendar, isCalendarDisabled });
}
combinations.forEach(({ isUnknownCalendar, isCalendarDisabled }) => {
expect(
getCanEditEvent({
isUnknownCalendar,
isCalendarDisabled,
})
).toEqual(!isCalendarDisabled && !isUnknownCalendar);
});
});
});
describe('getCanDeleteEvent()', () => {
test('User cannot delete events in subscribed or other read-only calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isInvitation = !!(2 & i);
combinations.push({ isOwnedCalendar, isInvitation });
}
combinations.forEach(({ isOwnedCalendar, isInvitation }) => {
expect(
getCanDeleteEvent({
isOwnedCalendar,
isCalendarWritable: false,
isInvitation,
})
).toEqual(false);
});
});
test('Attendee can delete invites in her own calendar', () => {
const isOwnedCalendar = true;
const isCalendarWritable = true;
const isInvitation = true;
expect(getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable, isInvitation })).toEqual(true);
});
test('Member cannot delete invites in a shared calendar with edit rights', () => {
const isOwnedCalendar = false;
const isCalendarWritable = true;
const isInvitation = true;
expect(getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable, isInvitation })).toEqual(false);
});
test('Member cannot delete invites in a shared calendar with view-only rights', () => {
const isOwnedCalendar = false;
const isCalendarWritable = false;
const isInvitation = true;
expect(getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable, isInvitation })).toEqual(false);
});
});
describe('getCanEditSharedEventData()', () => {
const activeAddress = addressBuilder();
const cannotSendAddress = {
...activeAddress,
Send: ADDRESS_SEND.SEND_NO,
};
test('Owner can edit shared event data of events which are not invitations', () => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: true,
isOrganizer: false,
isAttendee: false,
isInvitation: false,
selfAddress: undefined,
})
).toEqual(true);
});
test('Owner can edit shared event data of events she organizes if the address is active', () => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: true,
isOrganizer: true,
isAttendee: false,
isInvitation: false,
selfAddress: activeAddress,
})
).toEqual(true);
});
test('Owner cannot edit shared event data of events she organizes if the address cannot send', () => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: true,
isOrganizer: true,
isAttendee: false,
isInvitation: true,
selfAddress: cannotSendAddress,
})
).toEqual(false);
});
test('User cannot edit shared event data in subscribed calendars or other read-only calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 3; i++) {
const isOrganizer = !!(1 & i);
const isAttendee = !!(2 & i);
const isInvitation = isOrganizer || isAttendee || !!(4 & i);
const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined;
combinations.push({ isOrganizer, isAttendee, isInvitation, selfAddress });
}
combinations.forEach(({ isOrganizer, isAttendee, isInvitation, selfAddress }) => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: false,
isOrganizer,
isAttendee,
isInvitation,
selfAddress,
})
).toEqual(false);
});
});
test('Member cannot edit shared event data in shared calendars with view-only rights', () => {
const combinations = [];
for (let i = 0; i < 2 ** 3; i++) {
const isOrganizer = !!(1 & i);
const isAttendee = !!(2 & i);
const isInvitation = isOrganizer || isAttendee || !!(4 & i);
const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined;
combinations.push({ isOrganizer, isAttendee, isInvitation, selfAddress });
}
combinations.forEach(({ isOrganizer, isAttendee, isInvitation, selfAddress }) => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: false,
isCalendarWritable: false,
isOrganizer,
isAttendee,
isInvitation,
selfAddress,
})
).toEqual(false);
});
});
test('Member with edit rights cannot edit shared event data of invitations', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOrganizer = !!(1 & i);
const isAttendee = !!(2 & i);
const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined;
combinations.push({ isOrganizer, isAttendee, selfAddress });
}
combinations.forEach(({ isOrganizer, isAttendee, selfAddress }) => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: false,
isCalendarWritable: true,
isOrganizer,
isAttendee,
isInvitation: true,
selfAddress,
})
).toEqual(false);
});
});
test('Member with view-only rights cannot edit invitations', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOrganizer = !!(1 & i);
const isAttendee = !!(2 & i);
const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined;
combinations.push({ isOrganizer, isAttendee, selfAddress });
}
combinations.forEach(({ isOrganizer, isAttendee, selfAddress }) => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: false,
isCalendarWritable: false,
isOrganizer,
isAttendee,
isInvitation: true,
selfAddress,
})
).toEqual(false);
});
});
test('User cannot edit invitations in owned calendars if she is not organizing or attending', () => {
expect(
getCanEditSharedEventData({
isOwnedCalendar: true,
isCalendarWritable: true,
isOrganizer: false,
isAttendee: false,
isInvitation: true,
selfAddress: undefined,
})
).toEqual(false);
});
});
describe('getCanChangeCalendar()', () => {
test('User can change calendar of events that are not invitations', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isSingleEdit = !!(2 & i);
combinations.push({ isOwnedCalendar, isSingleEdit });
}
combinations.forEach(({ isOwnedCalendar, isSingleEdit }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar,
isCalendarWritable: true,
isSingleEdit,
isInvitation: false,
isAttendee: false,
isOrganizer: false,
})
).toEqual(true);
});
});
test('User creating event can change calendar', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isOrganizer = !!(2 & i);
const isInvitation = isOrganizer;
combinations.push({ isOwnedCalendar, isOrganizer, isInvitation });
}
combinations.forEach(({ isOwnedCalendar, isInvitation, isOrganizer }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: true,
isOwnedCalendar,
isCalendarWritable: true,
isSingleEdit: false,
isInvitation,
isAttendee: false,
isOrganizer,
})
).toEqual(true);
});
});
test('User cannot change calendar of event in non-writable calendar', () => {
const combinations = [];
for (let i = 0; i < 2 ** 5; i++) {
const isOwnedCalendar = !!(1 & i);
const isSingleEdit = !!(2 & i);
const isOrganizer = !!(4 & i);
const isAttendee = isOrganizer ? false : !!(8 & i);
const isInvitation = isOrganizer || isAttendee ? true : !!(16 & i);
combinations.push({ isOwnedCalendar, isSingleEdit, isInvitation, isOrganizer, isAttendee });
}
combinations.forEach(({ isOwnedCalendar, isSingleEdit, isInvitation, isOrganizer, isAttendee }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar,
isCalendarWritable: false,
isSingleEdit,
isInvitation,
isAttendee,
isOrganizer,
})
).toEqual(false);
});
});
test('Member cannot change calendar of non-organized invitation in shared calendar', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isSingleEdit = !!(1 & i);
const isAttendee = !!(2 & i);
combinations.push({ isSingleEdit, isAttendee });
}
combinations.forEach(({ isSingleEdit, isAttendee }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar: false,
isCalendarWritable: true,
isSingleEdit,
isInvitation: true,
isAttendee,
isOrganizer: false,
})
).toEqual(false);
});
});
test('Organizer cannot change calendar existing invitation', () => {
const combinations = [];
for (let i = 0; i < 2 ** 3; i++) {
const isOwnedCalendar = !!(1 & i);
const isCalendarWritable = !!(2 & i);
const isSingleEdit = !!(4 & i);
combinations.push({ isOwnedCalendar, isCalendarWritable, isSingleEdit });
}
combinations.forEach(({ isOwnedCalendar, isCalendarWritable, isSingleEdit }) => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar,
isCalendarWritable,
isSingleEdit,
isInvitation: true,
isAttendee: false,
isOrganizer: true,
})
).toEqual(false);
});
});
test('Attendee can change calendar in owned calendars if the event is not a single edit', () => {
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar: true,
isCalendarWritable: true,
isSingleEdit: false,
isInvitation: true,
isAttendee: true,
isOrganizer: false,
})
).toEqual(true);
expect(
getCanChangeCalendarOfEvent({
isCreateEvent: false,
isOwnedCalendar: true,
isCalendarWritable: true,
isSingleEdit: true,
isInvitation: true,
isAttendee: true,
isOrganizer: false,
})
).toEqual(false);
});
});
describe('getIsAvailableCalendar()', () => {
test('User cannot change calendar of events to subscribed or other read-only calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isInvitation = !!(2 & i);
combinations.push({ isOwnedCalendar, isInvitation });
}
combinations.forEach(({ isOwnedCalendar, isInvitation }) => {
expect(
getIsAvailableCalendar({
isOwnedCalendar,
isCalendarWritable: false,
isInvitation,
})
).toEqual(false);
});
});
test('Invitations can only be changed to owned calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOwnedCalendar = !!(1 & i);
const isCalendarWritable = isOwnedCalendar || !!(2 & i);
combinations.push({ isOwnedCalendar, isCalendarWritable });
}
combinations.forEach(({ isOwnedCalendar, isCalendarWritable }) => {
expect(
getIsAvailableCalendar({
isOwnedCalendar,
isCalendarWritable,
isInvitation: true,
})
).toEqual(isOwnedCalendar);
});
});
test('Events that are not invitations can be changed to writable calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 1; i++) {
const isOwnedCalendar = !!(1 & i);
const isCalendarWritable = isOwnedCalendar || !!(2 & i);
combinations.push({ isOwnedCalendar, isCalendarWritable });
}
combinations.forEach(({ isOwnedCalendar, isCalendarWritable }) => {
expect(
getIsAvailableCalendar({
isOwnedCalendar,
isCalendarWritable,
isInvitation: true,
})
).toEqual(isCalendarWritable);
});
});
});
describe('getCanDuplicateEvent()', () => {
test('User cannot duplicate events in unknown calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 4; i++) {
const isSubscribedCalendar = !!(1 & i);
const isOwnedCalendar = !!(2 & i);
const isOrganizer = !!(4 & i);
const isInvitation = !!(8 & i);
combinations.push({ isSubscribedCalendar, isOwnedCalendar, isOrganizer, isInvitation });
}
combinations.forEach(({ isSubscribedCalendar, isOwnedCalendar, isOrganizer, isInvitation }) => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: true,
isSubscribedCalendar,
isOwnedCalendar,
isInvitation,
isOrganizer,
})
).toEqual(false);
});
});
test('User cannot duplicate events in subscribed calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isOrganizer = !!(1 & i);
const isInvitation = isOrganizer || !!(2 & i);
combinations.push({ isOrganizer, isInvitation });
}
combinations.forEach(({ isOrganizer, isInvitation }) => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: true,
isOwnedCalendar: true,
isInvitation,
isOrganizer,
})
).toEqual(false);
});
});
test('Owner can duplicate events that are not invitations', () => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: true,
isInvitation: false,
isOrganizer: false,
})
).toEqual(true);
});
test('Owner can duplicate invitations that she is organizing', () => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: true,
isInvitation: true,
isOrganizer: true,
})
).toEqual(true);
});
test('Owner cannot duplicate invitations if she is not the organizer', () => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: true,
isInvitation: true,
isOrganizer: false,
})
).toEqual(false);
});
test('Member can duplicate events that are not invitations', () => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: false,
isInvitation: false,
isOrganizer: false,
})
).toEqual(true);
});
test('Member cannot duplicate invitations', () => {
const combinations = [];
for (let i = 0; i < 2 ** 1; i++) {
const isOrganizer = !!(1 & i);
combinations.push({ isOrganizer });
}
combinations.forEach(({ isOrganizer }) => {
expect(
getCanDuplicateEvent({
isUnknownCalendar: false,
isSubscribedCalendar: false,
isOwnedCalendar: false,
isInvitation: true,
isOrganizer,
})
).toEqual(false);
});
});
});
describe('getCanReplyToEvent()', () => {
test('User can reply to events he is invited in one of his own personal calendars if and only if the event is not cancelled', () => {
const combinations = [];
for (let i = 0; i < 2 ** 1; i++) {
const isCancelled = !!(1 & i);
combinations.push({ isCancelled });
}
combinations.forEach(({ isCancelled }) => {
expect(
getCanReplyToEvent({
isOwnedCalendar: true,
isCalendarWritable: true,
isAttendee: true,
isCancelled,
})
).toEqual(!isCancelled);
});
});
test('User cannot reply to events he is not attending', () => {
const combinations = [];
for (let i = 0; i < 2 ** 3; i++) {
const isOwnedCalendar = !!(1 & i);
const isCalendarWritable = isOwnedCalendar || !!(2 & i);
const isCancelled = !!(4 & i);
combinations.push({ isOwnedCalendar, isCalendarWritable, isCancelled });
}
combinations.forEach(({ isOwnedCalendar, isCalendarWritable, isCancelled }) => {
expect(
getCanReplyToEvent({
isOwnedCalendar,
isCalendarWritable,
isAttendee: false,
isCancelled,
})
).toEqual(false);
});
});
test('User cannot reply to invitations on subscribed calendars', () => {
const combinations = [];
for (let i = 0; i < 2 ** 1; i++) {
const isCancelled = !!(1 & i);
combinations.push({ isCancelled });
}
combinations.forEach(({ isCancelled }) => {
expect(
getCanReplyToEvent({
isOwnedCalendar: true,
isCalendarWritable: false,
isAttendee: true,
isCancelled,
})
).toEqual(false);
});
});
test('User cannot reply to invitations on shared calendars, with or without edit rights', () => {
const combinations = [];
for (let i = 0; i < 2 ** 2; i++) {
const isCalendarWritable = !!(1 & i);
const isCancelled = !!(2 & i);
combinations.push({ isCalendarWritable, isCancelled });
}
combinations.forEach(({ isCalendarWritable, isCancelled }) => {
expect(
getCanReplyToEvent({
isOwnedCalendar: false,
isCalendarWritable,
isAttendee: true,
isCancelled,
})
).toEqual(false);
});
});
});
``` | /content/code_sandbox/applications/calendar/src/app/helpers/event.test.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 5,069 |
```xml
import * as React from 'react';
import { cleanup, render, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DefaultButton } from './DefaultButton/DefaultButton';
import { IconButton } from './IconButton/IconButton';
import { ActionButton } from './ActionButton/ActionButton';
import { CommandBarButton } from './CommandBarButton/CommandBarButton';
import { CompoundButton } from './CompoundButton/CompoundButton';
import { KeyCodes, resetIds } from '../../Utilities';
import type { IContextualMenuProps } from '../../ContextualMenu';
const alertClicked = (): void => {
/*noop*/
};
describe('Button', () => {
beforeEach(() => {
resetIds();
cleanup();
document.body.innerHTML = '';
});
it('renders DefaultButton correctly', () => {
const { container } = render(<DefaultButton text="Button" />);
expect(container).toMatchSnapshot();
});
it('renders ActionButton correctly', () => {
const { container } = render(<ActionButton>Button</ActionButton>);
expect(container).toMatchSnapshot();
});
it('renders a DefaultButton with a keytip correctly', () => {
const keytipProps = {
content: 'A',
keySequences: ['a'],
};
const { container } = render(<DefaultButton text="Button" keytipProps={keytipProps} />);
expect(container).toMatchSnapshot();
});
it('renders CommandBarButton correctly', () => {
const { container } = render(
<CommandBarButton
iconProps={{ iconName: 'Add' }}
text="Create account"
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
expect(container).toMatchSnapshot();
});
it('renders CompoundButton correctly', () => {
const { container } = render(
<CompoundButton secondaryText="You can create a new account here.">Create account</CompoundButton>,
);
expect(container).toMatchSnapshot();
});
it('renders IconButton correctly', () => {
const { container } = render(<IconButton iconProps={{ iconName: 'Emoji2' }} title="Emoji" ariaLabel="Emoji" />);
expect(container).toMatchSnapshot();
});
describe('DefaultButton', () => {
it('can render without an onClick.', () => {
const { container } = render(<DefaultButton>Hello</DefaultButton>);
expect(container.firstElementChild!.tagName).toEqual('BUTTON');
});
it('can render with an onClick.', () => {
const onClick: () => null = () => null;
const { container } = render(<DefaultButton onClick={onClick}>Hello</DefaultButton>);
expect(container.firstElementChild!.tagName).toEqual('BUTTON');
});
it('can render with an href', () => {
const { container } = render(
<DefaultButton href="path_to_url" target="_blank">
Hello
</DefaultButton>,
);
expect(container.firstElementChild!.tagName).toEqual('A');
});
it('can handle elementRef', () => {
const ref = React.createRef<HTMLElement>();
render(<DefaultButton elementRef={ref}>Content</DefaultButton>);
expect(ref.current).toBeTruthy();
});
describe('aria attributes', () => {
it('does not apply aria attributes that are not passed in', () => {
const { getByRole } = render(
<DefaultButton href="path_to_url" target="_blank">
Hello
</DefaultButton>,
);
const button = getByRole('link');
expect(button.getAttribute('aria-label')).toBeNull();
expect(button.getAttribute('aria-labelledby')).toBeNull();
expect(button.getAttribute('aria-describedby')).toBeNull();
expect(button.getAttribute('aria-pressed')).toBeNull();
});
it('overrides native aria-label with Button ariaLabel', () => {
const { getByRole } = render(
<DefaultButton
href="path_to_url"
target="_blank"
aria-label="NativeLabel"
ariaLabel="ButtonLabel"
>
Hello
</DefaultButton>,
);
const button = getByRole('link');
expect(button.getAttribute('aria-label')).toEqual('ButtonLabel');
expect(button.getAttribute('aria-labelledby')).toBeNull();
expect(button.getAttribute('aria-describedby')).toBeNull();
});
it('applies aria-label', () => {
const { getByRole } = render(
<DefaultButton href="path_to_url" target="_blank" aria-label="MyLabel">
Hello
</DefaultButton>,
);
const button = getByRole('link');
expect(button.getAttribute('aria-label')).toEqual('MyLabel');
expect(button.getAttribute('aria-labelledby')).toBeNull();
expect(button.getAttribute('aria-describedby')).toBeNull();
});
it('applies aria-labelledby', () => {
const { getByRole } = render(
<DefaultButton href="path_to_url" target="_blank" aria-labelledby="someid">
Hello
</DefaultButton>,
);
const button = getByRole('link');
expect(button.getAttribute('aria-labelledby')).toEqual('someid');
expect(button.getAttribute('aria-describedby')).toBeNull();
});
it('does not apply aria-labelledby to a button with no text', () => {
const { getByRole } = render(
<DefaultButton href="path_to_url" target="_blank" aria-describedby="someid" />,
);
const button = getByRole('link');
expect(button.getAttribute('aria-labelledby')).toBeNull();
expect(button.getAttribute('aria-describedby')).toEqual('someid');
});
it('applies aria-labelledby and aria-describedby', () => {
const { getByRole } = render(
<DefaultButton
href="path_to_url"
target="_blank"
ariaDescription="This description is not visible"
styles={{ screenReaderText: 'some-screenreader-class' }}
>
Hello
</DefaultButton>,
);
const button = getByRole('link');
expect(button.getAttribute('aria-label')).toBeNull();
expect(button.getAttribute('aria-labelledby')).toEqual(button.querySelector(`.ms-Button-label`)!.id);
expect(button.getAttribute('aria-describedby')).toEqual(button.querySelector('.some-screenreader-class')!.id);
});
it('applies aria-describedby to an IconButton', () => {
const { getByRole } = render(
<IconButton
iconProps={{ iconName: 'Emoji2' }}
ariaDescription="Description on icon button"
styles={{ screenReaderText: 'some-screenreader-class' }}
/>,
);
const button = getByRole('button');
expect(button.getAttribute('aria-label')).toBeNull();
expect(button.getAttribute('aria-labelledby')).toBeNull();
expect(button.getAttribute('aria-describedby')).toEqual(button.querySelector('.some-screenreader-class')!.id);
});
it('applies aria-labelledby and aria-describedby to a CompoundButton with ariaDescription', () => {
const { getByRole } = render(
<CompoundButton
secondaryText="Some awesome description"
ariaDescription="Description on icon button"
styles={{ screenReaderText: 'some-screenreader-class' }}
>
And this is the label
</CompoundButton>,
);
const button = getByRole('button');
expect(button.getAttribute('aria-label')).toBeNull();
expect(button.getAttribute('aria-labelledby')).toEqual(button.querySelector('.ms-Button-label')!.id);
expect(button.getAttribute('aria-describedby')).toEqual(button.querySelector('.some-screenreader-class')!.id);
});
it(
'applies aria-labelledby and aria-describedby to a CompoundButton with secondaryText ' +
'and no ariaDescription',
() => {
const { getByRole } = render(
<CompoundButton secondaryText="Some awesome description">And this is the label</CompoundButton>,
);
const button = getByRole('button');
expect(button.getAttribute('aria-label')).toBeNull();
expect(button.getAttribute('aria-labelledby')).toEqual(button.querySelector('.ms-Button-label')!.id);
expect(button.getAttribute('aria-describedby')).toEqual(button.querySelector('.ms-Button-description')!.id);
},
);
it('does not apply aria-pressed to an unchecked button', () => {
const { getByRole } = render(<DefaultButton toggle={true}>Hello</DefaultButton>);
expect(getByRole('button').getAttribute('aria-pressed')).toEqual('false');
});
it('applies aria-pressed to a checked button', () => {
const { getByRole } = render(
<DefaultButton toggle={true} checked={true}>
Hello
</DefaultButton>,
);
expect(getByRole('button').getAttribute('aria-pressed')).toEqual('true');
});
it('does not apply aria-pressed to an unchecked split button', () => {
const { getAllByRole } = render(
<DefaultButton
toggle={true}
split={true}
onClick={alertClicked}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
],
}}
>
Hello
</DefaultButton>,
);
expect(getAllByRole('button')[0].getAttribute('aria-pressed')).toEqual('false');
});
it('applies aria-checked to a role=menuitemcheckbox checked button', () => {
const { getByRole } = render(
<DefaultButton role="menuitemcheckbox" toggle={true} checked={true}>
Hello
</DefaultButton>,
);
expect(getByRole('menuitemcheckbox').getAttribute('aria-checked')).toEqual('true');
});
it('applies aria-checked to a role=checkbox checked button', () => {
const { getByRole } = render(
<DefaultButton role="checkbox" toggle={true} checked={true}>
Hello
</DefaultButton>,
);
expect(getByRole('checkbox').getAttribute('aria-checked')).toEqual('true');
});
it('applies aria-checked=false to a role=checkbox button even if toggle is not passed', () => {
const { getByRole } = render(<DefaultButton role="checkbox">Hello</DefaultButton>);
expect(getByRole('checkbox').getAttribute('aria-checked')).toEqual('false');
});
it('does not mutate menuprops hidden property', () => {
const menuProps: IContextualMenuProps = {
hidden: false,
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
],
};
const { getAllByRole } = render(
<DefaultButton toggle={true} split={true} onClick={alertClicked} persistMenu={true} menuProps={menuProps}>
Hello
</DefaultButton>,
);
expect(getAllByRole('button')[0]).toBeTruthy();
expect(menuProps.hidden).toEqual(false);
});
it('uses menuprops id in aria-controls when passed', () => {
const menuProps: IContextualMenuProps = {
id: 'custom-id',
items: [
{
key: 'menuItem',
text: 'Menu Item',
},
],
};
const { getByRole } = render(<DefaultButton menuProps={menuProps}>Hello</DefaultButton>);
const button = getByRole('button');
userEvent.click(button);
expect(button.getAttribute('aria-controls')).toBe('custom-id');
});
it('applies aria-pressed to a checked split button', () => {
const { getAllByRole } = render(
<DefaultButton
toggle={true}
checked={true}
split={true}
onClick={alertClicked}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
],
}}
>
Hello
</DefaultButton>,
);
expect(getAllByRole('button')[0].getAttribute('aria-pressed')).toEqual('true');
});
});
describe('with menuProps', () => {
it('contains aria-haspopup=true', () => {
const { getAllByRole } = render(
<DefaultButton menuProps={{ items: [{ key: 'item', text: 'Item' }] }}>Hello</DefaultButton>,
);
expect(getAllByRole('button')[0].getAttribute('aria-haspopup')).toEqual('true');
});
});
describe('without menuProps', () => {
it('does not contain aria-haspopup', () => {
const { getByRole } = render(<DefaultButton>Hello</DefaultButton>);
expect(getByRole('button').getAttribute('aria-haspopup')).toEqual(null);
});
});
describe('with menuIconProps', () => {
it('Contains the expected icon via menuIconProps', () => {
const { getAllByRole } = render(<DefaultButton menuIconProps={{ iconName: 'fontColor' }}>Hello</DefaultButton>);
expect(getAllByRole('button')[0].querySelectorAll('[data-icon-name="fontColor"]').length).toEqual(1);
});
});
it('Providing onClick and menuProps does not render a SplitButton', () => {
const { getAllByRole } = render(
<DefaultButton
text="Create account"
onClick={alertClicked}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
expect(getAllByRole('button')[0].tagName).not.toEqual('DIV');
});
it('Providing onKeyDown and menuProps still fires provided onKeyDown', () => {
const keyDownSpy = jest.fn();
render(
<DefaultButton
text="Create account"
onKeyDown={keyDownSpy}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
userEvent.tab();
userEvent.keyboard('{enter}');
expect(keyDownSpy).toHaveBeenCalled();
});
it('Providing onKeyDown, menuProps and splitButton=true fires provided onKeyDown on both buttons', () => {
const keyDownSpy = jest.fn();
render(
<DefaultButton
text="Create account"
onKeyDown={keyDownSpy}
split={true}
onClick={alertClicked}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
userEvent.tab();
userEvent.keyboard('{arrowdown}');
expect(keyDownSpy).toHaveBeenCalled();
});
it('Space keydown in a splitButton will fire onClick', () => {
const onClickSpy = jest.fn();
render(
<DefaultButton
data-automation-id="test"
text="Create account"
split={true}
onClick={onClickSpy}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
userEvent.tab();
userEvent.keyboard('{space}');
expect(onClickSpy).toHaveBeenCalled();
});
it('Providing onClick, menuProps and setting splitButton to true renders a SplitButton', () => {
const { getAllByRole } = render(
<DefaultButton
text="Create account"
split={true}
onClick={alertClicked}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
expect(getAllByRole('button')[0].tagName).toEqual('DIV');
});
it('Tapping menu button of SplitButton expands menu', () => {
const { getAllByRole } = render(
<DefaultButton
text="Create account"
split={true}
onClick={alertClicked}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
const menuButton = getAllByRole('button')[2];
userEvent.click(menuButton);
expect(getAllByRole('button')[0].getAttribute('aria-expanded')).toEqual('true');
});
it('Touch Start on primary button of SplitButton expands menu', () => {
const { getAllByRole } = render(
<DefaultButton
text="Create account"
split={true}
onClick={alertClicked}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
const primaryButton = getAllByRole('button')[1];
// in a normal scenario, when we do a touchstart we would also cause a
// click event to fire. This doesn't happen in the simulator so we're
// manually adding this in.
fireEvent.touchStart(primaryButton);
userEvent.click(primaryButton);
expect(getAllByRole('button')[0].getAttribute('aria-expanded')).toEqual('true');
});
it('Touch Start on primary button of toggle SplitButton fires click event', () => {
const clickSpy = jest.fn();
const { getAllByRole } = render(
<DefaultButton
text="Create account"
split={true}
toggle
checked={false}
onClick={clickSpy}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
const primaryButton = getAllByRole('button')[1];
// in a normal scenario, when we do a touchstart we would also cause a
// click event to fire. This doesn't happen in the simulator so we're
// manually adding this in.
fireEvent.touchStart(primaryButton);
userEvent.click(primaryButton);
expect(clickSpy).toHaveBeenCalled();
});
it('If menu trigger is disabled, pressing down does not trigger menu', () => {
const { getAllByRole } = render(
<DefaultButton
text="Create account"
menuTriggerKeyCode={null}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
userEvent.tab();
userEvent.keyboard('{arrowdown}');
expect(getAllByRole('button')[0].getAttribute('aria-expanded')).toEqual('false');
});
it('If menu trigger is specified, default key is overridden', () => {
const { getAllByRole } = render(
<DefaultButton
text="Create account"
menuTriggerKeyCode={KeyCodes.right}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
const button = getAllByRole('button')[0];
userEvent.tab();
userEvent.keyboard('{arrowdown}');
expect(button.getAttribute('aria-expanded')).toEqual('false');
userEvent.keyboard('{arrowright}');
expect(button.getAttribute('aria-expanded')).toEqual('true');
});
describe('Response to click event', () => {
let didClick = false;
const setTrue = (): void => {
didClick = true;
};
beforeEach(() => {
didClick = false;
});
function buildRenderButtonWithMenu(callbackMock?: jest.Mock<unknown>, persistMenu?: boolean): HTMLElement {
const { getAllByRole } = render(
<DefaultButton
text="Create account"
split={true}
onClick={setTrue}
onAfterMenuDismiss={callbackMock}
persistMenu={persistMenu}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
return getAllByRole('button')[0];
}
it('Clicking SplitButton button triggers action', () => {
const button: HTMLElement = buildRenderButtonWithMenu();
const menuButtonDOM: HTMLButtonElement = button.querySelectorAll('button')[0];
userEvent.click(menuButtonDOM);
expect(didClick).toEqual(true);
});
it('Pressing alt + down on SplitButton triggers menu', () => {
const button: HTMLElement = buildRenderButtonWithMenu();
userEvent.tab();
userEvent.keyboard('{alt}{arrowdown}');
expect(button.getAttribute('aria-expanded')).toEqual('true');
});
it('Click on button opens the menu, a second click closes the menu and calls onAfterMenuDismiss', () => {
const callbackMock = jest.fn();
const button: HTMLElement = buildRenderButtonWithMenu(callbackMock);
const menuButtonElement = button.querySelectorAll('button')[1];
userEvent.click(menuButtonElement);
expect(button.getAttribute('aria-expanded')).toEqual('true');
userEvent.click(menuButtonElement);
expect(button.getAttribute('aria-expanded')).toEqual('false');
expect(callbackMock.mock.calls.length).toBe(1);
});
it('[PersistedMenu] Opens on first click, closes on second click and calls onAfterMenuDismiss', () => {
const callbackMock = jest.fn();
const button: HTMLElement = buildRenderButtonWithMenu(callbackMock, true);
const menuButtonElement = button.querySelectorAll('button')[1];
userEvent.click(menuButtonElement);
expect(button.getAttribute('aria-expanded')).toEqual('true');
userEvent.click(menuButtonElement);
expect(button.getAttribute('aria-expanded')).toEqual('false');
expect(callbackMock.mock.calls.length).toBe(1);
});
it('A disabled SplitButton does not respond to input events', () => {
const { getAllByRole } = render(
<DefaultButton
disabled={true}
text="Create account"
split={true}
onClick={setTrue}
onKeyPress={setTrue}
onKeyUp={setTrue}
onKeyDown={setTrue}
onMouseDown={setTrue}
onMouseUp={setTrue}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
const button = getAllByRole('button')[0];
userEvent.click(button);
userEvent.keyboard('{alt}{arrowdown}');
expect(didClick).toEqual(false);
});
it('A disabled Button does not respond to input events', () => {
const { getAllByRole } = render(
<DefaultButton
disabled={true}
text="Create account"
split={false}
onClick={setTrue}
onKeyPress={setTrue}
onKeyUp={setTrue}
onKeyDown={setTrue}
onMouseDown={setTrue}
onMouseUp={setTrue}
/>,
);
const button = getAllByRole('button')[0];
userEvent.click(button);
userEvent.keyboard('{alt}{arrowdown}');
expect(didClick).toEqual(false);
});
it('A focusable disabled button does not respond to input events', () => {
const { getAllByRole } = render(
<DefaultButton
disabled={true}
allowDisabledFocus={true}
text="Create account"
split={false}
onClick={setTrue}
onKeyPress={setTrue}
onKeyUp={setTrue}
onKeyDown={setTrue}
onMouseDown={setTrue}
onMouseUp={setTrue}
/>,
);
const button = getAllByRole('button')[0];
userEvent.click(button);
userEvent.keyboard('{alt}{arrowdown}');
expect(didClick).toEqual(false);
});
it('A focusable disabled menu button does not respond to input events', () => {
const { getAllByRole } = render(
<DefaultButton
disabled={true}
allowDisabledFocus={true}
text="Create account"
split={false}
onClick={setTrue}
onKeyPress={setTrue}
onKeyUp={setTrue}
onKeyDown={setTrue}
onMouseDown={setTrue}
onMouseUp={setTrue}
menuProps={{
items: [
{
key: 'emailMessage',
text: 'Email message',
iconProps: { iconName: 'Mail' },
},
{
key: 'calendarEvent',
text: 'Calendar event',
iconProps: { iconName: 'Calendar' },
},
],
}}
/>,
);
const button = getAllByRole('button')[0];
userEvent.click(button);
userEvent.keyboard('{alt}{arrowdown}');
expect(didClick).toEqual(false);
});
});
describe('with contextual menu', () => {
function buildRenderAndClickButtonAndReturnContextualMenuDOMElement(
menuPropsPatch?: any,
text?: string,
textAsChildElement: boolean = false,
): HTMLElement {
const menuProps = { items: [{ key: 'item', name: 'Item' }], ...menuPropsPatch };
const element: React.ReactElement<any> = (
<DefaultButton
iconProps={{ iconName: 'Add' }}
text={!textAsChildElement && text ? text : undefined}
menuProps={menuProps}
>
{textAsChildElement && text ? text : null}
</DefaultButton>
);
const { getAllByRole } = render(element);
const button = getAllByRole('button')[0];
userEvent.click(button);
// get the menu id from the button's aria attribute
const menuId = button.getAttribute('aria-controls');
expect(menuId).toBeTruthy();
const menuDOM = button.ownerDocument!.getElementById(menuId as string);
expect(menuDOM).toBeTruthy();
return menuDOM as HTMLElement;
}
it('If button has text, contextual menu has aria-labelledBy attribute set', () => {
const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement(null, 'Button Text');
expect(contextualMenuElement).not.toBeNull();
expect(contextualMenuElement?.getAttribute('aria-label')).toBeNull();
expect(contextualMenuElement?.getAttribute('aria-labelledBy')).toBeTruthy();
});
it('If button has a text child, contextual menu has aria-labelledBy attribute set', () => {
const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement(
null,
'Button Text',
true,
);
expect(contextualMenuElement).not.toBeNull();
expect(contextualMenuElement?.getAttribute('aria-label')).toBeNull();
expect(contextualMenuElement?.getAttribute('aria-labelledBy')).not.toBeNull();
});
it('If button has no text, contextual menu has no aria-label or aria-labelledBy attributes', () => {
const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement();
expect(contextualMenuElement).not.toBeNull();
expect(contextualMenuElement?.getAttribute('aria-label')).toBeNull();
expect(contextualMenuElement?.getAttribute('aria-labelledBy')).toBeNull();
});
it('If button has text but ariaLabel provided in menuProps, contextual menu has aria-label set', () => {
const explicitLabel = 'ExplicitLabel';
const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement(
{ ariaLabel: explicitLabel },
'Button Text',
);
expect(contextualMenuElement).not.toBeNull();
expect(contextualMenuElement?.getAttribute('aria-label')).toEqual(explicitLabel);
expect(contextualMenuElement?.getAttribute('aria-labelledBy')).toBeNull();
});
it('Click on button opens the menu, escape press dismisses menu', () => {
const callbackMock = jest.fn();
const menuProps = { items: [{ key: 'item', name: 'Item' }], onDismiss: callbackMock };
const { getAllByRole } = render(
<DefaultButton iconProps={{ iconName: 'Add' }} menuProps={menuProps}>
{'Button Text'}
</DefaultButton>,
);
const button = getAllByRole('button')[0];
userEvent.click(button);
// get the menu id from the button's aria attribute
const menuId = button.getAttribute('aria-controls');
expect(menuId).toBeTruthy();
const contextualMenuElement = button.ownerDocument!.getElementById(menuId as string);
expect(contextualMenuElement).not.toBeNull();
userEvent.tab();
userEvent.keyboard('{esc}');
expect(callbackMock.mock.calls.length).toBe(1);
// Expect that the menu doesn't exist any more since it's been dismissed
const dismissed = button.ownerDocument!.getElementById(menuId as string);
expect(dismissed).toBeNull();
});
it(`If button has text but labelElementId provided in menuProps, contextual menu has
aria-labelledBy reflecting labelElementId`, () => {
const explicitLabelElementId = 'id_ExplicitLabel';
const contextualMenuElement = buildRenderAndClickButtonAndReturnContextualMenuDOMElement(
{ labelElementId: explicitLabelElementId },
'Button Text',
);
expect(contextualMenuElement).not.toBeNull();
expect(contextualMenuElement?.getAttribute('aria-label')).toBeNull();
expect(contextualMenuElement?.getAttribute('aria-labelledBy')).toEqual(explicitLabelElementId);
});
});
});
});
``` | /content/code_sandbox/packages/react/src/components/Button/Button.test.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 6,750 |
```xml
import { ThemeProvider } from '@fluentui/react/lib/Theme';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { MessageBar, MessageBarType } from 'office-ui-fabric-react';
import * as React from 'react';
export interface IShowErrorProps {
message: string;
themeVariant: IReadonlyTheme;
}
function ShowError(props: IShowErrorProps) {
return (
<ThemeProvider theme={props.themeVariant}>
<MessageBar messageBarType={MessageBarType.error}>
{props.message}
</MessageBar>
</ThemeProvider>
);
}
export default ShowError;
``` | /content/code_sandbox/samples/react-htm-templating/src/webparts/reactHtm/components/showError.tsx | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 136 |
```xml
<manifest xmlns:android="path_to_url"
package="com.shopreactnative"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="22" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>
``` | /content/code_sandbox/android/app/src/main/AndroidManifest.xml | xml | 2016-08-13T08:29:58 | 2024-07-27T02:37:28 | Shop-React-Native | EleTeam/Shop-React-Native | 1,057 | 235 |
```xml
export const openNew = (url: string) => {
window.open(url, '_blank')
}
export const isBrowser = () => {
try {
const userAgentString = navigator.userAgent
return (
userAgentString.indexOf('Chrome') > -1 ||
userAgentString.indexOf('MSIE') > -1 ||
userAgentString.indexOf('rv:') > -1 ||
userAgentString.indexOf('Firefox') > -1 ||
userAgentString.indexOf('Safari') > -1 ||
userAgentString.indexOf('OP') > -1
)
} catch (error) {
return false
}
}
export type OsNameOptions = 'windows' | 'macos' | 'unix' | 'linux' | 'unknown'
export const getOsName = (): OsNameOptions => {
try {
if (navigator.appVersion.indexOf('Win') != -1) return 'windows'
if (navigator.appVersion.indexOf('Mac') != -1) return 'macos'
if (navigator.appVersion.indexOf('X11') != -1) return 'unix'
if (navigator.appVersion.indexOf('Linux') != -1) return 'linux'
return 'unknown'
} catch (error) {
return 'unknown'
}
}
export const osFromAgentString = (agent: string): OsNameOptions => {
if (agent.indexOf('Win') != -1) return 'windows'
if (agent.indexOf('Mac') != -1) return 'macos'
if (agent.indexOf('X11') != -1) return 'unix'
if (agent.indexOf('Linux') != -1) return 'linux'
return 'unknown'
}
export const osName = getOsName()
``` | /content/code_sandbox/src/cloud/lib/utils/platform.ts | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 361 |
```xml
import * as express from 'express';
import * as strongErrorHandler from 'strong-error-handler';
import {json} from 'body-parser';
import {sequelize} from './database/sequelize';
import {userRouterFactory} from './users/userRouterFactory';
import {postRouterFactory} from './posts/postRouterFactory';
import {User} from './users/User';
import {Post} from './posts/Post';
const userRepository = sequelize.getRepository(User);
const postRepository = sequelize.getRepository(Post);
export const app = express();
app.use(json());
app.use(userRouterFactory(userRepository, postRepository));
app.use(postRouterFactory(postRepository));
app.use(strongErrorHandler({
debug: true,
}));
``` | /content/code_sandbox/examples/repository-mode/lib/app.ts | xml | 2016-01-27T11:25:52 | 2024-08-13T16:56:45 | sequelize-typescript | sequelize/sequelize-typescript | 2,768 | 142 |
```xml
import elapsed from './elapsed';
/**
* Starts a timer and return a function that when called returns a string
* with the ellapsed time formatted.
*/
export default (start: number = Date.now()) => {
return (): string => elapsed(Date.now() - start);
};
``` | /content/code_sandbox/packages/cli/src/util/output/stamp.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 57 |
```xml
import React from 'react';
type IconProps = React.SVGProps<SVGSVGElement>;
export declare const IcBrandMastercard: (props: IconProps) => React.JSX.Element;
export {};
``` | /content/code_sandbox/packages/icons/lib/icBrandMastercard.d.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 44 |
```xml
import { assert } from 'chai';
import * as sinon from 'sinon';
import * as typemoq from 'typemoq';
import {
VENV_CREATED_MARKER,
VenvProgressAndTelemetry,
} from '../../../../client/pythonEnvironments/creation/provider/venvProgressAndTelemetry';
import { CreateEnvironmentProgress } from '../../../../client/pythonEnvironments/creation/types';
import * as telemetry from '../../../../client/telemetry';
import { CreateEnv } from '../../../../client/common/utils/localize';
suite('Venv Progress and Telemetry', () => {
let sendTelemetryEventStub: sinon.SinonStub;
let progressReporterMock: typemoq.IMock<CreateEnvironmentProgress>;
setup(() => {
sendTelemetryEventStub = sinon.stub(telemetry, 'sendTelemetryEvent');
progressReporterMock = typemoq.Mock.ofType<CreateEnvironmentProgress>();
});
teardown(() => {
sinon.restore();
});
test('Ensure telemetry event and progress are sent', async () => {
const progressReporter = progressReporterMock.object;
progressReporterMock
.setup((p) => p.report({ message: CreateEnv.Venv.created }))
.returns(() => undefined)
.verifiable(typemoq.Times.once());
const progressAndTelemetry = new VenvProgressAndTelemetry(progressReporter);
progressAndTelemetry.process(VENV_CREATED_MARKER);
assert.isTrue(sendTelemetryEventStub.calledOnce);
progressReporterMock.verifyAll();
});
test('Do not trigger telemetry event the second time', async () => {
const progressReporter = progressReporterMock.object;
progressReporterMock
.setup((p) => p.report({ message: CreateEnv.Venv.created }))
.returns(() => undefined)
.verifiable(typemoq.Times.once());
const progressAndTelemetry = new VenvProgressAndTelemetry(progressReporter);
progressAndTelemetry.process(VENV_CREATED_MARKER);
progressAndTelemetry.process(VENV_CREATED_MARKER);
assert.isTrue(sendTelemetryEventStub.calledOnce);
progressReporterMock.verifyAll();
});
});
``` | /content/code_sandbox/src/test/pythonEnvironments/creation/provider/venvProgressAndTelemetry.unit.test.ts | xml | 2016-01-19T10:50:01 | 2024-08-12T21:05:24 | pythonVSCode | DonJayamanne/pythonVSCode | 2,078 | 439 |
```xml
export interface TagsFeedResponse {
sections: TagsFeedResponseSectionsItem[];
more_available: boolean;
next_page: number;
next_media_ids: string[];
next_max_id: string;
status: string;
}
export interface TagsFeedResponseSectionsItem {
layout_type: string;
layout_content: TagsFeedResponseLayout_content;
feed_type: string;
explore_item_info: TagsFeedResponseExplore_item_info;
}
export interface TagsFeedResponseLayout_content {
medias: TagsFeedResponseMediasItem[];
}
export interface TagsFeedResponseMediasItem {
media: TagsFeedResponseMedia;
}
export interface TagsFeedResponseMedia {
taken_at: number;
pk: string;
id: string;
device_timestamp: string | number;
media_type: number;
code: string;
client_cache_key: string;
filter_type: number;
comment_likes_enabled: boolean;
comment_threading_enabled: boolean;
has_more_comments: boolean;
next_max_id: string;
max_num_visible_preview_comments: number;
preview_comments: TagsFeedResponsePreviewCommentsItem[];
can_view_more_preview_comments: boolean;
comment_count: number;
carousel_media_count?: number;
carousel_media?: TagsFeedResponseCarouselMediaItem[];
can_see_insights_as_brand?: boolean;
Tags: TagsFeedResponseTags;
lat: string;
lng: string;
user: TagsFeedResponseUser;
can_viewer_reshare: boolean;
caption: TagsFeedResponseCaption | null;
caption_is_edited: boolean;
like_count: number;
has_liked: boolean;
top_likers: any[];
photo_of_you: boolean;
can_viewer_save: boolean;
organic_tracking_token: string;
image_versions2?: TagsFeedResponseImage_versions2;
original_width?: number;
original_height?: number;
usertags?: TagsFeedResponseUsertags;
is_dash_eligible?: number;
video_dash_manifest?: string;
video_codec?: string;
number_of_qualities?: number;
video_versions?: TagsFeedResponseVideoVersionsItem[];
has_audio?: boolean;
video_duration?: number;
view_count?: number;
commenting_disabled_for_viewer?: boolean;
}
export interface TagsFeedResponsePreviewCommentsItem {
pk: string;
user_id: number;
text: string;
type: number;
created_at: number;
created_at_utc: number;
content_type: string;
status: string;
bit_flags: number;
user: TagsFeedResponseUser;
did_report_as_spam: boolean;
share_enabled: boolean;
media_id: string;
has_translation?: boolean;
parent_comment_id?: string;
}
export interface TagsFeedResponseUser {
pk: number;
username: string;
full_name: string;
is_private: boolean;
profile_pic_url: string;
profile_pic_id?: string;
is_verified?: boolean;
friendship_status?: TagsFeedResponseFriendship_status;
has_anonymous_profile_picture?: boolean;
is_unpublished?: boolean;
is_favorite?: boolean;
}
export interface TagsFeedResponseCarouselMediaItem {
id: string;
media_type: number;
image_versions2: TagsFeedResponseImage_versions2;
original_width: number;
original_height: number;
pk: string;
carousel_parent_id: string;
usertags?: TagsFeedResponseUsertags;
video_versions?: TagsFeedResponseVideoVersionsItem[];
video_duration?: number;
is_dash_eligible?: number;
video_dash_manifest?: string;
video_codec?: string;
number_of_qualities?: number;
}
export interface TagsFeedResponseImage_versions2 {
candidates: TagsFeedResponseCandidatesItem[];
}
export interface TagsFeedResponseCandidatesItem {
width: number;
height: number;
url: string;
}
export interface TagsFeedResponseTags {
pk: number;
name: string;
address: string;
city: string;
short_name: string;
lng: string;
lat: string;
external_source: string;
facebook_places_id: string;
}
export interface TagsFeedResponseFriendship_status {
following: boolean;
outgoing_request: boolean;
is_bestie: boolean;
}
export interface TagsFeedResponseCaption {
pk: string;
user_id: number;
text: string;
type: number;
created_at: number;
created_at_utc: number;
content_type: string;
status: string;
bit_flags: number;
user: TagsFeedResponseUser;
did_report_as_spam: boolean;
share_enabled: boolean;
media_id: string;
has_translation?: boolean;
}
export interface TagsFeedResponseUsertags {
in: TagsFeedResponseInItem[];
}
export interface TagsFeedResponseInItem {
user: TagsFeedResponseUser;
position: number[] | (number | string)[];
start_time_in_video_in_sec: null;
duration_in_video_in_sec: null;
}
export interface TagsFeedResponseExplore_item_info {
num_columns: number;
total_num_columns: number;
aspect_ratio: number;
autoplay: boolean;
}
export interface TagsFeedResponseVideoVersionsItem {
type: number;
width: number;
height: number;
url: string;
id: string;
}
``` | /content/code_sandbox/src/responses/tags.feed.response.ts | xml | 2016-06-09T12:14:48 | 2024-08-16T10:07:22 | instagram-private-api | dilame/instagram-private-api | 5,877 | 1,136 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<NoWarn>$(NoWarn);1591;1574</NoWarn>
<AssemblyName>Peachpie.Library.Scripting</AssemblyName>
<PackageId>Peachpie.Library.Scripting</PackageId>
<PackageTags>peachpie;library;scripting</PackageTags>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Description>Support for dynamic code evaluation in Peachpie application. The package enables `eval` and `create_function` in compiled programs.</Description>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Peachpie.Microsoft.CodeAnalysis" Version="$(PeachpieMicrosoftCodeAnalysisVersion)" />
<!--
System.Runtime.Loader.AssemblyLoadContext cannot be loaded from System.Runtime.Loader 4.0.0 which is hard referenced on full .NET Framework,
you may remove this workaround once it will work using netstandard2.0 well.
-->
<PackageReference Include="System.Runtime.Loader" Version="4.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Peachpie.CodeAnalysis\Peachpie.CodeAnalysis.csproj" />
<ProjectReference Include="..\Peachpie.Library\Peachpie.Library.csproj" />
<ProjectReference Include="..\Peachpie.Runtime\Peachpie.Runtime.csproj" />
<ProjectReference Include="..\Peachpie.Library.XmlDom\Peachpie.Library.XmlDom.csproj" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/src/Peachpie.Library.Scripting/Peachpie.Library.Scripting.csproj | xml | 2016-02-05T16:22:55 | 2024-08-16T17:42:35 | peachpie | peachpiecompiler/peachpie | 2,317 | 325 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Do not translate those arrays which named "xxx_values". -->
<!-- Do not translate those items with a value of "@string/xxx". -->
<!-- Chinese source. -->
<string-array name="weather_sources">
<item>caiyunapp.com (Exclusiv pentru China)</item>
<item>accuweather.com</item>
<item>OpenWeather</item>
<item>Mto France</item>
</string-array>
<!-- Location service. -->
<string-array name="location_services">
<item>Locaie Baidu</item>
<item>Locaie Baidu IP (Exclusiv pentru China)</item>
<item>Locaie AMap</item>
<item>API Nativ</item>
</string-array>
<!-- Dark mode. -->
<string-array name="dark_modes">
<item>Automat</item>
<item>La fel ca tema sistemului</item>
<item>ntunecat</item>
<item>Luminos</item>
</string-array>
<!-- UI style. -->
<string-array name="ui_styles">
<item>Cer static</item>
<item>Cer animat</item>
</string-array>
<!-- automatic refresh rate. -->
<string-array name="automatic_refresh_rates">
<item> 30 minute</item>
<item>1 or</item>
<item>1.5 ore</item>
<item>2 ore</item>
<item>2.5 ore</item>
<item>3 ore</item>
<item>3.5 ore</item>
<item>4 ore</item>
<item>4.5 ore</item>
<item>5 ore</item>
<item>5.5 ore</item>
<item>6 ore</item>
</string-array>
<!-- widget week icon mode. -->
<string-array name="week_icon_modes">
<item>Automat</item>
<item>@string/daytime</item><!-- do not translate. -->
<item>@string/nighttime</item><!-- do not translate. -->
</string-array>
<!-- notification style. -->
<string-array name="notification_styles">
<item>sistem</item>
<item>Orae</item>
<item>@string/daily_overview</item><!-- do not translate. -->
<item>@string/hourly_overview</item><!-- do not translate. -->
</string-array>
<!-- notification text color. -->
<string-array name="notification_text_colors">
<item>nchis la culoare</item>
<item>Gri</item>
<item>Deschis la culoare</item>
</string-array>
<!-- widget style. -->
<string-array name="widget_styles">
<item>Dreptunghi</item>
<item>Simetric</item>
<item>Compact</item>
<item>Mini</item>
<item>Nano</item>
<item>Pixel</item>
<item>Vertical</item>
<item>Oreo</item>
<item>Oreo (Google sans)</item>
<item>Temperatur</item>
</string-array>
<!-- week widget style. -->
<string-array name="week_widget_styles">
<item>5 zile</item>
<item>3 zile</item>
</string-array>
<!-- Widget subtitle data. -->
<string-array name="subtitle_data">
<item>Or actualizare</item>
<item>Calitatea aerului (Invalid n unele zone.)</item>
<item>Vnt</item>
<item>Temp. resimit</item>
<item>Calendar Lunar</item>
<item>Personalizat</item>
</string-array>
<!-- widget clock font. -->
<string-array name="clock_font">
<item>sans-serif-light</item>
<item>sans-serif</item>
<item>sans-serif-black</item>
<item>analog</item>
</string-array>
<!-- widget card style. -->
<string-array name="widget_card_styles">
<item>Nici unul</item>
<item>Mod zi - noapte</item>
<item>Luminos</item>
<item>ntunecat</item>
</string-array>
<!-- widget clock font. -->
<string-array name="widget_text_colors">
<item>Deschis la culoare</item>
<item>nchis la culoare</item>
<item>Automat</item>
</string-array>
<!-- live wallpaper weather kind. -->
<string-array name="live_wallpaper_weather_kinds">
<item>Automat</item>
<item>Senin</item>
<item>Parial noros</item>
<item>Noros</item>
<item>Ploaie</item>
<item>Ninsoare</item>
<item>Lapovi</item>
<item>Grindin</item>
<item>Cea</item>
<item>Vizibilitate redus</item>
<item>Trsnet</item>
<item>Furtun</item>
<item>Vnt</item>
</string-array>
<!-- live wallpaper weather kind. -->
<string-array name="live_wallpaper_day_night_types">
<item>Automat</item>
<item>Zi</item>
<item>Noapte</item>
</string-array>
<!-- speed unit. -->
<string-array name="speed_units">
<item>km/h</item>
<item>m/s</item>
<item>kn</item>
<item>mph</item>
<item>ft/s</item>
</string-array>
<!-- precipitation unit. -->
<string-array name="precipitation_units">
<item>mm</item>
<item>cm</item>
<item>inch</item>
<item>L/m</item>
</string-array>
<!-- temperature unit. -->
<string-array name="temperature_units">
<item></item>
<item></item>
<item>K</item>
</string-array>
<string-array name="temperature_units_short">
<item></item>
<item></item>
<item>K</item>
</string-array>
<string-array name="temperature_units_long">
<item>C</item>
<item>F</item>
<item>K</item>
</string-array>
<!-- distance unit. -->
<string-array name="distance_units">
<item>km</item>
<item>m</item>
<item>mi</item>
<item>nmi</item>
<item>ft</item>
</string-array>
<!-- pressure unit. -->
<string-array name="pressure_units">
<item>mb</item>
<item>kPa</item>
<item>hPa</item>
<item>atm</item>
<item>mmHg</item>
<item>inHg</item>
<item>kgf/cm</item>
</string-array>
<!-- air quality unit. -->
<string-array name="air_quality_units">
<item>g/m</item>
</string-array>
<!-- air quality co unit. -->
<string-array name="air_quality_co_units">
<item>mg/m</item>
</string-array>
<!-- duration unit. -->
<string-array name="duration_units">
<item>h</item> <!-- hour -->
</string-array>
<!-- pollen unit. -->
<string-array name="pollen_units">
<item>/m</item>
</string-array>
</resources>
``` | /content/code_sandbox/app/src/main/res/values-ro/arrays.xml | xml | 2016-02-21T04:39:19 | 2024-08-16T13:35:51 | GeometricWeather | WangDaYeeeeee/GeometricWeather | 2,420 | 1,738 |
```xml
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<response>
<result code="1000">
<msg>Command completed successfully</msg>
</result>
<resData>
<domain:infData
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>example.tld</domain:name>
<domain:roid>%ROID%</domain:roid>
<domain:status s="ok"/>
<domain:registrant>jd1234</domain:registrant>
<domain:contact type="admin">sh8013</domain:contact>
<domain:contact type="tech">sh8013</domain:contact>
<domain:clID>NewRegistrar</domain:clID>
<domain:crID>TheRegistrar</domain:crID>
<domain:crDate>1999-04-03T22:00:00.0Z</domain:crDate>
<domain:upID>NewRegistrar</domain:upID>
<domain:upDate>1999-12-03T09:00:00.0Z</domain:upDate>
<domain:exDate>2005-04-03T22:00:00.0Z</domain:exDate>
<domain:trDate>2000-04-08T09:00:00.0Z</domain:trDate>
<domain:authInfo>
<domain:pw>2fooBAR</domain:pw>
</domain:authInfo>
</domain:infData>
</resData>
<trID>
<clTRID>ABC-12345</clTRID>
<svTRID>server-trid</svTRID>
</trID>
</response>
</epp>
``` | /content/code_sandbox/core/src/test/resources/google/registry/flows/domain/domain_info_response_none_hosts.xml | xml | 2016-02-29T20:16:48 | 2024-08-15T19:49:29 | nomulus | google/nomulus | 1,685 | 403 |
```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 FLOAT16_NINF = require( './index' );
// TESTS //
// The export is a number...
{
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
FLOAT16_NINF; // $ExpectType number
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/constants/float16/ninf/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 101 |
```xml
/**
* Module providing "strands," serialized execution in an asychronous world.
*/ /** */
/**
* Provides serial execution for asynchronous code. Here are the semantics:
*
* `Strand` holds an internal execution queue of completion callbacks. Each
* call to `execute` will push to the queue. When a callback in the queue
* finishes with either an exception or a regular return, the next callback in
* the queue will be dispatched. Callbacks are not executed until all prior
* callbacks have run to completion.
*/
export class Strand {
private _tailPromise: Thenable<void> = Promise.resolve();
private _enqueue(fn: () => Promise<void>) {
this._tailPromise = this._tailPromise.then(
fn,
fn
);
}
/**
* Enqueue a function for execution.
*
* Callbacks passed to `execute()` are always executed in order, and never
* started until the prior callbacks have executed.
*
* @param func The next completion callback
* @returns a Thenable that will resolve with the return value/exception of
* the enqueued function.
*/
execute<T>(func: () => Thenable<T>): Thenable<T>;
execute<T>(func: () => Promise<T>): Thenable<T>;
execute<T>(func: () => T): Thenable<T>;
execute<Ret>(func: () => Ret): Thenable<Ret> {
return new Promise<Ret>((resolve, reject) => {
this._enqueue(async () => {
try {
const result = await Promise.resolve(func());
resolve(result);
} catch (e) {
reject(e);
}
});
});
}
}
``` | /content/code_sandbox/src/strand.ts | xml | 2016-04-16T21:00:29 | 2024-08-16T16:41:57 | vscode-cmake-tools | microsoft/vscode-cmake-tools | 1,450 | 363 |
```xml
/*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BaseEntity } from '../entity/BaseEntity';
import { BaseService } from './base.service';
@Injectable({
providedIn: 'root'
})
export class SessionsService extends BaseService<BaseEntity> {
constructor(private _httpClient: HttpClient) {
super(_httpClient, '/access/session');
this.server.urls.delete = '/terminate';
}
}
``` | /content/code_sandbox/maxkey-web-frontend/maxkey-web-app/src/app/service/sessions.service.ts | xml | 2016-11-16T03:06:50 | 2024-08-16T09:22:42 | MaxKey | dromara/MaxKey | 1,423 | 127 |
```xml
import type { Reducer } from 'redux';
import type { WithOptimisticReducer } from '../types';
import { combineOptimisticReducers } from './combine-optimistic-reducers';
describe('combineOptimisticReducers', () => {
test('should keep a reference to the underlying "reducer state structure"', () => {
const reducer: Reducer = () => {};
const optimisticReducer: WithOptimisticReducer = () => {};
optimisticReducer.innerReducer = () => {};
const nestedOptimisticCombinedReducer = combineOptimisticReducers({
nestedOptimisticTest: optimisticReducer,
nestedTest: reducer,
});
const reducersMap = {
nestedOptimisticCombinedReducer,
optimisticTest: optimisticReducer,
test: reducer,
};
const rootReducer = combineOptimisticReducers(reducersMap);
expect(rootReducer.innerCombinedReducers).toEqual(reducersMap);
});
});
``` | /content/code_sandbox/packages/pass/store/optimistic/utils/combine-optimistic-reducers.spec.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 194 |
```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.
*/
/**
* @fileoverview Items for TeX parsing of bussproofs.
*
* @author v.sorge@mathjax.org (Volker Sorge)
*/
import TexError from '../TexError.js';
import {BaseItem, CheckType, StackItem} from '../StackItem.js';
import {MmlNode} from '../../../core/MmlTree/MmlNode.js';
import Stack from '../Stack.js';
import * as BussproofsUtil from './BussproofsUtil.js';
export class ProofTreeItem extends BaseItem {
/**
* The current left label.
* @type {MmlNode[]}
*/
public leftLabel: MmlNode[] = null;
/**
* The current right label.
* @type {MmlNode[]}
*/
public rigthLabel: MmlNode[] = null;
private innerStack: Stack = new Stack(this.factory, {}, true);
/**
* @override
*/
public get kind() {
return 'proofTree';
}
/**
* @override
*/
public checkItem(item: StackItem): CheckType {
if (item.isKind('end') && item.getName() === 'prooftree') {
let node = this.toMml();
BussproofsUtil.setProperty(node, 'proof', true);
return [[this.factory.create('mml', node), item], true];
}
if (item.isKind('stop')) {
throw new TexError('EnvMissingEnd', 'Missing \\end{%1}', this.getName());
}
this.innerStack.Push(item);
return BaseItem.fail;
}
/**
* @override
*/
public toMml() {
const tree = super.toMml();
const start = this.innerStack.Top();
if (start.isKind('start') && !start.Size()) {
return tree;
}
this.innerStack.Push(this.factory.create('stop'));
let prefix = this.innerStack.Top().toMml();
return this.create('node', 'mrow', [prefix, tree], {});
}
}
``` | /content/code_sandbox/ts/input/tex/bussproofs/BussproofsItems.ts | xml | 2016-02-23T09:52:03 | 2024-08-16T04:46:50 | MathJax-src | mathjax/MathJax-src | 2,017 | 488 |
```xml
export const enum eCmsKitRouteNames {
CmsKit = 'CmsKit',
}
``` | /content/code_sandbox/modules/cms-kit/angular/projects/cms-kit/config/src/enums/route-names.ts | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 22 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<xs:schema version="1.0.0"
attributeFormDefault="unqualified"
elementFormDefault="qualified"
targetNamespace="path_to_url"
xmlns:self="path_to_url"
xmlns:xs="path_to_url">
<xs:annotation>
<xs:documentation>
<!-- _locID_text="VsixSchema" _locComment="" -->This schema is used for installing extensions to Visual Studio.
</xs:documentation>
</xs:annotation>
<xs:include schemaLocation="PackageManifestSchema.Metadata.xsd" />
<xs:include schemaLocation="PackageManifestSchema.Installation.xsd" />
<xs:include schemaLocation="PackageManifestSchema.Dependencies.xsd" />
<xs:include schemaLocation="PackageManifestSchema.Assets.xsd" />
<xs:element name="PackageLanguagePackManifest">
<xs:complexType>
<xs:sequence>
<xs:element name="Metadata" type="self:MetadataInfo" minOccurs="1" maxOccurs="1" />
<xs:element name="Installation" type="self:Installation" minOccurs="0" maxOccurs="1" />
<xs:element name="Dependencies" minOccurs="0" maxOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="Dependency" type="self:DependencyInfo" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Assets" type="self:Assets" minOccurs="0" maxOccurs="1" />
<xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="Version" type="xs:string" use="required">
<xs:annotation>
<xs:documentation>
<!-- _locID_text="Vsix.Version" _locComment="" -->The Version attribute is the version of the VSIX file. For VS 2010, use 1.0.0
</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>
``` | /content/code_sandbox/packages/Microsoft.VSSDK.BuildTools.14.3.25407/tools/vssdk/schemas/PackageLanguagePackManifestSchema.xsd | xml | 2016-04-24T09:50:47 | 2024-08-16T11:45:14 | ILRuntime | Ourpalm/ILRuntime | 2,976 | 500 |
```xml
import { existsSync } from 'node:fs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { JsPackageManager, PackageJsonWithMaybeDeps } from '@storybook/core/common';
import { logger } from '@storybook/core/node-logger';
import { detect, detectFrameworkPreset, detectLanguage } from './detect';
import { ProjectType, SupportedLanguage } from './project_types';
vi.mock('./helpers', () => ({
isNxProject: vi.fn(),
}));
vi.mock('fs', () => ({
existsSync: vi.fn(),
stat: vi.fn(),
lstat: vi.fn(),
access: vi.fn(),
realpathSync: vi.fn(),
lstatSync: vi.fn(),
readdir: vi.fn(),
readdirSync: vi.fn(),
readlinkSync: vi.fn(),
default: vi.fn(),
}));
vi.mock('fs-extra', () => ({
pathExistsSync: vi.fn(() => true),
}));
vi.mock('@storybook/core/node-logger');
const MOCK_FRAMEWORK_FILES: {
name: string;
files: Record<'package.json', PackageJsonWithMaybeDeps> | Record<string, string>;
}[] = [
{
name: ProjectType.VUE3,
files: {
'package.json': {
dependencies: {
vue: '^3.0.0',
},
},
},
},
{
name: ProjectType.VUE3,
files: {
'package.json': {
dependencies: {
// Testing the `next` tag too
vue: 'next',
},
},
},
},
{
name: ProjectType.EMBER,
files: {
'package.json': {
devDependencies: {
'ember-cli': '1.0.0',
},
},
},
},
{
name: ProjectType.REACT_PROJECT,
files: {
'package.json': {
peerDependencies: {
react: '1.0.0',
},
},
},
},
{
name: ProjectType.QWIK,
files: {
'package.json': {
devDependencies: {
'@builder.io/qwik': '1.0.0',
},
},
},
},
{
name: ProjectType.REACT_NATIVE,
files: {
'package.json': {
dependencies: {
'react-native': '1.0.0',
},
devDependencies: {
'react-native-scripts': '1.0.0',
},
},
},
},
{
name: ProjectType.REACT_SCRIPTS,
files: {
'package.json': {
devDependencies: {
'react-scripts': '1.0.0',
},
},
},
},
{
name: ProjectType.WEBPACK_REACT,
files: {
'package.json': {
dependencies: {
react: '1.0.0',
},
devDependencies: {
webpack: '1.0.0',
},
},
},
},
{
name: ProjectType.REACT,
files: {
'package.json': {
dependencies: {
react: '1.0.0',
},
},
},
},
{
name: ProjectType.NEXTJS,
files: {
'package.json': {
dependencies: {
next: '^9.0.0',
},
},
},
},
{
name: ProjectType.ANGULAR,
files: {
'package.json': {
dependencies: {
'@angular/core': '1.0.0',
},
},
},
},
{
name: ProjectType.WEB_COMPONENTS,
files: {
'package.json': {
dependencies: {
'lit-element': '1.0.0',
},
},
},
},
{
name: ProjectType.WEB_COMPONENTS,
files: {
'package.json': {
dependencies: {
'lit-html': '1.4.1',
},
},
},
},
{
name: ProjectType.WEB_COMPONENTS,
files: {
'package.json': {
dependencies: {
'lit-html': '2.0.0-rc.3',
},
},
},
},
{
name: ProjectType.WEB_COMPONENTS,
files: {
'package.json': {
dependencies: {
lit: '2.0.0-rc.2',
},
},
},
},
{
name: ProjectType.PREACT,
files: {
'package.json': {
dependencies: {
preact: '1.0.0',
},
},
},
},
{
name: ProjectType.SVELTE,
files: {
'package.json': {
dependencies: {
svelte: '1.0.0',
},
},
},
},
];
describe('Detect', () => {
it(`should return type HTML if html option is passed`, async () => {
const packageManager = {
retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: {} }),
getAllDependencies: () => Promise.resolve({}),
getPackageVersion: () => Promise.resolve(null),
} as Partial<JsPackageManager>;
await expect(detect(packageManager as any, { html: true })).resolves.toBe(ProjectType.HTML);
});
it(`should return language javascript if the TS dependency is present but less than minimum supported`, async () => {
vi.mocked(logger.warn).mockClear();
const packageManager = {
retrievePackageJson: () =>
Promise.resolve({
dependencies: {},
devDependencies: {
typescript: '1.0.0',
},
}),
getAllDependencies: () =>
Promise.resolve({
typescript: '1.0.0',
}),
getPackageVersion: (packageName) => {
switch (packageName) {
case 'typescript':
return Promise.resolve('1.0.0');
default:
return Promise.resolve(null);
}
},
} as Partial<JsPackageManager>;
await expect(detectLanguage(packageManager as any)).resolves.toBe(SupportedLanguage.JAVASCRIPT);
expect(logger.warn).toHaveBeenCalledWith(
'Detected TypeScript < 3.8, populating with JavaScript examples'
);
});
it(`should return language typescript-3-8 if the TS dependency is >=3.8 and <4.9`, async () => {
await expect(
detectLanguage({
retrievePackageJson: () =>
Promise.resolve({
dependencies: {},
devDependencies: {
typescript: '3.8.0',
},
}),
getAllDependencies: () =>
Promise.resolve({
typescript: '3.8.0',
}),
getPackageVersion: (packageName: string) => {
switch (packageName) {
case 'typescript':
return Promise.resolve('3.8.0');
default:
return Promise.resolve(null);
}
},
} as Partial<JsPackageManager> as JsPackageManager)
).resolves.toBe(SupportedLanguage.TYPESCRIPT_3_8);
await expect(
detectLanguage({
retrievePackageJson: () =>
Promise.resolve({
dependencies: {},
devDependencies: {
typescript: '4.8.0',
},
}),
getAllDependencies: () =>
Promise.resolve({
typescript: '4.8.0',
}),
getPackageVersion: (packageName: string) => {
switch (packageName) {
case 'typescript':
return Promise.resolve('4.8.0');
default:
return Promise.resolve(null);
}
},
} as Partial<JsPackageManager> as JsPackageManager)
).resolves.toBe(SupportedLanguage.TYPESCRIPT_3_8);
});
it(`should return language typescript-4-9 if the dependency is >TS4.9`, async () => {
await expect(
detectLanguage({
retrievePackageJson: () =>
Promise.resolve({
dependencies: {},
devDependencies: {
typescript: '4.9.1',
},
}),
getAllDependencies: () =>
Promise.resolve({
typescript: '4.9.1',
}),
getPackageVersion: (packageName: string) => {
switch (packageName) {
case 'typescript':
return Promise.resolve('4.9.1');
default:
return Promise.resolve(null);
}
},
} as Partial<JsPackageManager> as JsPackageManager)
).resolves.toBe(SupportedLanguage.TYPESCRIPT_4_9);
});
it(`should return language typescript if the dependency is =TS4.9`, async () => {
await expect(
detectLanguage({
retrievePackageJson: () =>
Promise.resolve({
dependencies: {},
devDependencies: {
typescript: '4.9.0',
},
}),
getAllDependencies: () =>
Promise.resolve({
typescript: '4.9.0',
}),
getPackageVersion: (packageName: string) => {
switch (packageName) {
case 'typescript':
return Promise.resolve('4.9.0');
default:
return Promise.resolve(null);
}
},
} as Partial<JsPackageManager> as JsPackageManager)
).resolves.toBe(SupportedLanguage.TYPESCRIPT_4_9);
});
it(`should return language typescript if the dependency is =TS4.9beta`, async () => {
await expect(
detectLanguage({
retrievePackageJson: () =>
Promise.resolve({
dependencies: {},
devDependencies: {
typescript: '4.9.0-beta',
},
}),
getAllDependencies: () =>
Promise.resolve({
typescript: '4.9.0-beta',
}),
getPackageVersion: (packageName: string) => {
switch (packageName) {
case 'typescript':
return Promise.resolve('4.9.0-beta');
default:
return Promise.resolve(null);
}
},
} as Partial<JsPackageManager> as JsPackageManager)
).resolves.toBe(SupportedLanguage.TYPESCRIPT_3_8);
});
it(`should return language javascript by default`, async () => {
await expect(
detectLanguage({
retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: {} }),
getAllDependencies: () => Promise.resolve({}),
getPackageVersion: () => {
return Promise.resolve(null);
},
} as Partial<JsPackageManager> as JsPackageManager)
).resolves.toBe(SupportedLanguage.JAVASCRIPT);
});
it(`should return language Javascript even when Typescript is detected in the node_modules but not listed as a direct dependency`, async () => {
await expect(
detectLanguage({
retrievePackageJson: () => Promise.resolve({ dependencies: {}, devDependencies: {} }),
getAllDependencies: () => Promise.resolve({}),
getPackageVersion: (packageName) => {
switch (packageName) {
case 'typescript':
return Promise.resolve('4.9.0');
default:
return Promise.resolve(null);
}
},
} as Partial<JsPackageManager> as JsPackageManager)
).resolves.toBe(SupportedLanguage.JAVASCRIPT);
});
describe('detectFrameworkPreset should return', () => {
afterEach(() => {
vi.clearAllMocks();
});
MOCK_FRAMEWORK_FILES.forEach((structure) => {
it(`${structure.name}`, () => {
vi.mocked(existsSync).mockImplementation((filePath) => {
return typeof filePath === 'string' && Object.keys(structure.files).includes(filePath);
});
const result = detectFrameworkPreset(
structure.files['package.json'] as PackageJsonWithMaybeDeps
);
expect(result).toBe(structure.name);
});
});
it(`UNDETECTED for unknown frameworks`, () => {
const result = detectFrameworkPreset();
expect(result).toBe(ProjectType.UNDETECTED);
});
// TODO(blaine): Remove once Nuxt3 is supported
it(`UNSUPPORTED for Nuxt framework above version 3.0.0`, () => {
const result = detectFrameworkPreset({
dependencies: {
nuxt: '3.0.0',
},
});
expect(result).toBe(ProjectType.UNSUPPORTED);
});
// TODO: The mocking in this test causes tests after it to fail
it('REACT_SCRIPTS for custom react scripts config', () => {
const forkedReactScriptsConfig = {
'/node_modules/.bin/react-scripts': 'file content',
};
vi.mocked(existsSync).mockImplementation((filePath) => {
return (
typeof filePath === 'string' && Object.keys(forkedReactScriptsConfig).includes(filePath)
);
});
const result = detectFrameworkPreset();
expect(result).toBe(ProjectType.REACT_SCRIPTS);
});
});
});
``` | /content/code_sandbox/code/core/src/cli/detect.test.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 2,766 |
```xml
import type {
NodePath,
types as BabelTypes,
} from 'next/dist/compiled/babel/core'
import type { PluginObj } from 'next/dist/compiled/babel/core'
import jsx from 'next/dist/compiled/babel/plugin-syntax-jsx'
export default function ({
types: t,
}: {
types: typeof BabelTypes
}): PluginObj<any> {
return {
inherits: jsx,
visitor: {
JSXElement(_path, state) {
state.set('jsx', true)
},
// Fragment syntax is still JSX since it compiles to createElement(),
// but JSXFragment is not a JSXElement
JSXFragment(_path, state) {
state.set('jsx', true)
},
Program: {
exit(path: NodePath<BabelTypes.Program>, state) {
if (state.get('jsx')) {
const pragma = t.identifier(state.opts.pragma)
let importAs = pragma
// if there's already a React in scope, use that instead of adding an import
const existingBinding =
state.opts.reuseImport !== false &&
state.opts.importAs &&
path.scope.getBinding(state.opts.importAs)
// var _jsx = _pragma.createElement;
if (state.opts.property) {
if (state.opts.importAs) {
importAs = t.identifier(state.opts.importAs)
} else {
importAs = path.scope.generateUidIdentifier('pragma')
}
const mapping = t.variableDeclaration('var', [
t.variableDeclarator(
pragma,
t.memberExpression(
importAs,
t.identifier(state.opts.property)
)
),
])
// if the React binding came from a require('react'),
// make sure that our usage comes after it.
let newPath: NodePath<BabelTypes.VariableDeclaration>
if (
existingBinding &&
t.isVariableDeclarator(existingBinding.path.node) &&
t.isCallExpression(existingBinding.path.node.init) &&
t.isIdentifier(existingBinding.path.node.init.callee) &&
existingBinding.path.node.init.callee.name === 'require'
) {
;[newPath] =
existingBinding.path.parentPath.insertAfter(mapping)
} else {
;[newPath] = path.unshiftContainer('body', mapping)
}
for (const declar of newPath.get('declarations')) {
path.scope.registerBinding(
newPath.node.kind,
declar as NodePath<BabelTypes.Node>
)
}
}
if (!existingBinding) {
const importSpecifier = t.importDeclaration(
[
state.opts.import
? // import { $import as _pragma } from '$module'
t.importSpecifier(
importAs,
t.identifier(state.opts.import)
)
: state.opts.importNamespace
? t.importNamespaceSpecifier(importAs)
: // import _pragma from '$module'
t.importDefaultSpecifier(importAs),
],
t.stringLiteral(state.opts.module || 'react')
)
const [newPath] = path.unshiftContainer('body', importSpecifier)
for (const specifier of newPath.get('specifiers')) {
path.scope.registerBinding(
'module',
specifier as NodePath<BabelTypes.Node>
)
}
}
}
},
},
},
}
}
``` | /content/code_sandbox/packages/next/src/build/babel/plugins/jsx-pragma.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 697 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppCollapsingTheme" parent="AppBaseTheme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
</resources>
``` | /content/code_sandbox/app/src/main/res/values-v21/styles.xml | xml | 2016-08-19T09:59:38 | 2024-07-21T15:24:26 | MvpApp | Rukey7/MvpApp | 2,342 | 136 |
```xml
export type UpperCaseCharacters =
| "A"
| "B"
| "C"
| "D"
| "E"
| "F"
| "G"
| "H"
| "I"
| "J"
| "K"
| "L"
| "M"
| "N"
| "O"
| "P"
| "Q"
| "R"
| "S"
| "T"
| "U"
| "V"
| "W"
| "X"
| "Y"
| "Z";
export type WordSeparators = "-" | "_" | " ";
export type StringDigit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
``` | /content/code_sandbox/packages/icons/src/type-utils/sourceUtilities.ts | xml | 2016-10-25T21:17:50 | 2024-08-16T15:14:48 | blueprint | palantir/blueprint | 20,593 | 193 |
```xml
import clsx from 'clsx';
import { createContext, PropsWithChildren, useContext } from 'react';
const Context = createContext<null | boolean>(null);
Context.displayName = 'InputGroupContext';
type Size = 'small' | 'large';
export function useInputGroupContext() {
const context = useContext(Context);
if (context == null) {
throw new Error('Should be inside a InputGroup component');
}
}
interface Props {
size?: Size;
className?: string;
}
export function InputGroup({
children,
size,
className,
}: PropsWithChildren<Props>) {
return (
<Context.Provider value>
<div className={clsx('input-group', sizeClass(size), className)}>
{children}
</div>
</Context.Provider>
);
}
function sizeClass(size?: Size) {
switch (size) {
case 'large':
return 'input-group-lg';
case 'small':
return 'input-group-sm';
default:
return '';
}
}
``` | /content/code_sandbox/app/react/components/form-components/InputGroup/InputGroup.tsx | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 213 |
```xml
import { DialogRef, DIALOG_DATA } from "@angular/cdk/dialog";
import { Component, Inject } from "@angular/core";
import { FormGroup } from "@angular/forms";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { SimpleDialogOptions, SimpleDialogType, Translation } from "../..";
const DEFAULT_ICON: Record<SimpleDialogType, string> = {
primary: "bwi-business",
success: "bwi-star",
info: "bwi-info-circle",
warning: "bwi-exclamation-triangle",
danger: "bwi-error",
};
const DEFAULT_COLOR: Record<SimpleDialogType, string> = {
primary: "tw-text-primary-600",
success: "tw-text-success",
info: "tw-text-info",
warning: "tw-text-warning",
danger: "tw-text-danger",
};
@Component({
templateUrl: "./simple-configurable-dialog.component.html",
})
export class SimpleConfigurableDialogComponent {
get iconClasses() {
return [
this.simpleDialogOpts.icon ?? DEFAULT_ICON[this.simpleDialogOpts.type],
DEFAULT_COLOR[this.simpleDialogOpts.type],
];
}
protected title: string;
protected content: string;
protected acceptButtonText: string;
protected cancelButtonText: string;
protected formGroup = new FormGroup({});
protected showCancelButton = this.simpleDialogOpts.cancelButtonText !== null;
constructor(
public dialogRef: DialogRef,
private i18nService: I18nService,
@Inject(DIALOG_DATA) public simpleDialogOpts?: SimpleDialogOptions,
) {
this.localizeText();
}
protected accept = async () => {
if (this.simpleDialogOpts.acceptAction) {
await this.simpleDialogOpts.acceptAction();
}
this.dialogRef.close(true);
};
private localizeText() {
this.title = this.translate(this.simpleDialogOpts.title);
this.content = this.translate(this.simpleDialogOpts.content);
this.acceptButtonText = this.translate(this.simpleDialogOpts.acceptButtonText, "yes");
if (this.showCancelButton) {
// If accept text is overridden, use cancel, otherwise no
this.cancelButtonText = this.translate(
this.simpleDialogOpts.cancelButtonText,
this.simpleDialogOpts.acceptButtonText !== undefined ? "cancel" : "no",
);
}
}
private translate(translation: string | Translation, defaultKey?: string): string {
// Translation interface use implies we must localize.
if (typeof translation === "object") {
return this.i18nService.t(translation.key, ...(translation.placeholders ?? []));
}
// Use string that is already translated or use default key post translate
return translation ?? this.i18nService.t(defaultKey);
}
}
``` | /content/code_sandbox/libs/components/src/dialog/simple-dialog/simple-configurable-dialog/simple-configurable-dialog.component.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 584 |
```xml
import { LinkingOptions } from '@react-navigation/native';
import { RouteNode } from './Route';
import { RouterStore } from './global-state/router-store';
import { getInitialURL, getPathFromState, getStateFromPath } from './link/linking';
import { RequireContext } from './types';
export declare function getNavigationConfig(routes: RouteNode, metaOnly?: boolean): {
initialRouteName: string | undefined;
screens: Record<string, import("./getReactNavigationConfig").Screen>;
};
export type ExpoLinkingOptions<T extends object = Record<string, unknown>> = LinkingOptions<T> & {
getPathFromState?: typeof getPathFromState;
getStateFromPath?: typeof getStateFromPath;
};
export type LinkingConfigOptions = {
metaOnly?: boolean;
serverUrl?: string;
getInitialURL?: typeof getInitialURL;
};
export declare function getLinkingConfig(store: RouterStore, routes: RouteNode, context: RequireContext, { metaOnly, serverUrl }?: LinkingConfigOptions): ExpoLinkingOptions;
//# sourceMappingURL=getLinkingConfig.d.ts.map
``` | /content/code_sandbox/packages/expo-router/build/getLinkingConfig.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 229 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
// TypeScript Version: 4.1
/// <reference types="@stdlib/types"/>
import { Iterator as Iter, IterableIterator } from '@stdlib/types/iter';
// Define a union type representing both iterable and non-iterable iterators:
type Iterator = Iter | IterableIterator;
/**
* Returns an iterator which iteratively computes the inverse half-value versed cosine.
*
* ## Notes
*
* - The domain of inverse half-value versed cosine is restricted to `[0,1]`. If an iterated value is outside of the domain, the returned iterator returns `NaN`.
* - If an environment supports `Symbol.iterator` **and** a provided iterator is iterable, the returned iterator is iterable.
*
* @param iterator - input iterator
* @returns iterator
*
* @example
* var uniform = require( '@stdlib/random/iter/uniform' );
*
* var iter = iterAhavercos( uniform( 0.0, 1.0 ) );
*
* var r = iter.next().value;
* // returns <number>
*
* r = iter.next().value;
* // returns <number>
*
* r = iter.next().value;
* // returns <number>
*
* // ...
*/
declare function iterAhavercos( iterator: Iterator ): Iterator;
// EXPORTS //
export = iterAhavercos;
``` | /content/code_sandbox/lib/node_modules/@stdlib/math/iter/special/ahavercos/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 329 |
```xml
<resources>
<string name="upgrade_msg"> Magisk Manager, . ?</string>
<string name="no_internet_msg"> , Magisk Manager .</string>
</resources>
``` | /content/code_sandbox/app/stub/src/main/res/values-bg/strings.xml | xml | 2016-09-08T12:42:53 | 2024-08-16T19:41:25 | Magisk | topjohnwu/Magisk | 46,424 | 48 |
```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.
-->
<merge xmlns:android="path_to_url">
<ImageView
android:id="@+id/iv_avatar"
style="@style/AvatarMedium"
android:contentDescription="@string/avatar" />
<TextView
android:id="@+id/tv_issue_creation"
style="@style/ListSubtitleText"
android:layout_width="0dp"
android:layout_weight="1"
android:paddingLeft="10dp"
android:paddingRight="2dp"
android:singleLine="true" />
<TextView
android:id="@+id/tv_pull_request_icon"
style="@style/ListIcon"
android:paddingRight="5dp" />
<TextView
android:id="@+id/tv_comment_icon"
style="@style/ListIcon" />
<TextView
android:id="@+id/tv_issue_comments"
style="@style/ListNumericSubtitleText"
android:paddingLeft="5dp" />
</merge>
``` | /content/code_sandbox/app/src/main/res/layout/issue_details.xml | xml | 2016-04-09T16:05:02 | 2024-08-08T06:37:18 | trugithub | kba7/trugithub | 2,055 | 253 |
```xml
import { stdSerializers } from "bunyan";
import { GraphQLError } from "graphql";
import StackUtils from "stack-utils";
import VError from "verror";
import { CoralError, CoralErrorContext } from "coral-server/errors";
interface SerializedError {
id?: string;
message: string;
name: string;
stack?: string;
context?: CoralErrorContext | Record<string, any>;
originalError?: SerializedError;
}
const stackUtils = new StackUtils();
const errSerializer = (err: Error) => {
const obj: SerializedError = {
message: err.message,
name: err.name,
};
if (err.stack) {
// Copy over a cleaned stack.
obj.stack = stackUtils.clean(err.stack);
}
if (err instanceof GraphQLError && err.originalError) {
// If the error was caused by another error, integrate it.
obj.originalError = errSerializer(err.originalError);
} else if (err instanceof CoralError) {
// Copy over the CoralError specific details.
obj.id = err.id;
obj.context = err.context;
// If the error was caused by another error, integrate it.
const cause = err.cause();
if (cause) {
obj.originalError = errSerializer(cause);
}
} else if (err instanceof VError) {
obj.context = VError.info(err);
}
return obj;
};
export default {
...stdSerializers,
err: errSerializer,
};
``` | /content/code_sandbox/server/src/core/server/logger/serializers.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 324 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="path_to_url">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<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|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{5291ff8e-fecd-42b2-bdc0-275cd7c9a671}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<ProjectName>ClassesStructs</ProjectName>
<RootNamespace>ClassesStructs</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<ApplicationTypeRevision>8.1</ApplicationTypeRevision>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PlatformToolset>v120</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<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|ARM'">
<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)'=='Debug|x64'">
<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|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
<ClInclude Include="Class1.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="Class1.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
``` | /content/code_sandbox/docs/cppcx/codesnippet/CPP/classesstructs/classesstructs.vcxproj | xml | 2016-11-14T19:38:32 | 2024-08-16T09:06:37 | cpp-docs | MicrosoftDocs/cpp-docs | 1,425 | 2,881 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="path_to_url" xmlns:xsi="path_to_url" xmlns:xsd="path_to_url" xmlns:flowable="path_to_url" xmlns:bpmndi="path_to_url" xmlns:omgdc="path_to_url" xmlns:omgdi="path_to_url" typeLanguage="path_to_url" expressionLanguage="path_to_url" targetNamespace="path_to_url">
<process id="testExpressionFunction" name="testExpressionFunction" isExecutable="true">
<startEvent id="startEvent1"></startEvent>
<exclusiveGateway id="sid-6E34791D-78DF-4C8F-B731-8CE6CCEBFB19" default="sid-826377D5-8D95-4735-8181-543CDCCECB89"></exclusiveGateway>
<sequenceFlow id="sid-BA634968-FB98-41FE-A40B-113E3A040917" sourceRef="startEvent1" targetRef="sid-6E34791D-78DF-4C8F-B731-8CE6CCEBFB19"></sequenceFlow>
<userTask id="sid-F5799224-7B30-46E7-B703-4E1028A136BE" name="A"></userTask>
<userTask id="sid-CC202B6A-5FCD-4E7F-9805-98054E856277" name="B"></userTask>
<endEvent id="sid-1A08718D-53D5-40C9-AA3E-646959109884"></endEvent>
<sequenceFlow id="sid-C62C8C0D-44D4-4A3D-ABCB-4E1F553945CB" sourceRef="sid-F5799224-7B30-46E7-B703-4E1028A136BE" targetRef="sid-1A08718D-53D5-40C9-AA3E-646959109884"></sequenceFlow>
<endEvent id="sid-E3D726DE-D19C-49BF-BAA2-A7DB85EF8EB9"></endEvent>
<sequenceFlow id="sid-A307500B-C2C6-4AEE-B671-616338A20ACE" sourceRef="sid-CC202B6A-5FCD-4E7F-9805-98054E856277" targetRef="sid-E3D726DE-D19C-49BF-BAA2-A7DB85EF8EB9"></sequenceFlow>
<sequenceFlow id="sid-826377D5-8D95-4735-8181-543CDCCECB89" sourceRef="sid-6E34791D-78DF-4C8F-B731-8CE6CCEBFB19" targetRef="sid-CC202B6A-5FCD-4E7F-9805-98054E856277"></sequenceFlow>
<sequenceFlow id="sid-7D60A91B-B875-44A4-ACC6-976FAF73FB97" sourceRef="sid-6E34791D-78DF-4C8F-B731-8CE6CCEBFB19" targetRef="sid-F5799224-7B30-46E7-B703-4E1028A136BE">
<conditionExpression xsi:type="tFormalExpression"><![CDATA[${variables:get(myVar) == "go to A"}]]></conditionExpression>
</sequenceFlow>
</process>
<bpmndi:BPMNDiagram id="BPMNDiagram_testExpressionFunction">
<bpmndi:BPMNPlane bpmnElement="testExpressionFunction" id="BPMNPlane_testExpressionFunction">
<bpmndi:BPMNShape bpmnElement="startEvent1" id="BPMNShape_startEvent1">
<omgdc:Bounds height="30.0" width="30.0" x="90.0" y="225.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="sid-6E34791D-78DF-4C8F-B731-8CE6CCEBFB19" id="BPMNShape_sid-6E34791D-78DF-4C8F-B731-8CE6CCEBFB19">
<omgdc:Bounds height="40.0" width="40.0" x="165.0" y="220.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="sid-F5799224-7B30-46E7-B703-4E1028A136BE" id="BPMNShape_sid-F5799224-7B30-46E7-B703-4E1028A136BE">
<omgdc:Bounds height="80.0" width="100.0" x="270.0" y="105.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="sid-CC202B6A-5FCD-4E7F-9805-98054E856277" id="BPMNShape_sid-CC202B6A-5FCD-4E7F-9805-98054E856277">
<omgdc:Bounds height="80.0" width="100.0" x="270.0" y="300.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="sid-1A08718D-53D5-40C9-AA3E-646959109884" id="BPMNShape_sid-1A08718D-53D5-40C9-AA3E-646959109884">
<omgdc:Bounds height="28.0" width="28.0" x="415.0" y="131.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="sid-E3D726DE-D19C-49BF-BAA2-A7DB85EF8EB9" id="BPMNShape_sid-E3D726DE-D19C-49BF-BAA2-A7DB85EF8EB9">
<omgdc:Bounds height="28.0" width="28.0" x="415.0" y="326.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="sid-A307500B-C2C6-4AEE-B671-616338A20ACE" id="BPMNEdge_sid-A307500B-C2C6-4AEE-B671-616338A20ACE">
<omgdi:waypoint x="369.949999999934" y="340.0"></omgdi:waypoint>
<omgdi:waypoint x="415.0" y="340.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="sid-826377D5-8D95-4735-8181-543CDCCECB89" id="BPMNEdge_sid-826377D5-8D95-4735-8181-543CDCCECB89">
<omgdi:waypoint x="185.5" y="259.44048694779116"></omgdi:waypoint>
<omgdi:waypoint x="185.5" y="340.0"></omgdi:waypoint>
<omgdi:waypoint x="270.0" y="340.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="sid-C62C8C0D-44D4-4A3D-ABCB-4E1F553945CB" id="BPMNEdge_sid-C62C8C0D-44D4-4A3D-ABCB-4E1F553945CB">
<omgdi:waypoint x="369.949999999996" y="145.0"></omgdi:waypoint>
<omgdi:waypoint x="415.0" y="145.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="sid-7D60A91B-B875-44A4-ACC6-976FAF73FB97" id="BPMNEdge_sid-7D60A91B-B875-44A4-ACC6-976FAF73FB97">
<omgdi:waypoint x="185.5" y="220.5"></omgdi:waypoint>
<omgdi:waypoint x="185.5" y="145.0"></omgdi:waypoint>
<omgdi:waypoint x="270.0" y="145.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="sid-BA634968-FB98-41FE-A40B-113E3A040917" id="BPMNEdge_sid-BA634968-FB98-41FE-A40B-113E3A040917">
<omgdi:waypoint x="119.9496588110467" y="240.09285545292158"></omgdi:waypoint>
<omgdi:waypoint x="165.375" y="240.375"></omgdi:waypoint>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>
``` | /content/code_sandbox/modules/flowable-engine/src/test/resources/org/flowable/engine/test/el/function/VariableExpressionFunctionsTest.testGetVariable.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 2,281 |
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "path_to_url" >
<mapper namespace="com.jsh.erp.datasource.mappers.MaterialExtendMapperEx" >
<resultMap extends="com.jsh.erp.datasource.mappers.MaterialExtendMapper.BaseResultMap" id="ResultMapList" type="com.jsh.erp.datasource.vo.MaterialExtendVo4List">
</resultMap>
<select id="getDetailList" parameterType="com.jsh.erp.datasource.entities.MaterialExtendExample" resultMap="ResultMapList">
select DISTINCT d.Id,d.bar_code,d.commodity_unit,d.sku,d.commodity_decimal,d.purchase_decimal,d.wholesale_decimal,d.low_decimal
from jsh_material_extend d
where d.material_id = #{materialId}
and ifnull(d.delete_Flag,'0') !='1'
order by d.default_flag desc,d.id asc
</select>
<select id="getMaxTimeByTenantAndTime" resultType="java.lang.Long">
select max(update_time) from
(
select update_time from jsh_material_extend
where 1=1
<if test="lastTime != null">
and update_time > #{lastTime}
</if>
order by update_time asc
<if test="syncNum != null">
limit 0,#{syncNum}
</if>
) time_list
</select>
<select id="getListByMId" resultType="com.jsh.erp.datasource.entities.MaterialExtend">
select
<include refid="com.jsh.erp.datasource.mappers.MaterialExtendMapper.Base_Column_List" />
from jsh_material_extend
where 1=1
and ifnull(delete_Flag,'0') !='1'
and material_id in (
<foreach collection="ids" item="id" separator=",">
#{id}
</foreach>
)
group by material_id
</select>
<update id="batchDeleteMaterialExtendByIds">
update jsh_material_extend
set delete_Flag='1'
where 1=1
and ifnull(delete_Flag,'0') !='1'
and id in (
<foreach collection="ids" item="id" separator=",">
#{id}
</foreach>
)
</update>
<update id="batchDeleteMaterialExtendByMIds">
update jsh_material_extend
set delete_Flag='1'
where 1=1
and ifnull(delete_Flag,'0') !='1'
and material_id in (
<foreach collection="ids" item="id" separator=",">
#{id}
</foreach>
)
</update>
<update id="specialUpdatePrice" parameterType="com.jsh.erp.datasource.entities.MaterialExtend">
update jsh_material_extend
set purchase_decimal = #{purchaseDecimal,jdbcType=DECIMAL},
commodity_decimal = #{commodityDecimal,jdbcType=DECIMAL},
wholesale_decimal = #{wholesaleDecimal,jdbcType=DECIMAL},
low_decimal = #{lowDecimal,jdbcType=DECIMAL}
where id = #{id,jdbcType=BIGINT}
and ifnull(delete_flag,'0') !='1'
</update>
</mapper>
``` | /content/code_sandbox/jshERP-boot/src/main/resources/mapper_xml/MaterialExtendMapperEx.xml | xml | 2016-09-20T04:51:39 | 2024-08-16T16:42:52 | jshERP | jishenghua/jshERP | 3,107 | 716 |
```xml
import {Injectable} from '@angular/core';
import {Event} from '../../../../common/event/Event';
declare const document: {
fullscreenElement: boolean;
mozFullScreenElement: boolean;
webkitFullscreenElement: boolean;
exitFullscreen: () => void;
mozCancelFullScreen: () => void;
webkitExitFullscreen: () => void;
};
@Injectable()
export class FullScreenService {
OnFullScreenChange = new Event<boolean>();
public isFullScreenEnabled(): boolean {
return !!(
document.fullscreenElement ||
document.mozFullScreenElement ||
document.webkitFullscreenElement
);
}
public showFullScreen(element: Element): void {
if (this.isFullScreenEnabled()) {
return;
}
if (element.requestFullscreen) {
element.requestFullscreen().catch(console.error);
} else if ((element as unknown as Record<string, () => void>).mozRequestFullScreen) {
(element as unknown as Record<string, () => void>).mozRequestFullScreen();
} else if ((element as unknown as Record<string, () => void>).webkitRequestFullscreen) {
(element as unknown as Record<string, () => void>).webkitRequestFullscreen();
} else if ((element as unknown as Record<string, () => void>).msRequestFullscreen) {
(element as unknown as Record<string, () => void>).msRequestFullscreen();
}
this.OnFullScreenChange.trigger(true);
}
public exitFullScreen(): void {
if (!this.isFullScreenEnabled()) {
return;
}
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
this.OnFullScreenChange.trigger(false);
}
}
``` | /content/code_sandbox/src/frontend/app/ui/gallery/fullscreen.service.ts | xml | 2016-03-12T11:46:41 | 2024-08-16T19:56:44 | pigallery2 | bpatrik/pigallery2 | 1,727 | 378 |
```xml
import { ActionDefinitions, KeaAction, KeaReduxAction, Logic, LogicBuilder, PayloadCreatorDefinition } from '../types'
import { getContext, getPluginContext } from '../kea/context'
import type { ListenersPluginContext } from './listeners'
import { isBreakpoint } from './listeners'
let asyncCounter = 0
const nextDispatchId = () => String(++asyncCounter)
/** Logic builder: actions({ actionWithParams: (id) => ({ id }), actionNoParams: true }) */
export function actions<L extends Logic = Logic>(
input: ActionDefinitions<L> | ((logic: L) => ActionDefinitions<L>),
): LogicBuilder<L> {
return (logic) => {
const actions = typeof input === 'function' ? input(logic) : input
for (const [key, payloadCreator] of Object.entries(actions)) {
const actionCreator: KeaAction =
typeof payloadCreator === 'function' && '_isKeaAction' in payloadCreator
? (payloadCreator as KeaAction)
: createActionCreator(createActionType(key, logic.pathString), payloadCreator ?? true)
const type = actionCreator.toString()
const {
options: { disableAsyncActions },
} = getContext()
logic.actionCreators[key] = actionCreator
logic.actions[key] = (...inp: any[]) => {
const builtAction = actionCreator(...inp)
getContext().store.dispatch(
disableAsyncActions ? builtAction : { ...builtAction, dispatchId: nextDispatchId() },
)
}
logic.actions[key].toString = () => type
if (!disableAsyncActions) {
logic.asyncActions[key] = async (...inp: any[]) => {
const builtAction = actionCreator(...inp)
let dispatchId = nextDispatchId()
getContext().store.dispatch({ ...builtAction, dispatchId })
const { pendingDispatches } = getPluginContext<ListenersPluginContext>('listeners')
while (true) {
const promises = pendingDispatches.get(dispatchId)
if (!promises) {
return
}
try {
const responses = await Promise.all(promises)
return responses[0]
} catch (e: any) {
if (isBreakpoint(e)) {
if ('__keaDispatchId' in e) {
dispatchId = e.__keaDispatchId
// loop again
}
} else {
throw e
}
}
}
}
logic.asyncActions[key].toString = () => type
}
logic.actionKeys[type] = key
logic.actionTypes[key] = type
}
}
}
export function createActionCreator(type: string, payloadCreator: PayloadCreatorDefinition): KeaAction {
const action = <KeaAction>(...payloadArgs: any[]): KeaReduxAction => ({
type: type,
payload: typeof payloadCreator === 'function' ? payloadCreator(...payloadArgs) : { value: true },
})
action.toString = () => type
action._isKeaAction = true
return action
}
export function createActionType(key: string, pathString: string): string {
const toSpaces = (key: string) => key.replace(/(?:^|\.?)([A-Z])/g, (x, y) => ' ' + y.toLowerCase()).replace(/^ /, '')
return `${toSpaces(key)} (${pathString})`
}
``` | /content/code_sandbox/src/core/actions.ts | xml | 2016-03-29T08:30:54 | 2024-08-10T20:41:40 | kea | keajs/kea | 1,933 | 721 |
```xml
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-curso-form',
templateUrl: './curso-form.component.html',
styleUrls: ['./curso-form.component.css']
})
export class CursoFormComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
``` | /content/code_sandbox/rotas/src/app/cursos/curso-form/curso-form.component.ts | xml | 2016-07-02T18:58:48 | 2024-08-15T23:36:46 | curso-angular | loiane/curso-angular | 1,910 | 62 |
```xml
import assert from 'assert';
import {
getStatusForInput,
getSelectedReferencesStatus,
getStatusForArrayInput,
REFERENCES_STATUS_READY,
REFERENCES_STATUS_INCOMPLETE,
REFERENCES_STATUS_EMPTY,
} from './referenceDataStatus';
describe('References data status', () => {
describe('getStatusForInput', () => {
const data = {
field: {},
matchingReferences: null,
referenceRecord: null,
translate: x => `*${x}*`,
};
it('should indicate whether the data are ready or not', () => {
const test = (params, waiting, explanation) =>
assert.equal(
getStatusForInput(params).waiting,
waiting,
explanation
);
test(
data,
true,
'we must waitFor until the references fetch is finished and there is no reference already associated with the resource.'
);
test(
{ ...data, field: { value: 1 } },
true,
'we must waitFor until the references fetch is finished and linked reference data are not found.'
);
test(
{ ...data, field: { value: 1 }, referenceRecord: [{ id: 1 }] },
false,
'it is ready if the references fetch is not finished but linked reference data are found.'
);
test(
{ ...data, field: { value: 1 }, matchingReferences: [] },
false,
'it is ready if linked reference data are not found, but the references fetch is finished.'
);
test(
{
...data,
field: { value: 1 },
matchingReferences: { error: 'error' },
},
false,
'it is ready if linked reference data are not found, but the references fetch is finished with error.'
);
});
it('should claim an error if needed', () => {
const test = (params, error, explanation) => {
const status = getStatusForInput(params);
assert.equal(status.waiting, false);
assert.equal(status.error, error, explanation);
};
test(
{
...data,
matchingReferences: { error: 'error' },
},
'*error*',
'there is an error if the references fetch fails and there is no linked reference'
);
test(
{
...data,
matchingReferences: { error: 'error' },
field: { value: 1 },
},
'*ra.input.references.single_missing*',
'there is an error if the references fetch fails and there is a linked reference without data'
);
test(
{
...data,
matchingReferences: { error: 'error' },
field: { value: 1 },
referenceRecord: [{ id: 1 }],
},
null,
'there is no error if the references fetch fails but there is a linked reference with data'
);
test(
{
...data,
matchingReferences: [{ id: 2 }],
field: { value: 1 },
referenceRecord: null,
},
null,
'there is no error if there is a linked reference without data but the references fetch succeeds'
);
test(
{
...data,
matchingReferences: [],
field: { value: 1 },
referenceRecord: null,
},
null,
'there is no error if there is a linked reference without data but the references fetch succeeds even empty'
);
test(
{
...data,
matchingReferences: [{ id: 1 }],
},
null,
'there is no error if the references fetch succeeds and there is no linked reference'
);
});
it('should claim a warning if needed', () => {
const test = (params, warning, explanation) => {
const status = getStatusForInput(params);
assert.equal(status.waiting, false);
assert.equal(status.error, null);
assert.equal(status.warning, warning, explanation);
};
test(
{
...data,
matchingReferences: { error: 'error on fetch' },
field: { value: 1 },
referenceRecord: [{ id: 1 }],
},
'*error on fetch*',
'there is a warning if the references fetch fails but there is a linked reference with data'
);
test(
{
...data,
matchingReferences: [{ id: 2 }],
field: { value: 1 },
referenceRecord: null,
},
'*ra.input.references.single_missing*',
'there is a warning if there is a linked reference without data but the references fetch succeeds'
);
test(
{
...data,
matchingReferences: [],
field: { value: 1 },
referenceRecord: [{ value: 1 }],
},
null,
'there is no warning if there is a linked reference with data and the references fetch succeeds even empty'
);
test(
{
...data,
matchingReferences: [],
},
null,
'there is no warning if the references fetch succeeds and there is no linked reference'
);
});
it('should return choices consistent with the data status', () => {
const test = (params, warning, choices, explanation) => {
const status = getStatusForInput(params);
assert.equal(status.waiting, false);
assert.equal(status.error, null);
assert.equal(status.warning, warning);
assert.deepEqual(status.choices, choices, explanation);
};
test(
{
...data,
matchingReferences: { error: 'error on fetch' },
field: { value: 1 },
referenceRecord: { id: 1 },
},
'*error on fetch*',
[{ id: 1 }],
'if the references fetch fails the single choice is the linked reference'
);
test(
{
...data,
matchingReferences: [{ id: 2 }],
field: { value: 1 },
referenceRecord: null,
},
'*ra.input.references.single_missing*',
[{ id: 2 }],
'if there is no data for the linked reference, the choices are those returned by fetch'
);
test(
{
...data,
matchingReferences: [{ id: 1 }, { id: 2 }],
field: { value: 1 },
referenceRecord: { id: 1 },
},
null,
[{ id: 1 }, { id: 2 }],
'if there is data for the linked reference and the references fetch succeeds, we use the choices returned by fetch (that will include the linked reference, but this is not managed at getStatusForInput method level.)'
);
});
});
describe('getSelectedReferencesStatus', () => {
it('should return ready if input value has no references', () => {
const test = (input, referenceRecords) =>
assert.equal(
getSelectedReferencesStatus(input, referenceRecords),
REFERENCES_STATUS_READY
);
test({}, []);
test({ value: null }, []);
test({ value: false }, []);
test({ value: [] }, []);
});
it('should return empty if there is some input values but the referenceRecords is empty', () => {
assert.equal(
getSelectedReferencesStatus({ value: [1, 2] }, []),
REFERENCES_STATUS_EMPTY
);
});
it('should return incomplete if there is less data in the referenceRecords than values in the input value', () => {
assert.equal(
getSelectedReferencesStatus({ value: [1, 2] }, [{ id: 1 }]),
REFERENCES_STATUS_INCOMPLETE
);
});
it('should return ready if there is as much data in the referenceRecords as there are values in the input value', () => {
assert.equal(
getSelectedReferencesStatus({ value: [1, 2] }, [
{ id: 1 },
{ id: 2 },
]),
REFERENCES_STATUS_READY
);
});
});
describe('getStatusForArrayInput', () => {
const data = {
field: {},
matchingReferences: null,
referenceRecords: [],
translate: x => `*${x}*`,
};
it('should indicate whether the data are ready or not', () => {
const test = (params, waiting, explanation) =>
assert.equal(
getStatusForArrayInput(params).waiting,
waiting,
explanation
);
test(
data,
true,
'we must waitFor until the references fetch is finished and there is no reference already associated with the resource.'
);
test(
{ ...data, field: { value: [1, 2] } },
true,
'we must waitFor until the references fetch is finished and linked references data are not found.'
);
test(
{
...data,
field: { value: [1, 2] },
referenceRecords: [{ id: 1 }],
},
false,
'it is ready if the references fetch is not finished but at least one linked reference data are found.'
);
test(
{ ...data, field: { value: [1, 2] }, matchingReferences: [] },
false,
'it is ready if none linked reference data are not found, but the references fetch is finished.'
);
test(
{
...data,
field: { value: [1, 2] },
matchingReferences: { error: 'error' },
},
false,
'it is ready if linked reference data are not found, but the references fetch is finished with error.'
);
});
it('should return an error if needed', () => {
const test = (params, error, explanation) => {
const status = getStatusForArrayInput(params);
assert.equal(status.waiting, false);
assert.equal(status.error, error, explanation);
};
test(
{
...data,
matchingReferences: { error: 'error' },
},
'*ra.input.references.all_missing*',
'there is an error if the references fetch fails and there is no linked reference'
);
test(
{
...data,
matchingReferences: { error: 'error' },
field: { value: [1] },
},
'*ra.input.references.all_missing*',
'there is an error if the references fetch fails and there is all linked reference without data'
);
test(
{
...data,
matchingReferences: { error: 'error' },
field: { value: [1, 2] },
referenceRecords: [{ id: 1 }],
},
null,
'there is no error if the references fetch fails but there is at least one linked reference with data'
);
test(
{
...data,
matchingReferences: [{ id: 2 }],
field: { value: [1, 2] },
referenceRecords: [],
},
null,
'there is no error if there is all linked references without data but the references fetch succeeds'
);
test(
{
...data,
matchingReferences: [],
field: { value: [1, 2] },
referenceRecords: [],
},
null,
'there is no error if there is a linked reference without data but the references fetch succeeds even empty'
);
test(
{
...data,
matchingReferences: [{ id: 1 }],
},
null,
'there is no error if the references fetch succeeds and there is no linked reference'
);
});
it('should return a warning if needed', () => {
const test = (params, warning, explanation) => {
const status = getStatusForArrayInput(params);
assert.equal(status.waiting, false);
assert.equal(status.error, null);
assert.equal(status.warning, warning, explanation);
};
test(
{
...data,
matchingReferences: { error: 'error on fetch' },
field: { value: [1] },
referenceRecords: [{ id: 1 }],
},
'*error on fetch*',
'there is a warning if the references fetch fails but there is linked references with data'
);
test(
{
...data,
matchingReferences: [{ id: 3 }],
field: { value: [1, 2] },
referenceRecords: [{ id: 2 }],
},
'*ra.input.references.many_missing*',
'there is a warning if there is at least one linked reference without data but the references fetch succeeds'
);
test(
{
...data,
matchingReferences: [],
field: { value: [1, 2] },
referenceRecords: [{ id: 1 }, { id: 2 }],
},
null,
'there is no warning if there is all linked references with data and the references fetch succeeds even empty'
);
test(
{
...data,
matchingReferences: [],
},
null,
'there is no warning if the references fetch succeeds and there is no linked references'
);
});
it('should return choices consistent with the data status', () => {
const test = (params, warning, choices, explanation) => {
const status = getStatusForArrayInput(params);
assert.equal(status.waiting, false);
assert.equal(status.error, null);
assert.equal(status.warning, warning);
assert.deepEqual(status.choices, choices, explanation);
};
test(
{
...data,
matchingReferences: { error: 'error on fetch' },
field: { value: [1, 2] },
referenceRecords: [{ id: 1 }, { id: 2 }],
},
'*error on fetch*',
[{ id: 1 }, { id: 2 }],
'if the references fetch fails the choices are the linked references'
);
test(
{
...data,
matchingReferences: [{ id: 3 }],
field: { value: [1, 2] },
referenceRecords: [],
},
'*ra.input.references.many_missing*',
[{ id: 3 }],
'if there is no data for the linked references, the choices are those returned by fetch'
);
test(
{
...data,
matchingReferences: [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
],
field: { value: [1, 2] },
referenceRecords: [{ id: 1 }, { id: 2 }],
},
null,
[{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
'if there is data for the linked reference and the references fetch succeeds, we use the choices returned by fetch (that will include the linked reference, but this is not managed at getStatusForArrayInput method level.)'
);
});
});
});
``` | /content/code_sandbox/packages/ra-core/src/controller/input/referenceDataStatus.spec.ts | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 3,182 |
```xml
import {Builder} from 'selenium-webdriver';
import {
ServiceBuilder,
Options as ChromeOptions,
setDefaultService,
} from 'selenium-webdriver/chrome.js';
export function configureDriver() {
const options = new ChromeOptions();
const service = new ServiceBuilder(process.env['CHROMEDRIVER_BIN']!);
options.headless();
options.addArguments('--no-sandbox');
options.setChromeBinaryPath(process.env['CHROME_BIN']!);
setDefaultService(service.build());
return new Builder().forBrowser('chrome').setChromeOptions(options).build();
}
``` | /content/code_sandbox/integration/harness-e2e-cli/e2e/driver.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 127 |
```xml
import * as React from 'react';
import * as _ from 'lodash';
import { Text, ProviderConsumer } from '@fluentui/react-northstar';
const TextExampleColor = () => (
<ProviderConsumer
render={({ siteVariables: { contextualColors, naturalColors } }) =>
_.keys({ ...contextualColors, ...naturalColors }).map(color => (
<React.Fragment key={color}>
<Text color={color} content={_.startCase(color)} />
<br />
</React.Fragment>
))
}
/>
);
export default TextExampleColor;
``` | /content/code_sandbox/packages/fluentui/docs/src/examples/components/Text/Variations/TextExampleColor.shorthand.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 124 |
```xml
<?xml version="1.0"?>
<package format="3">
<name>moveit_ros_planning_interface</name>
<version>1.1.14</version>
<description>Components of MoveIt that offer simpler interfaces to planning and execution</description>
<author email="isucan@google.com">Ioan Sucan</author>
<maintainer email="mferguson@fetchrobotics.com">Michael Ferguson</maintainer>
<maintainer email="me@v4hn.de">Michael Grner</maintainer>
<maintainer email="moveit_releasers@googlegroups.com">MoveIt Release Team</maintainer>
<license>BSD</license>
<url type="website">path_to_url
<url type="bugtracker">path_to_url
<url type="repository">path_to_url
<buildtool_depend>catkin</buildtool_depend>
<buildtool_depend condition="$ROS_PYTHON_VERSION == 2">python-catkin-pkg</buildtool_depend>
<buildtool_depend condition="$ROS_PYTHON_VERSION == 3">python3-catkin-pkg</buildtool_depend>
<depend>moveit_ros_planning</depend>
<depend>moveit_ros_warehouse</depend>
<depend>moveit_ros_move_group</depend>
<depend>moveit_ros_manipulation</depend>
<depend>roscpp</depend>
<depend>rospy</depend>
<depend>rosconsole</depend>
<depend>actionlib</depend>
<depend>geometry_msgs</depend>
<depend>moveit_msgs</depend>
<depend>tf2</depend>
<depend>tf2_eigen</depend>
<depend>tf2_geometry_msgs</depend>
<depend>tf2_ros</depend>
<depend condition="$ROS_PYTHON_VERSION == 2">python</depend>
<depend condition="$ROS_PYTHON_VERSION == 3">python3</depend>
<depend>eigenpy</depend>
<build_depend>eigen</build_depend>
<test_depend>moveit_resources_fanuc_moveit_config</test_depend>
<test_depend>moveit_resources_panda_moveit_config</test_depend>
<test_depend>rostest</test_depend>
</package>
``` | /content/code_sandbox/moveit_ros/planning_interface/package.xml | xml | 2016-07-27T20:38:09 | 2024-08-15T02:08:44 | moveit | moveit/moveit | 1,626 | 501 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions
xmlns="path_to_url"
targetNamespace="Examples">
<process id="noneTaskProcess" name="None Task Process">
<documentation>This is a process for testing purposes</documentation>
<startEvent id="theStart" />
<sequenceFlow id="flow1" sourceRef="theStart" targetRef="theEnd" />
<endEvent id="theEnd" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/engine/test/api/event/ProcessInstanceEventsTest.noneTaskProcess.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 110 |
```xml
<stix:STIX_Package xmlns:FileObj="path_to_url#FileObject-2" xmlns:cybox="path_to_url" xmlns:cyboxCommon="path_to_url" xmlns:cyboxVocabs="path_to_url" xmlns:example="path_to_url" xmlns:indicator="path_to_url" xmlns:stix="path_to_url" xmlns:stixCommon="path_to_url" xmlns:stixVocabs="path_to_url" xmlns:ttp="path_to_url" xmlns:xsi="path_to_url" id="example:Package-bc2955f8-f1bb-4f02-b2ed-339d7daf6d75" version="1.2">
<stix:STIX_Header>
<stix:Title>File Hash Reputation Service Results</stix:Title>
<stix:Package_Intent xsi:type="stixVocabs:PackageIntentVocab-1.0">Indicators - Malware Artifacts</stix:Package_Intent>
</stix:STIX_Header>
<stix:Indicators>
<stix:Indicator id="example:indicator-14975dea-86cd-4211-a5f8-9c2e4daab69a" timestamp="2015-07-20T19:52:13.853585+00:00" xsi:type="indicator:IndicatorType">
<indicator:Title>
File Reputation for SHA256=your_sha256_hash
</indicator:Title>
<indicator:Type xsi:type="stixVocabs:IndicatorTypeVocab-1.1">File Hash Watchlist</indicator:Type>
<indicator:Observable id="example:Observable-7b97c8a2-2d0b-4af7-bcf0-cad28f2fea5a">
<cybox:Object id="example:File-b04bfc7c-04ae-4dfe-ba8e-a297f0717552">
<cybox:Properties xsi:type="FileObj:FileObjectType">
<FileObj:Hashes>
<cyboxCommon:Hash>
<cyboxCommon:Type condition="Equals" xsi:type="cyboxVocabs:HashNameVocab-1.0">SHA256</cyboxCommon:Type>
<cyboxCommon:Simple_Hash_Value condition="Equals">
your_sha256_hash
</cyboxCommon:Simple_Hash_Value>
</cyboxCommon:Hash>
<cyboxCommon:Hash>
<cyboxCommon:Type condition="Equals" xsi:type="cyboxVocabs:HashNameVocab-1.0">SSDEEP</cyboxCommon:Type>
<cyboxCommon:Fuzzy_Hash_Value condition="Equals">193:iAklVz3fzvBk5oFblLPBN1iXf2bCRErwyN4aEbwyiNwyiQwNeDAi4XMG:iAklVzfzvBTFblLpN1iXOYpyuapyiWym</cyboxCommon:Fuzzy_Hash_Value>
</cyboxCommon:Hash>
</FileObj:Hashes>
</cybox:Properties>
</cybox:Object>
</indicator:Observable>
<indicator:Indicated_TTP>
<stixCommon:TTP id="example:ttp-23e715a9-24c8-4b21-ba5b-f564d2edc660" timestamp="2015-07-20T19:52:13.854415+00:00" xsi:type="ttp:TTPType">
<ttp:Title>Malicious file</ttp:Title>
</stixCommon:TTP>
</indicator:Indicated_TTP>
<indicator:Confidence timestamp="2015-07-20T19:52:13.854506+00:00">
<stixCommon:Value vocab_reference="path_to_url" vocab_name="Percentage">75</stixCommon:Value>
</indicator:Confidence>
</stix:Indicator>
</stix:Indicators>
</stix:STIX_Package>
``` | /content/code_sandbox/Packs/Base/Scripts/StixParser/test_data/stix1_tests/file-stix-ioc.xml | xml | 2016-06-06T12:17:02 | 2024-08-16T11:52:59 | content | demisto/content | 1,108 | 907 |
```xml
<Project>
<PropertyGroup>
<StaticWebAssetsSdkRoot>$(RepoRoot)\src\StaticWebAssetsSdk\</StaticWebAssetsSdkRoot>
<PackageId>Microsoft.NET.Sdk.StaticWebAssets</PackageId>
<OutDirName>$(Configuration)\Sdks\$(PackageId)\tasks</OutDirName>
<!-- Avoid path_to_url -->
<AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>
</PropertyGroup>
<Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
<PropertyGroup>
<TargetFrameworks>$(SdkTargetFramework);net472</TargetFrameworks>
<OutputType>Library</OutputType>
<Description>SDK for building and publishing applications containing static web assets.</Description>
<RootNamespace>Microsoft.NET.Sdk.StaticWebAssets</RootNamespace>
<GenerateDependencyFile>false</GenerateDependencyFile>
<IncludeBuildOutput>false</IncludeBuildOutput>
<NoPackageAnalysis>true</NoPackageAnalysis>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<CopyLocalLockFileAssemblies Condition="'$(TargetFramework)'!='net472'">false</CopyLocalLockFileAssemblies>
<!-- MSBuild Task DLLs need to be versioned with every build -->
<AutoGenerateAssemblyVersion>true</AutoGenerateAssemblyVersion>
<OutputPath>$(BaseOutputPath)</OutputPath>
<IsPackable>true</IsPackable>
<PackageLayoutOutputPath>$(ArtifactsBinDir)$(Configuration)\Sdks\$(PackageId)\</PackageLayoutOutputPath>
<NoDefaultExcludes>true</NoDefaultExcludes>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Build.Framework" ExcludeAssets="Runtime" />
<PackageReference Include="Microsoft.Build.Utilities.Core" ExcludeAssets="Runtime" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" />
<PackageReference Include="Microsoft.Css.Parser" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<PackageReference Include="System.Reflection.Metadata" VersionOverride="$(SystemReflectionMetadataVersion)" />
<PackageReference Include="System.Text.Json" />
</ItemGroup>
<!-- Only include these files in the outer build to avoid double writes. -->
<ItemGroup Condition="'$(IsCrossTargetingBuild)' == 'true'">
<AdditionalContent Include="$(StaticWebAssetsSdkRoot)Targets\**\*.*"
Pack="true"
PackagePath="targets" />
<AdditionalContent Include="$(StaticWebAssetsSdkRoot)Sdk\**\*.*"
Pack="true"
PackagePath="Sdk" />
</ItemGroup>
<ItemDefinitionGroup>
<PackageReference>
<PrivateAssets>All</PrivateAssets>
<Publish>true</Publish>
</PackageReference>
</ItemDefinitionGroup>
<Target Name="CopyFileSystemGlobbing"
BeforeTargets="PrepareAdditionalFilesToLayout"
AfterTargets="ResolveReferences"
Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'">
<ItemGroup>
<_FileSystemGlobbing Include="@(ReferencePath)" Condition="'%(ReferencePath.NuGetPackageId)' == 'Microsoft.Extensions.FileSystemGlobbing'" />
<_FileSystemGlobbingContent Include="@(_FileSystemGlobbing)" TargetPath="tasks\$(TargetFramework)\%(_FileSystemGlobbing.Filename)%(_FileSystemGlobbing.Extension)" />
<AdditionalContent Include="@(_FileSystemGlobbing)" PackagePath="tasks\$(TargetFramework)" />
</ItemGroup>
<Copy SourceFiles="@(_FileSystemGlobbingContent)"
DestinationFiles="@(_FileSystemGlobbingContent->'$(PackageLayoutOutputPath)%(TargetPath)')"
SkipUnchangedFiles="true">
<Output TaskParameter="DestinationFiles" ItemName="FileWrites" />
</Copy>
</Target>
<Target Name="CopyCssParser"
BeforeTargets="PrepareAdditionalFilesToLayout"
AfterTargets="ResolveReferences"
Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'">
<ItemGroup>
<_CssParser Include="@(ReferencePath->WithMetadataValue('NuGetPackageId', 'Microsoft.Css.Parser'))" />
<_CssParserContent Include="@(_CssParser)" TargetPath="tasks\$(TargetFramework)\%(_CssParser.Filename)%(_CssParser.Extension)" />
<AdditionalContent Include="@(_CssParser)" PackagePath="tasks\$(TargetFramework)" />
</ItemGroup>
<Copy SourceFiles="@(_CssParserContent)"
DestinationFiles="@(_CssParserContent->'$(PackageLayoutOutputPath)%(TargetPath)')"
SkipUnchangedFiles="true">
<Output TaskParameter="DestinationFiles" ItemName="FileWrites" />
</Copy>
</Target>
<Target Name="PrepareAdditionalFilesToLayout" BeforeTargets="AssignTargetPaths">
<ItemGroup>
<LayoutFile Include="@(AdditionalContent)"
Condition="'%(AdditionalContent.PackagePath)' != '' and '%(AdditionalContent.PackagePath)' != 'Icon.png'"
TargetPath="%(AdditionalContent.PackagePath)\%(AdditionalContent.RecursiveDir)%(AdditionalContent.Filename)%(AdditionalContent.Extension)" />
</ItemGroup>
</Target>
<Target Name="CopyAdditionalFilesToLayout"
DependsOnTargets="PrepareAdditionalFilesToLayout"
AfterTargets="Build"
Inputs="@(LayoutFile)"
Outputs="@(LayoutFile->'$(PackageLayoutOutputPath)%(TargetPath)')">
<Copy SourceFiles="@(LayoutFile)" DestinationFiles="@(LayoutFile->'$(PackageLayoutOutputPath)%(TargetPath)')">
<Output TaskParameter="DestinationFiles" ItemName="FileWrites" />
</Copy>
</Target>
<Target Name="PackLayout"
DependsOnTargets="CopyAdditionalFilesToLayout"
BeforeTargets="$(GenerateNuspecDependsOn)">
<Message Importance="high" Text="Packing assets at $(PackageLayoutOutputPath)" />
<ItemGroup>
<Content Include="$(PackageLayoutOutputPath)**\*" PackagePath="\" />
</ItemGroup>
</Target>
<!-- Global usings -->
<!-- See: path_to_url#using -->
<ItemGroup>
<!-- This causes conflicts with System.Threading.Tasks.Task. Giving it an alias to avoid the conflict. -->
<Using Include="Microsoft.Build.Utilities.Task" Alias="Task" />
</ItemGroup>
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
</Project>
``` | /content/code_sandbox/src/StaticWebAssetsSdk/Tasks/Microsoft.NET.Sdk.StaticWebAssets.Tasks.csproj | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 1,392 |
```xml
import { Directive } from '@angular2/core';
/**
* @internal
*/
@Directive({ selector: '[app-foo]' })
export class FooDirective {}
``` | /content/code_sandbox/test/fixtures/sample-files/foo.directive.ts | xml | 2016-10-17T07:09:28 | 2024-08-14T16:30:10 | compodoc | compodoc/compodoc | 3,980 | 33 |
```xml
import type { RxMigrationState } from './plugins/migration-schema/index.ts';
import { DocumentCache } from './doc-cache.ts';
import { QueryCache } from './query-cache.ts';
import { ChangeEventBuffer } from './change-event-buffer.ts';
import { Subscription, Observable } from 'rxjs';
import type { KeyFunctionMap, RxCollection, RxDatabase, RxQuery, RxDocument, RxDumpCollection, RxDumpCollectionAny, MangoQuery, MangoQueryNoLimit, RxCacheReplacementPolicy, RxStorageWriteError, RxChangeEvent, RxChangeEventInsert, RxChangeEventUpdate, RxChangeEventDelete, RxStorageInstance, CollectionsOfDatabase, RxConflictHandler, MaybePromise, CRDTEntry, MangoQuerySelectorAndIndex, MigrationStrategies } from './types/index.d.ts';
import { RxSchema } from './rx-schema.ts';
import { WrappedRxStorageInstance } from './rx-storage-helper.ts';
import { IncrementalWriteQueue } from './incremental-write.ts';
import type { RxPipeline, RxPipelineOptions } from './plugins/pipeline/index.ts';
declare const HOOKS_WHEN: readonly ["pre", "post"];
type HookWhenType = typeof HOOKS_WHEN[number];
declare const HOOKS_KEYS: readonly ["insert", "save", "remove", "create"];
type HookKeyType = typeof HOOKS_KEYS[number];
export declare class RxCollectionBase<InstanceCreationOptions, RxDocumentType = {
[prop: string]: any;
}, OrmMethods = {}, StaticMethods = {
[key: string]: any;
}, Reactivity = any> {
database: RxDatabase<CollectionsOfDatabase, any, InstanceCreationOptions, Reactivity>;
name: string;
schema: RxSchema<RxDocumentType>;
internalStorageInstance: RxStorageInstance<RxDocumentType, any, InstanceCreationOptions>;
instanceCreationOptions: InstanceCreationOptions;
migrationStrategies: MigrationStrategies;
methods: KeyFunctionMap;
attachments: KeyFunctionMap;
options: any;
cacheReplacementPolicy: RxCacheReplacementPolicy;
statics: KeyFunctionMap;
conflictHandler: RxConflictHandler<RxDocumentType>;
/**
* Stores all 'normal' documents
*/
storageInstance: WrappedRxStorageInstance<RxDocumentType, any, InstanceCreationOptions>;
readonly timeouts: Set<ReturnType<typeof setTimeout>>;
incrementalWriteQueue: IncrementalWriteQueue<RxDocumentType>;
/**
* Before reads, all these methods are awaited. Used to "block" reads
* depending on other processes, like when the RxPipeline is running.
*/
readonly awaitBeforeReads: Set<() => MaybePromise<any>>;
constructor(database: RxDatabase<CollectionsOfDatabase, any, InstanceCreationOptions, Reactivity>, name: string, schema: RxSchema<RxDocumentType>, internalStorageInstance: RxStorageInstance<RxDocumentType, any, InstanceCreationOptions>, instanceCreationOptions?: InstanceCreationOptions, migrationStrategies?: MigrationStrategies, methods?: KeyFunctionMap, attachments?: KeyFunctionMap, options?: any, cacheReplacementPolicy?: RxCacheReplacementPolicy, statics?: KeyFunctionMap, conflictHandler?: RxConflictHandler<RxDocumentType>);
get insert$(): Observable<RxChangeEventInsert<RxDocumentType>>;
get update$(): Observable<RxChangeEventUpdate<RxDocumentType>>;
get remove$(): Observable<RxChangeEventDelete<RxDocumentType>>;
_incrementalUpsertQueues: Map<string, Promise<any>>;
synced: boolean;
hooks: {
[key in HookKeyType]: {
[when in HookWhenType]: {
series: Function[];
parallel: Function[];
};
};
};
_subs: Subscription[];
_docCache: DocumentCache<RxDocumentType, OrmMethods>;
_queryCache: QueryCache;
$: Observable<RxChangeEvent<RxDocumentType>>;
checkpoint$: Observable<any>;
_changeEventBuffer: ChangeEventBuffer<RxDocumentType>;
/**
* When the collection is destroyed,
* these functions will be called an awaited.
* Used to automatically clean up stuff that
* belongs to this collection.
*/
onDestroy: (() => MaybePromise<any>)[];
destroyed: boolean;
onRemove: (() => MaybePromise<any>)[];
prepare(): Promise<void>;
/**
* Manually call the cleanup function of the storage.
* @link path_to_url
*/
cleanup(_minimumDeletedTime?: number): Promise<boolean>;
migrationNeeded(): Promise<boolean>;
getMigrationState(): RxMigrationState;
startMigration(batchSize?: number): Promise<void>;
migratePromise(batchSize?: number): Promise<any>;
insert(json: RxDocumentType | RxDocument): Promise<RxDocument<RxDocumentType, OrmMethods>>;
bulkInsert(docsData: RxDocumentType[]): Promise<{
success: RxDocument<RxDocumentType, OrmMethods>[];
error: RxStorageWriteError<RxDocumentType>[];
}>;
bulkRemove(ids: string[]): Promise<{
success: RxDocument<RxDocumentType, OrmMethods>[];
error: RxStorageWriteError<RxDocumentType>[];
}>;
/**
* same as bulkInsert but overwrites existing document with same primary
*/
bulkUpsert(docsData: Partial<RxDocumentType>[]): Promise<{
success: RxDocument<RxDocumentType, OrmMethods>[];
error: RxStorageWriteError<RxDocumentType>[];
}>;
/**
* same as insert but overwrites existing document with same primary
*/
upsert(json: Partial<RxDocumentType>): Promise<RxDocument<RxDocumentType, OrmMethods>>;
/**
* upserts to a RxDocument, uses incrementalModify if document already exists
*/
incrementalUpsert(json: Partial<RxDocumentType>): Promise<RxDocument<RxDocumentType, OrmMethods>>;
find(queryObj?: MangoQuery<RxDocumentType>): RxQuery<RxDocumentType, RxDocument<RxDocumentType, OrmMethods>[], OrmMethods, Reactivity>;
findOne(queryObj?: MangoQueryNoLimit<RxDocumentType> | string): RxQuery<RxDocumentType, RxDocument<RxDocumentType, OrmMethods> | null, OrmMethods, Reactivity>;
count(queryObj?: MangoQuerySelectorAndIndex<RxDocumentType>): RxQuery<RxDocumentType, number, OrmMethods, Reactivity>;
/**
* find a list documents by their primary key
* has way better performance then running multiple findOne() or a find() with a complex $or-selected
*/
findByIds(ids: string[]): RxQuery<RxDocumentType, Map<string, RxDocument<RxDocumentType, OrmMethods>>, OrmMethods, Reactivity>;
/**
* Export collection to a JSON friendly format.
*/
exportJSON(): Promise<RxDumpCollection<RxDocumentType>>;
exportJSON(): Promise<RxDumpCollectionAny<RxDocumentType>>;
/**
* Import the parsed JSON export into the collection.
* @param _exportedJSON The previously exported data from the `<collection>.exportJSON()` method.
*/
importJSON(_exportedJSON: RxDumpCollectionAny<RxDocumentType>): Promise<void>;
insertCRDT(_updateObj: CRDTEntry<any> | CRDTEntry<any>[]): RxDocument<RxDocumentType, OrmMethods>;
addPipeline(_options: RxPipelineOptions<RxDocumentType>): Promise<RxPipeline<RxDocumentType>>;
/**
* HOOKS
*/
addHook(when: HookWhenType, key: HookKeyType, fun: any, parallel?: boolean): void;
getHooks(when: HookWhenType, key: HookKeyType): {
series: Function[];
parallel: Function[];
};
hasHooks(when: HookWhenType, key: HookKeyType): boolean;
_runHooks(when: HookWhenType, key: HookKeyType, data: any, instance?: any): Promise<any>;
/**
* does the same as ._runHooks() but with non-async-functions
*/
_runHooksSync(when: HookWhenType, key: HookKeyType, data: any, instance: any): void;
/**
* Returns a promise that resolves after the given time.
* Ensures that is properly cleans up when the collection is destroyed
* so that no running timeouts prevent the exit of the JavaScript process.
*/
promiseWait(time: number): Promise<void>;
destroy(): Promise<boolean>;
/**
* remove all data of the collection
*/
remove(): Promise<any>;
get asRxCollection(): RxCollection<RxDocumentType, OrmMethods, StaticMethods, any, Reactivity>;
}
/**
* creates and prepares a new collection
*/
export declare function createRxCollection({ database, name, schema, instanceCreationOptions, migrationStrategies, autoMigrate, statics, methods, attachments, options, localDocuments, cacheReplacementPolicy, conflictHandler }: any): Promise<RxCollection>;
export declare function isRxCollection(obj: any): boolean;
export {};
``` | /content/code_sandbox/dist/types/rx-collection.d.ts | xml | 2016-12-02T19:34:42 | 2024-08-16T15:47:20 | rxdb | pubkey/rxdb | 21,054 | 1,915 |
```xml
import { useEffect, useMemo } from 'react';
import { c } from 'ttag';
import { useNotifications } from '@proton/components';
import { useLoading } from '@proton/hooks';
import { SORT_DIRECTION } from '@proton/shared/lib/constants';
import { sendErrorReport } from '../../utils/errorHandling';
import { useLinksListing } from '../_links';
import { useSearchResults } from '../_search';
import { useUserSettings } from '../_settings';
import { useAbortSignal, useMemoArrayNoMatterTheOrder, useSorting, useSortingWithDefault } from './utils';
import type { SortField } from './utils/useSorting';
const DEFAULT_SORT = {
sortField: 'name' as SortField,
sortOrder: SORT_DIRECTION.ASC,
};
/**
* useSearchView provides data for search view (file browser of search results).
*
* At this moment, we show only fully loaded results, that means results are
* picked up from cache and fetched from API if they are missing. But because
* we have quite enough data in index database, we could show and sort results
* right away. Probably the best way would be to allow paging over search
* results so we dont have to load everything if not needed; that way we could
* fetch data from API only for the pages which user scrolled to. The issue is,
* modify date, sharing info, or thumbnail is not available and we would need
* some clever placeholder in the UI. We don't know for now how to tackle this
* in general (it is needed also on shared links page), therefore we start with
* simple algorithm and we improve in the future.
*/
export default function useSearchView(shareId: string, query: string) {
const { createNotification } = useNotifications();
const { layout } = useUserSettings();
const { runSearch, dbExists, isSearching, results } = useSearchResults();
const cachedResults = useMemoArrayNoMatterTheOrder(results);
const searchResults = useMemo(() => {
return cachedResults.map((esLink) => ({
linkId: esLink.linkId,
isFile: esLink.MIMEType !== 'Folder',
name: esLink.decryptedName,
mimeType: esLink.MIMEType,
size: esLink.size,
metaDataModifyTime: esLink.modifiedTime,
// These fields are not kept in index db, but its fine that its not
// possible to sort by them, we need load for now everything anyway.
fileModifyTime: esLink.modifiedTime,
trashed: null,
}));
}, [cachedResults]);
const {
sortedList: sortedSearchResults,
sortParams,
setSorting,
} = useSortingWithDefault(searchResults, DEFAULT_SORT);
const sortedSearchResultIds = useMemo(() => {
return sortedSearchResults.map(({ linkId }) => linkId);
}, [sortedSearchResults]);
const abortSignal = useAbortSignal([shareId, query]);
const linksListing = useLinksListing();
const { links, isDecrypting } = linksListing.getCachedLinks(abortSignal, query, shareId, sortedSearchResultIds);
const cachedLinks = useMemoArrayNoMatterTheOrder(links);
// For now we don't show trashed items in search results. We index them
// so we are free to experiemnt with showing them without need to re-index
// the whole db every time. But trashed items don't have the same options
// in toolbar or context menu, which could be confusing.
const cachedLinksWithoutTrashedItems = useMemo(() => {
return cachedLinks.filter(({ trashed }) => !trashed);
}, [cachedLinks]);
const sortedLinks = useSorting(cachedLinksWithoutTrashedItems, sortParams);
const [isFetchLoading, withLoading] = useLoading(true);
useEffect(() => {
// Wait till database is indexed and loaded. If db does not exist
// yet and runSearch is called, no results is returned and it will
// not be automatically updated.
if (!dbExists) {
return;
}
runSearch(query).catch((err) => {
createNotification({
type: 'error',
text: c('Error').t`Search failed`,
});
sendErrorReport(err);
});
}, [dbExists, query]);
// Load links using sorted search results so we load items in the best
// possible order.
useEffect(() => {
const ac = new AbortController();
void withLoading(linksListing.loadLinksMeta(ac.signal, query, shareId, sortedSearchResultIds)).catch(
sendErrorReport
);
return () => {
ac.abort();
};
}, [shareId, query, sortedSearchResultIds]);
return {
layout,
numberOfResults: sortedLinks.length,
items: sortedLinks,
sortParams,
setSorting,
isLoading: isSearching || isFetchLoading || isDecrypting,
};
}
``` | /content/code_sandbox/applications/drive/src/app/store/_views/useSearchView.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,064 |
```xml
import { Component } from '@angular/core';
import { FieldBaseComponent } from '../field-base';
@Component({
selector: 'app-form-file-path',
styleUrls: ['form-file-path.component.scss'],
templateUrl: 'form-file-path.component.html',
})
export class FormFilePathComponent extends FieldBaseComponent {}
``` | /content/code_sandbox/src/Presentation/Web/ClientApp/src/app/shared/components/forms/components/form-file-path/form-file-path.component.ts | xml | 2016-06-03T17:49:56 | 2024-08-14T02:53:24 | AspNetCoreSpa | fullstackproltd/AspNetCoreSpa | 1,472 | 63 |
```xml
<manifest xmlns:android="path_to_url"
package="com.view.jameson.library">
<application android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true"
>
</application>
</manifest>
``` | /content/code_sandbox/library/src/main/AndroidManifest.xml | xml | 2016-09-01T06:43:09 | 2024-08-15T11:25:56 | RecyclerViewCardGallery | huazhiyuan2008/RecyclerViewCardGallery | 2,629 | 58 |
```xml
/**
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import * as Code from '../code';
import * as Error from '../error';
import * as FileWriter from '../file-writer';
import * as IGListDiffableUtils from './iglistdiffable-utils';
import * as Maybe from '../maybe';
import * as ObjC from '../objc';
import * as ObjectSpec from '../object-spec';
function diffIdentiferAttributeFilter(
attribute: ObjectSpec.Attribute,
index,
array,
): boolean {
return attribute.annotations['diffIdentifier'] != null;
}
function diffIdentifierMethodImplementation(
objectType: ObjectSpec.Type,
): string[] {
const diffIdentifierAttributes: ObjectSpec.Attribute[] = objectType.attributes.filter(
diffIdentiferAttributeFilter,
);
if (diffIdentifierAttributes.length > 0) {
// use first marked attribute as identifier, if available
return [
'return ' +
IGListDiffableUtils.objectValueForAttribute(
diffIdentifierAttributes[0],
) +
';',
];
} else {
// fallback/default to self
return ['return self;'];
}
}
function diffIdentifierMethod(objectType: ObjectSpec.Type): ObjC.Method {
return {
preprocessors: [],
belongsToProtocol: Maybe.Just<string>('IGListDiffable'),
code: diffIdentifierMethodImplementation(objectType),
comments: [],
compilerAttributes: [],
keywords: [
{
name: 'diffIdentifier',
argument: Maybe.Nothing<ObjC.KeywordArgument>(),
},
],
returnType: {
type: Maybe.Just({
name: 'NSObject',
reference: 'id<NSObject>',
}),
modifiers: [],
},
};
}
export function createPlugin(): ObjectSpec.Plugin {
return {
additionalFiles: function(objectType: ObjectSpec.Type): Code.File[] {
return [];
},
transformBaseFile: function(
objectType: ObjectSpec.Type,
baseFile: Code.File,
): Code.File {
return baseFile;
},
additionalTypes: function(objectType: ObjectSpec.Type): ObjectSpec.Type[] {
return [];
},
attributes: function(objectType: ObjectSpec.Type): ObjectSpec.Attribute[] {
return [];
},
classMethods: function(objectType: ObjectSpec.Type): ObjC.Method[] {
return [];
},
transformFileRequest: function(
request: FileWriter.Request,
): FileWriter.Request {
return request;
},
fileType: function(
objectType: ObjectSpec.Type,
): Maybe.Maybe<Code.FileType> {
return Maybe.Nothing<Code.FileType>();
},
forwardDeclarations: function(
objectType: ObjectSpec.Type,
): ObjC.ForwardDeclaration[] {
return [];
},
functions: function(objectType: ObjectSpec.Type): ObjC.Function[] {
return [];
},
headerComments: function(objectType: ObjectSpec.Type): ObjC.Comment[] {
return [];
},
implementedProtocols: function(
objectType: ObjectSpec.Type,
): ObjC.Protocol[] {
return [{name: 'IGListDiffable'}];
},
imports: function(objectType: ObjectSpec.Type): ObjC.Import[] {
return [
{
file: 'IGListDiffable.h',
isPublic: true,
requiresCPlusPlus: false,
library: Maybe.Just('IGListKit'),
},
];
},
instanceMethods: function(objectType: ObjectSpec.Type): ObjC.Method[] {
return [
IGListDiffableUtils.isEqualToDiffableObjectMethod(),
diffIdentifierMethod(objectType),
];
},
macros: function(valueType: ObjectSpec.Type): ObjC.Macro[] {
return [];
},
properties: function(objectType: ObjectSpec.Type): ObjC.Property[] {
return [];
},
requiredIncludesToRun: ['IGListDiffable'],
staticConstants: function(objectType: ObjectSpec.Type): ObjC.Constant[] {
return [];
},
validationErrors: function(objectType: ObjectSpec.Type): Error.Error[] {
return [];
},
nullability: function(
objectType: ObjectSpec.Type,
): Maybe.Maybe<ObjC.ClassNullability> {
return Maybe.Nothing<ObjC.ClassNullability>();
},
subclassingRestricted: function(objectType: ObjectSpec.Type): boolean {
return false;
},
};
}
``` | /content/code_sandbox/remodel-plugin/src/plugins/iglistdiffable.ts | xml | 2016-09-07T08:39:27 | 2024-08-16T09:53:38 | IGListKit | Instagram/IGListKit | 12,842 | 937 |
```xml
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<dataset update-count="1">
<metadata data-nodes="encrypt.t_user">
<column name="user_id" type="numeric" />
<column name="user_name_cipher" type="varchar" />
<column name="user_name_like" type="varchar" />
<column name="password_cipher" type="varchar" />
<column name="email_cipher" type="varchar" />
<column name="user_telephone_cipher" type="varchar" />
<column name="user_telephone_like" type="varchar" />
<column name="creation_date" type="datetime" />
</metadata>
<row data-node="encrypt.t_user" values="11, fQ7IzBxKVuNHtUF6h6WSBg==, mhth, wuhmEKgdgrWQYt+Ev0hgGA==, svATu3uWv9KfiloWJeWx3A==, 0kDFxndQdzauFwL/wyCsNQ==, 01454589810, 2017-08-08" />
<row data-node="encrypt.t_user" values="12, AQRWSlufQPog/b64YRhu6Q==, x`mhxt, x7A+2jq9B6DSOSFtSOibdA==, nHJv9e6NiClIuGHOjHLvCAq2ZLhWcqfQ8/EQnIqMx+g=, a/SzSJLapt5iBXvF2c9ycw==, 01454589811, 2017-08-08" />
<row data-node="encrypt.t_user" values="13, 5NqS4YvpT+mHBFqZOZ3QDA==, yi`pmht, zi6b4xYRjjV+bBk2R4wB+w==, MLBZczLjriUXvg3aM5QPTxMJbLjNh8yeNrSNBek/VTw=, b6VVhG+F6ujG8IMUZJAIFg==, 01454589814, 2017-08-08" />
<row data-node="encrypt.t_user" values="14, qeIY9od3u1KwhjihzLQUTQ==, yitph, 51UmlLAC+tUvdOAj8CjWfQ==, JCmeNdPyrKO5BW5zvhAA+g==, f995xinpZdKMVU5J5/yv3w==, 01454589815, 2017-08-08" />
<row data-node="encrypt.t_user" values="15, VbNUtguwtpeGhHGnPJ3aXg==, mha`, +3/5CVbqoKhg3sqznKTFFQ==, T+X+e3Q3+ZNIXXmg/80uxg==, GETj+S6DrO042E7NuBXLBQ==, 01454589814, 2017-08-08" />
<row data-node="encrypt.t_user" values="16, U0/Ao/w1u7L5avR3fAH2Og==, x`mhiht, jFfFMYxv02DjaFRuAoCDGw==, RNW/KRq5HeL2YTfAdXSyARMJbLjNh8yeNrSNBek/VTw=, +lbvjJwO7VO4HUKc0Mw0NA==, 01454589815, 2017-08-08" />
<row data-node="encrypt.t_user" values="17, zb1sgBigoMi7JPSoY4bAVw==, yite`, VFIjocgjujJCJc6waWXqJA==, 1vF/ET3nBxt7T7vVfAndZQ==, wFvs5BH6OikgveBeTEBwsQ==, 01454589818, 2017-08-08" />
<row data-node="encrypt.t_user" values="18, rJzNIrFEnx296kW+N1YmMw==, ttmdq, LaODSKGyR7vZ1IvmBOe9vA==, 5u4GIQkJsWRmnJHWaHNSjg==, uwqm2O1Lv2tNTraJX1ym7Q==, 01454589819, 2017-08-08" />
<row data-node="encrypt.t_user" values="19, qHwpQ9kteL8VX6iTUhNdbQ==, yiptt`m, MyOShk4kjRnds7CZfU5NCw==, HmYCo7QBfJ2E0EvaGHBCOBMJbLjNh8yeNrSNBek/VTw=, YLNQuuUPMGA21nhKWPzzsg==, 01454589818, 2017-08-08" />
<row data-node="encrypt.t_user" values="20, qCCmvf7OWRxbVbtLb0az1g==, upl, fzdTMkzpBvgNYmKSQAp8Fg==, gOoP4Mf0P4ISOJp6A4sRmg==, l4xa4HwOfs/jusoJon9Wzw==, 01454589801, 2017-08-08" />
<row data-node="encrypt.t_user" values="21, IYJ1COaRQ0gSjWMC/UAeMg==, lpad, 1uEDMeYh2jstbOf6kx/cqw==, tikMAFiQ37u2VgWqUT38Eg==, rGpr30UXfczXjCjdvPN+BA==, 01454589800, 2017-08-08" />
<row data-node="encrypt.t_user" values="22, 7wvZZ7NVHgk6m1vB/sTC1Q==, idqqx, OirN3gvz9uBnrq88nfa1wQ==, T7K/Uz1O2m+3xvB0+c4nGQ==, 7+fCU+VbQZKgLJXZPTTegA==, 01454589801, 2017-08-08" />
<row data-node="encrypt.t_user" values="23, SbVQWl8JbnxflCfGJ7KZdA==, i`ldt, hWVVYdkdTUTgm08haeq+tw==, Uk3ju6GteCD1qEHns5ZhKA==, DpnV86FZefwBRmIAVBh2gg==, 01454589804, 2017-08-08" />
<row data-node="encrypt.t_user" values="24, fx7OfSAYqVpjNa7LoKhXvw==, x`ed, N2W9ijAXNkBxhkvJiIwp0A==, lAAGItVLmb1H69++1MDrIA==, QrE62wAb8B+2cEPcs4Lm1Q==, 01454589805, 2017-08-08" />
<row data-node="encrypt.t_user" values="25, wH3/LdWShD9aCb8eCIm3Tg==, qptd, GDixtt6NzPOVv6H0dmov5g==, T1yfJSyVxumZUfkDnmUQxA==, iU+AsGczboCRfU+Zr7mcpw==, 01454589804, 2017-08-08" />
<row data-node="encrypt.t_user" values="26, GgJQTndbxyBZ2tECS8SmqQ==, apti, gLgVFLFIyyKwdQCXaw78Ag==, O+JIn9XZ3yq6RnKElHuqlA==, kwYlbu9aF7ndvMTcj8QBSg==, 01454589805, 2017-08-08" />
<row data-node="encrypt.t_user" values="27, lv8w8g32kuTXNvSUUypOig==, i`dl, 8i0YH2mn6kXSyvBjM5p+Yg==, gqRoJF5S66SvBalc2RCo1A==, 2ob/3UYqRsZA5VdScnaWxQ==, 01454589808, 2017-08-08" />
<row data-node="encrypt.t_user" values="28, P9YCbFvWCIhcS99KyKH2zA==, ipqe`m, PRrI4z4FrWwLvcHPx9g4og==, y8q31Jj4PFSyZHiLVIxKEQq2ZLhWcqfQ8/EQnIqMx+g=, kDF2za26uOerlNYWYHRT2Q==, 01454589809, 2017-08-08" />
<row data-node="encrypt.t_user" values="29, 5wu9XvlJAVtjKijhxt6SQQ==, itmhd, O4pgkLgz34N+C4bIUOQVnA==, UH7ihg16J61Np/EYMQnXIA==, z2hbJQD4dRkVVITNxAac5Q==, 01454589808, 2017-08-08" />
<row data-node="encrypt.t_user" values="30, i50fpEe3j0VOy/Hbfmr5Bg==, , MyOShk4kjRnds7CZfU5NCw==, WM0fHOH91JNWnHTkiqBdyNmzk4uJ7CCz4mB1va9Ya1M=, uRbQGcAhuXmxdIzRsgiy8g==, 09101401454, 2017-08-08" />
<row data-node="encrypt.t_user" values="31, wLXX1Gs7zl0PkyJRMIxmCQ==, , fzdTMkzpBvgNYmKSQAp8Fg==, cq1LN85LmWHrEtS4gN/ac9mzk4uJ7CCz4mB1va9Ya1M=, jDL+p5OyKQXfQ4H8JpNKJQ==, 09101401454, 2017-08-08" />
<row data-node="encrypt.t_user" values="32, 5NNYIZCq4Dxab0uKWXt93A==, , 1uEDMeYh2jstbOf6kx/cqw==, rehTd++DbFy3qYqeDJUjRRMJbLjNh8yeNrSNBek/VTw=, 60fpnMdKCWeyKzxkdthn2Q==, 09101401454, 2017-08-08" />
<row data-node="encrypt.t_user" values="33, 8kgeyqYaHUMq6di5BVt3Ow==, , OirN3gvz9uBnrq88nfa1wQ==, svATu3uWv9KfiloWJeWx3A==, 60fpnMdKCWeyKzxkdthn2Q==, 09101401454, 2017-08-08" />
<row data-node="encrypt.t_user" values="34, THN1NIcHrqnfvPKR92lAKw==, , ZSU1lmpj8cugQHD59QxPhQ==, KtMacpLCtRTSl+VeCPYrPwq2ZLhWcqfQ8/EQnIqMx+g=, 60fpnMdKCWeyKzxkdthn2Q==, 09101401454, 2017-08-08" />
<row data-node="encrypt.t_user" values="35, R3tsv8yeGKXz7WXLYfjkPA==, , 31jh3gwg1fgDFnd6iYxU+Q==, ZsrMzd0mjJ9H3fxe4UNVfQsU49iKH47f2rb+/uKuo9M=, 60fpnMdKCWeyKzxkdthn2Q==, 09101401454, 2017-08-08" />
<row data-node="encrypt.t_user" values="36, M2hIFm7Z/s4zGd+rPD1USA==, , bO/8ha1eS/H8/3DugjdOAQ==, PyO5yO0W8v5cpLPhqASTHA==, 60fpnMdKCWeyKzxkdthn2Q==, 09101401454, 2017-08-08" />
<row data-node="encrypt.t_user" values="37, aXS0VfnqHIAnOAtDjsF/9Q==, , bO/8ha1eS/H8/3DugjdOAQ==, fwyOxfHtLxNuSCFmghYiY0qMsgbpjg5UIo3xmJOLGu0=, 60fpnMdKCWeyKzxkdthn2Q==, 09101401454, 2017-08-08" />
<row data-node="encrypt.t_user" values="38, 59/68izQEdnwNSueX1lPAA==, , ilD/Tk7DUG4+EuznS1bNLg==, 2emhAeiXPr0kHbFrhYlM1dmzk4uJ7CCz4mB1va9Ya1M=, 60fpnMdKCWeyKzxkdthn2Q==, 09101401454, 2017-08-08" />
<row data-node="encrypt.t_user" values="39, fn9LnNltUAOWO0F0iy0+Jw==, , qe/WdUiSPP1RAsSSuejGJw==, zx2omwIbXHpEJeh8ta7HqQq2ZLhWcqfQ8/EQnIqMx+g=, 60fpnMdKCWeyKzxkdthn2Q==, 09101401454, 2017-08-08" />
</dataset>
``` | /content/code_sandbox/test/e2e/sql/src/test/resources/cases/dml/dataset/encrypt/delete_user_table.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 3,463 |
```xml
export * from './Dropdown';
export * from './Dropdown.base';
export * from './Dropdown.types';
``` | /content/code_sandbox/packages/react/src/components/Dropdown/index.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 21 |
```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 { CloudFunction, EventContext, makeCloudFunction } from "../cloud-functions";
import { DeploymentOptions, ScheduleRetryConfig } from "../function-configuration";
/** @internal */
export const provider = "google.pubsub";
/** @internal */
export const service = "pubsub.googleapis.com";
/**
* Registers a Cloud Function triggered when a Google Cloud Pub/Sub message
* is sent to a specified topic.
*
* @param topic - The Pub/Sub topic to watch for message events.
* @returns Pub/Sub topic builder interface.
*/
export function topic(topic: string) {
return _topicWithOptions(topic, {});
}
/** @internal */
export function _topicWithOptions(topic: string, options: DeploymentOptions): TopicBuilder {
if (topic.indexOf("/") !== -1) {
throw new Error("Topic name may not have a /");
}
return new TopicBuilder(() => {
if (!process.env.GCLOUD_PROJECT) {
throw new Error("process.env.GCLOUD_PROJECT is not set.");
}
return `projects/${process.env.GCLOUD_PROJECT}/topics/${topic}`;
}, options);
}
/**
* The Google Cloud Pub/Sub topic builder.
*
* Access via `functions.pubsub.topic()`.
*/
export class TopicBuilder {
/** @hidden */
constructor(private triggerResource: () => string, private options: DeploymentOptions) {}
/**
* Event handler that fires every time a Cloud Pub/Sub message is
* published.
*
* @param handler - Event handler that runs every time a Cloud Pub/Sub message
* is published.
* @returns A function that you can export and deploy.
*/
onPublish(
handler: (message: Message, context: EventContext) => PromiseLike<any> | any
): CloudFunction<Message> {
return makeCloudFunction({
handler,
provider,
service,
triggerResource: this.triggerResource,
eventType: "topic.publish",
dataConstructor: (raw) => new Message(raw.data),
options: this.options,
});
}
}
/**
* Registers a Cloud Function to run at specified times.
*
* @param schedule - The schedule, in Unix Crontab or AppEngine syntax.
* @returns ScheduleBuilder interface.
*/
export function schedule(schedule: string): ScheduleBuilder {
return _scheduleWithOptions(schedule, {});
}
/** @internal */
export function _scheduleWithOptions(
schedule: string,
options: DeploymentOptions
): ScheduleBuilder {
const triggerResource = () => {
if (!process.env.GCLOUD_PROJECT) {
throw new Error("process.env.GCLOUD_PROJECT is not set.");
}
// The CLI will append the correct topic name based on region and function name
return `projects/${process.env.GCLOUD_PROJECT}/topics`;
};
return new ScheduleBuilder(triggerResource, {
...options,
schedule: { schedule },
});
}
/**
* The builder for scheduled functions, which are powered by
* Google Pub/Sub and Cloud Scheduler. Describes the Cloud Scheduler
* job that is deployed to trigger a scheduled function at the provided
* frequency. For more information, see
* [Schedule functions](/docs/functions/schedule-functions).
*
* Access via `functions.pubsub.schedule()`.
*/
export class ScheduleBuilder {
/** @hidden */
constructor(private triggerResource: () => string, private options: DeploymentOptions) {}
retryConfig(config: ScheduleRetryConfig): ScheduleBuilder {
this.options.schedule.retryConfig = config;
return this;
}
timeZone(timeZone: string): ScheduleBuilder {
this.options.schedule.timeZone = timeZone;
return this;
}
/**
* Event handler for scheduled functions. Triggered whenever the associated
* scheduler job sends a Pub/Sub message.
*
* @param handler - Handler that fires whenever the associated
* scheduler job sends a Pub/Sub message.
* @returns A function that you can export and deploy.
*/
onRun(handler: (context: EventContext) => PromiseLike<any> | any) {
const cloudFunction = makeCloudFunction({
contextOnlyHandler: handler,
provider,
service,
triggerResource: this.triggerResource,
eventType: "topic.publish",
options: this.options,
labels: { "deployment-scheduled": "true" },
});
return cloudFunction;
}
}
/**
* Interface representing a Google Cloud Pub/Sub message.
*
* @param data - Payload of a Pub/Sub message.
*/
export class Message {
/**
* The data payload of this message object as a base64-encoded string.
*/
readonly data: string;
/**
* User-defined attributes published with the message, if any.
*/
readonly attributes: { [key: string]: string };
/** @hidden */
private _json: any;
constructor(data: any) {
[this.data, this.attributes, this._json] = [data.data, data.attributes || {}, data.json];
}
/**
* The JSON data payload of this message object, if any.
*/
get json(): any {
if (typeof this._json === "undefined") {
this._json = JSON.parse(Buffer.from(this.data, "base64").toString("utf8"));
}
return this._json;
}
/**
* Returns a JSON-serializable representation of this object.
*
* @returns A JSON-serializable representation of this object.
*/
toJSON(): any {
return {
data: this.data,
attributes: this.attributes,
};
}
}
``` | /content/code_sandbox/src/v1/providers/pubsub.ts | xml | 2016-09-22T23:13:54 | 2024-08-16T17:59:09 | firebase-functions | firebase/firebase-functions | 1,015 | 1,382 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Description>Azure providers for Workflow Core
- Provides distributed lock management on Workflow Core
- Provides Queueing support on Workflow Core</Description>
<PackageTags>workflow workflowcore dlm</PackageTags>
<PackageTargetFallback Condition=" '$(TargetFramework)' == 'netstandard1.3' ">$(PackageTargetFallback);dnxcore50</PackageTargetFallback>
<PackageProjectUrl>path_to_url
<RepositoryType>git</RepositoryType>
<RepositoryUrl>path_to_url
<Authors>Daniel Gerlag</Authors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.19.0" />
<PackageReference Include="Microsoft.Azure.DocumentDB" Version="2.11.6" />
<PackageReference Include="Microsoft.Azure.ServiceBus" Version="5.0.0" />
<PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\WorkflowCore\WorkflowCore.csproj" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/src/providers/WorkflowCore.Providers.Azure/WorkflowCore.Providers.Azure.csproj | xml | 2016-11-15T23:32:24 | 2024-08-16T06:12:22 | workflow-core | danielgerlag/workflow-core | 5,247 | 272 |
```xml
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { join } from 'path'
import webdriver from 'next-webdriver'
const mockedGoogleFontResponses = require.resolve(
'./google-font-mocked-responses.js'
)
describe('next/font/google fetch error', () => {
const isDev = (global as any).isNextDev
let next: NextInstance
if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {})
return
}
beforeAll(async () => {
next = await createNext({
files: {
pages: new FileRef(join(__dirname, 'google-fetch-error/pages')),
},
env: {
NEXT_FONT_GOOGLE_MOCKED_RESPONSES: mockedGoogleFontResponses,
},
skipStart: true,
})
})
afterAll(() => next.destroy())
if (isDev) {
it('should use a fallback font in dev', async () => {
await next.start()
const outputIndex = next.cliOutput.length
const browser = await webdriver(next.url, '/')
const ascentOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Inter Fallback")).ascentOverride'
)
expect(ascentOverride).toBe('90.49%')
const descentOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Inter Fallback")).descentOverride'
)
expect(descentOverride).toBe('22.56%')
const lineGapOverride = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Inter Fallback")).lineGapOverride'
)
expect(lineGapOverride).toBe('0%')
const sizeAdjust = await browser.eval(
'Array.from(document.fonts.values()).find(font => font.family.includes("Inter Fallback")).sizeAdjust'
)
expect(sizeAdjust).toBe('107.06%')
expect(next.cliOutput.slice(outputIndex)).toInclude(
'Failed to download `Inter` from Google Fonts. Using fallback font instead.'
)
})
} else {
it('should error when not in dev', async () => {
await expect(next.start()).rejects.toThrow('next build failed')
expect(next.cliOutput).toInclude(
'Failed to fetch `Inter` from Google Fonts.'
)
})
}
})
``` | /content/code_sandbox/test/e2e/next-font/google-fetch-error.test.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 533 |
```xml
import { CallStates } from '@storybook/instrumenter';
import type { Meta, StoryObj } from '@storybook/react';
import { expect, userEvent, within } from '@storybook/test';
import { getCalls } from '../mocks';
import { Interaction } from './Interaction';
import SubnavStories from './Subnav.stories';
type Story = StoryObj<typeof Interaction>;
export default {
title: 'Interaction',
component: Interaction,
args: {
callsById: new Map(getCalls(CallStates.DONE).map((call) => [call.id, call])),
controls: SubnavStories.args.controls,
controlStates: SubnavStories.args.controlStates,
},
} as Meta<typeof Interaction>;
export const Active: Story = {
args: {
call: getCalls(CallStates.ACTIVE).slice(-1)[0],
},
};
export const Waiting: Story = {
args: {
call: getCalls(CallStates.WAITING).slice(-1)[0],
},
};
export const Failed: Story = {
args: {
call: getCalls(CallStates.ERROR).slice(-1)[0],
},
};
export const Done: Story = {
args: {
call: getCalls(CallStates.DONE).slice(-1)[0],
},
};
export const WithParent: Story = {
args: {
call: { ...getCalls(CallStates.DONE).slice(-1)[0], ancestors: ['parent-id'] },
},
};
export const Disabled: Story = {
args: { ...Done.args, controlStates: { ...SubnavStories.args.controlStates, goto: false } },
};
export const Hovered: Story = {
...Done,
globals: { sb_theme: 'light' },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.hover(canvas.getByRole('button'));
await expect(canvas.getByTestId('icon-active')).toBeInTheDocument();
},
};
``` | /content/code_sandbox/code/addons/interactions/src/components/Interaction.stories.tsx | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 407 |
```xml
import { useAuth } from 'ice';
function CustomAuth({ children, authKey, fallback }) {
const [auth] = useAuth();
//
const hasAuth = auth[authKey];
//
if (hasAuth) {
return children;
} else {
// UI
return fallback || (<>No Auth</>);
}
}
export default CustomAuth;
``` | /content/code_sandbox/examples/with-auth/src/components/CustomAuth.tsx | xml | 2016-11-03T06:59:15 | 2024-08-16T10:11:29 | ice | alibaba/ice | 17,815 | 85 |
```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 `dvarmpn`.
*/
interface Routine {
/**
* Computes the variance of a double-precision floating-point strided array provided a known mean and using Neely's correction algorithm.
*
* @param N - number of indexed elements
* @param mean - mean
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @returns variance
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
*
* var v = dvarmpn( x.length, 1.0/3.0, 1, x, 1 );
* // returns ~4.3333
*/
( N: number, mean: number, correction: number, x: Float64Array, stride: number ): number;
/**
* Computes the variance of a double-precision floating-point strided array provided a known mean and using Neely's correction algorithm and alternative indexing semantics.
*
* @param N - number of indexed elements
* @param mean - mean
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @param offset - starting index
* @returns variance
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
*
* var v = dvarmpn.ndarray( x.length, 1.0/3.0, 1, x, 1, 0 );
* // returns ~4.3333
*/
ndarray( N: number, mean: number, correction: number, x: Float64Array, stride: number, offset: number ): number;
}
/**
* Computes the variance of a double-precision floating-point strided array provided a known mean and using Neely's correction algorithm.
*
* @param N - number of indexed elements
* @param mean - mean
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @returns variance
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
*
* var v = dvarmpn( x.length, 1.0/3.0, 1, x, 1 );
* // returns ~4.3333
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
*
* var v = dvarmpn.ndarray( x.length, 1.0/3.0, 1, x, 1, 0 );
* // returns ~4.3333
*/
declare var dvarmpn: Routine;
// EXPORTS //
export = dvarmpn;
``` | /content/code_sandbox/lib/node_modules/@stdlib/stats/base/dvarmpn/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 788 |
```xml
/*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import noColorLiteral from "./rules/no-color-literal";
import noPrefixLiteral from "./rules/no-prefix-literal";
export default [noPrefixLiteral, noColorLiteral];
``` | /content/code_sandbox/packages/stylelint-plugin/src/index.ts | xml | 2016-10-25T21:17:50 | 2024-08-16T15:14:48 | blueprint | palantir/blueprint | 20,593 | 74 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="path_to_url">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.20506</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<RootNamespace></RootNamespace>
<ProjectGuid>{767AF72C-BF6B-8F81-04D1-3C54BC2768B1}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<AssemblyName>Assembly-CSharp</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<BaseDirectory>Assets</BaseDirectory>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>Temp\bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;UNITY_5_2_1;UNITY_5_2;UNITY_5;ENABLE_NEW_BUGREPORTER;ENABLE_2D_PHYSICS;ENABLE_4_6_FEATURES;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_FRAME_DEBUGGER;ENABLE_GENERICS;ENABLE_HOME_SCREEN;ENABLE_IMAGEEFFECTS;ENABLE_LIGHT_PROBES_LEGACY;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_PLUGIN_INSPECTOR;ENABLE_SHADOWS;ENABLE_SINGLE_INSTANCE_BUILD_SETTING;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_RAKNET;ENABLE_UNET;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_METRICS;ENABLE_REFLECTION_BUFFERS;INCLUDE_DYNAMIC_GI;INCLUDE_GI;INCLUDE_IL2CPP;INCLUDE_DIRECTX12;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_LOCALIZATION;ENABLE_ANDROID_ATLAS_ETC1_COMPRESSION;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_TEXTUREID_MAP;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_LOG_MIXED_STACKTRACE;ENABLE_UNITYWEBREQUEST;ENABLE_EVENT_QUEUE;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;ENABLE_PROFILER;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_WIN</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>0169</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>Temp\bin\Release\</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoWarn>0169</NoWarn>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.XML" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="UnityEngine">
<HintPath>C:/Program Files/Unity/Editor/Data/Managed/UnityEngine.dll</HintPath>
</Reference>
<Reference Include="UnityEditor">
<HintPath>C:/Program Files/Unity/Editor/Data/Managed/UnityEditor.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Assets\Script\WebManager.cs" />
<Reference Include="UnityEngine.UI">
<HintPath>C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.Networking">
<HintPath>C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/Networking/UnityEngine.Networking.dll</HintPath>
</Reference>
<Reference Include="Mono.Cecil">
<HintPath>C:/Program Files/Unity/Editor/Data/Managed/Mono.Cecil.dll</HintPath>
</Reference>
<Reference Include="UnityEditor.iOS.Extensions.Xcode">
<HintPath>C:/Program Files/Unity/Editor/Data/PlaybackEngines/iOSSupport/UnityEditor.iOS.Extensions.Xcode.dll</HintPath>
</Reference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
``` | /content/code_sandbox/NetWorkAndResources/WebTest/Assembly-CSharp.csproj | xml | 2016-04-25T14:37:08 | 2024-08-16T09:19:37 | Unity3DTraining | XINCGer/Unity3DTraining | 7,368 | 1,140 |
```xml
/**
* Mocks/neovim/MockNeovimInstance.ts
*
* Implementations of test mocks and doubles,
* for Neovim facing classes / interfaces.
*/
import * as Utility from "./../../../src/Utility"
export interface NeovimRequest {
requestName: string
args: any[]
}
export class MockNeovimInstance {
private _requests: NeovimRequest[] = []
private _pendingPromises: Array<Utility.ICompletablePromise<any>> = []
public get onColorsChanged() {
return {
subscribe: (fn: (args?: any) => any) => fn(),
}
}
public request(requestName: string, args: any[]) {
this._requests.push({ requestName, args })
const promise = Utility.createCompletablePromise()
this._pendingPromises.push(promise)
return promise.promise
}
public getPendingRequests(): NeovimRequest[] {
return this._requests
}
public flushFirstRequest(val: any) {
const [firstPromise, ...remainingPromises] = this._pendingPromises
const [, ...remainingRequests] = this._requests
firstPromise.resolve(val)
this._pendingPromises = remainingPromises
this._requests = remainingRequests
}
public flushPendingRequests(): void {
this._pendingPromises.forEach(p => p.resolve())
this._requests = []
this._pendingPromises = []
}
}
``` | /content/code_sandbox/browser/test/Mocks/neovim/MockNeovimInstance.ts | xml | 2016-11-16T14:42:55 | 2024-08-14T11:48:05 | oni | onivim/oni | 11,355 | 312 |
```xml
import { HighContrastSelector } from './CommonStyles';
import { IsFocusVisibleClassName } from '@fluentui/utilities';
import { ZIndexes } from './zIndexes';
import type { IRawStyle } from '@fluentui/merge-styles';
import type { IGetFocusStylesOptions, ITheme } from '../interfaces/index';
/**
* Generates a focus style which can be used to define an :after focus border.
*
* @param theme - The theme object to use.
* @param options - Options to customize the focus border.
* @returns The style object.
*/
export function getFocusStyle(theme: ITheme, options?: IGetFocusStylesOptions): IRawStyle;
/**
* Generates a focus style which can be used to define an :after focus border.
*
* @param theme - The theme object to use.
* @param inset - The number of pixels to inset the border.
* @param position - The positioning applied to the container. Must
* be 'relative' or 'absolute' so that the focus border can live around it.
* @param highContrastStyle - Style for high contrast mode.
* @param borderColor - Color of the border.
* @param outlineColor - Color of the outline.
* @param isFocusedOnly - If the styles should apply on focus or not.
* @param borderRadius - If the style should include a rounded border.
* @returns The style object.
* @deprecated Use the object parameter version instead.
*/
export function getFocusStyle(
theme: ITheme,
inset?: number,
position?: 'relative' | 'absolute',
highContrastStyle?: IRawStyle | undefined,
borderColor?: string,
outlineColor?: string,
isFocusedOnly?: boolean,
borderRadius?: string | number | undefined,
): IRawStyle;
export function getFocusStyle(
theme: ITheme,
insetOrOptions?: number | IGetFocusStylesOptions,
position?: 'relative' | 'absolute',
highContrastStyle?: IRawStyle,
borderColor?: string,
outlineColor?: string,
isFocusedOnly?: boolean,
borderRadius?: string | number | undefined,
): IRawStyle {
if (typeof insetOrOptions === 'number' || !insetOrOptions) {
return _getFocusStyleInternal(theme, {
inset: insetOrOptions,
position,
highContrastStyle,
borderColor,
outlineColor,
isFocusedOnly,
borderRadius,
});
} else {
return _getFocusStyleInternal(theme, insetOrOptions);
}
}
function _getFocusStyleInternal(theme: ITheme, options: IGetFocusStylesOptions = {}): IRawStyle {
const {
borderRadius,
inset = 0,
width = 1,
position = 'relative',
highContrastStyle,
borderColor = theme.palette.white,
outlineColor = theme.palette.neutralSecondary,
isFocusedOnly = true,
pointerEvents,
} = options;
return {
// Clear browser-specific focus styles and use 'transparent' as placeholder for focus style.
outline: 'transparent',
// Requirement because pseudo-element is absolutely positioned.
position,
selectors: {
// Clear the focus border in Firefox.
// Reference: path_to_url
'::-moz-focus-inner': {
border: '0',
},
// When the element that uses this mixin is in a :focus state, add a pseudo-element to
// create a border.
[`.${IsFocusVisibleClassName} &${isFocusedOnly ? ':focus' : ''}:after, :host(.${IsFocusVisibleClassName}) &${
isFocusedOnly ? ':focus' : ''
}:after`]: {
content: '""',
position: 'absolute',
pointerEvents,
left: inset + 1,
top: inset + 1,
bottom: inset + 1,
right: inset + 1,
border: `${width}px solid ${borderColor}`,
outline: `${width}px solid ${outlineColor}`,
zIndex: ZIndexes.FocusStyle,
borderRadius,
selectors: {
[HighContrastSelector]: highContrastStyle,
},
},
},
};
}
/**
* Generates style to clear browser specific focus styles.
*/
export function focusClear(): IRawStyle {
return {
selectors: {
'&::-moz-focus-inner': {
// Clear the focus border in Firefox. Reference: path_to_url
border: 0,
},
'&': {
// Clear browser specific focus styles and use transparent as placeholder for focus style
outline: 'transparent',
},
},
};
}
/**
* Generates a style which can be used to set a border on focus.
*
* @param theme - The theme object to use.
* @param inset - The number of pixels to inset the border (default 0)
* @param width - The border width in pixels (default 1)
* @param color - Color of the outline (default `theme.palette.neutralSecondary`)
* @returns The style object.
*/
export function getFocusOutlineStyle(theme: ITheme, inset: number = 0, width: number = 1, color?: string): IRawStyle {
return {
selectors: {
[`:global(${IsFocusVisibleClassName}) &:focus`]: {
outline: `${width} solid ${color || theme.palette.neutralSecondary}`,
outlineOffset: `${-inset}px`,
},
},
};
}
/**
* Generates text input border styles on focus.
*
* @param borderColor - Color of the border.
* @param borderRadius - Radius of the border.
* @param borderType - Type of the border.
* @param borderPosition - Position of the border relative to the input element (default to -1
* as it's the most common border width of the input element)
* @returns The style object.
*/
export const getInputFocusStyle = (
borderColor: string,
borderRadius: string | number,
borderType: 'border' | 'borderBottom' = 'border',
borderPosition: number = -1,
): IRawStyle => {
const isBorderBottom = borderType === 'borderBottom';
return {
borderColor,
selectors: {
':after': {
pointerEvents: 'none',
content: "''",
position: 'absolute',
left: isBorderBottom ? 0 : borderPosition,
top: borderPosition,
bottom: borderPosition,
right: isBorderBottom ? 0 : borderPosition,
[borderType]: `2px solid ${borderColor}`,
borderRadius,
width: borderType === 'borderBottom' ? '100%' : undefined,
selectors: {
[HighContrastSelector]: {
[borderType === 'border' ? 'borderColor' : 'borderBottomColor']: 'Highlight',
},
},
},
},
};
};
``` | /content/code_sandbox/packages/style-utilities/src/styles/getFocusStyle.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 1,449 |
```xml
// See LICENSE in the project root for license information.
import webpack, { type Compiler, type Plugin } from 'webpack';
import type { ReplaceSource } from 'webpack-sources';
import type { Tapable, TapOptions } from 'tapable';
const { Template } = webpack;
import { STAGE_AFTER } from './Constants';
import type {
IExtendedModule,
IModuleMinifierPluginHooks,
IPostProcessFragmentContext
} from './ModuleMinifierPlugin.types';
const PLUGIN_NAME: 'AsyncImportCompressionPlugin' = 'AsyncImportCompressionPlugin';
const TAP_AFTER: TapOptions<'sync'> = {
name: PLUGIN_NAME,
stage: STAGE_AFTER
};
const ASYNC_IMPORT_PREFIX: '__IMPORT_ASYNC' = '__IMPORT_ASYNC';
const ASYNC_IMPORT_REGEX: RegExp = /__IMPORT_ASYNC[^\)]+/g;
declare class WebpackImportDependency extends webpack.compilation.Dependency {
public module: webpack.compilation.Module;
public block: {
chunkGroup: webpack.compilation.ChunkGroup;
range: [number, number];
};
}
interface IImportDependencyTemplate {
apply(
dependency: WebpackImportDependency,
source: ReplaceSource,
runtime: webpack.compilation.RuntimeTemplate
): void;
}
interface IAsyncImportMetadata {
chunkCount: number;
chunkIds: number[];
count: number;
index: number;
}
interface ILocalImportMetadata {
meta: IAsyncImportMetadata;
module: webpack.compilation.Module;
}
function getImportDependency(compilation: webpack.compilation.Compilation): typeof WebpackImportDependency {
for (const key of compilation.dependencyTemplates.keys()) {
if (key.name === 'ImportDependency') {
return key as unknown as typeof WebpackImportDependency;
}
}
throw new Error(`Could not find ImportDependency!`);
}
function getImportTypeExpression(
module: webpack.compilation.Module,
originModule: webpack.compilation.Module
): string {
const exportsType: string | undefined = module.buildMeta?.exportsType;
const strict: boolean | undefined = originModule.buildMeta?.strictHarmonyModule;
// Logic translated from:
// path_to_url#L110-L122
if (exportsType === 'namespace') {
// Use the raw module directly
return '';
} else if (exportsType === 'named') {
// Create a new namespace object and forward all exports
return ',3';
} else if (strict) {
// Synthetic default export
return ',1';
} else {
// If modules is marked __esModule, return raw module, otherwise create a new namespace object and forward all exports
return ',7';
}
}
function needChunkOnDemandLoadingCode(chunk: webpack.compilation.Chunk): boolean {
for (const chunkGroup of chunk.groupsIterable) {
if (chunkGroup.getNumberOfChildren() > 0) {
return true;
}
}
return false;
}
/**
* Plugin that replaces `Promise.all([__webpack_require__.e(1), __webpack_require__.e(12)]).then(__webpack_require__.t.bind(123,7))`
* with more concise expressions like `__webpack_require__.ee([1,12],123,7)`, etc.
*
* Also ensures that the code seen by the minifier does not contain chunk ids, and is therefore portable across chunks/compilations.
*/
export class AsyncImportCompressionPlugin implements Plugin {
private readonly _minifierHooks: IModuleMinifierPluginHooks;
public constructor(minifierHooks: IModuleMinifierPluginHooks) {
this._minifierHooks = minifierHooks;
}
public apply(compiler: Compiler): void {
const asyncImportMap: Map<webpack.compilation.Module, Map<string, ILocalImportMetadata>> = new Map();
const asyncImportGroups: Map<string, IAsyncImportMetadata> = new Map();
let rankedImportGroups: IAsyncImportMetadata[] | undefined;
this._minifierHooks.postProcessCodeFragment.tap(
{
name: PLUGIN_NAME,
stage: -1
},
(source: ReplaceSource, context: IPostProcessFragmentContext) => {
const code: string = source.original().source() as string;
let localImports: Map<string, ILocalImportMetadata> | undefined;
ASYNC_IMPORT_REGEX.lastIndex = -1;
// RegExp.exec uses null or an array as the return type, explicitly
let match: RegExpExecArray | null = null;
while ((match = ASYNC_IMPORT_REGEX.exec(code))) {
const token: string = match[0];
if (!localImports) {
if (!context.module) {
context.compilation.errors.push(
new Error(`Unexpected async import ${token} in non-module context ${context.loggingName}`)
);
return source;
}
localImports = asyncImportMap.get(context.module);
if (!localImports) {
context.compilation.errors.push(
new Error(`Unexpected async import ${token} in module ${context.loggingName}`)
);
return source;
}
}
const localImport: ILocalImportMetadata | undefined = localImports.get(token);
if (!localImport) {
context.compilation.errors.push(
new Error(`Missing metadata for ${token} in module ${context.loggingName}`)
);
return source;
}
const { meta, module } = localImport;
const chunkExpression: string = meta.index < 0 ? JSON.stringify(meta.chunkIds) : `${meta.index}`;
const mapped: string | number | undefined = this._minifierHooks.finalModuleId.call(
module.id!,
context.compilation
);
const idExpr: string | number = mapped === undefined ? module.id! : mapped;
// Replace with a reference or array of ideas, the target module id, and the type of import
source.replace(
match.index,
ASYNC_IMPORT_REGEX.lastIndex - 1,
`${chunkExpression},${JSON.stringify(idExpr)}${getImportTypeExpression(module, context.module!)}`
);
}
return source;
}
);
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation: webpack.compilation.Compilation) => {
asyncImportMap.clear();
asyncImportGroups.clear();
compilation.hooks.beforeChunkAssets.tap(TAP_AFTER, () => {
const ImportDependency: typeof WebpackImportDependency = getImportDependency(compilation);
for (const module of compilation.modules) {
const toProcess: IExtendedModule[] = module.modules || [module];
for (const child of toProcess) {
child.hasDependencies((dep: webpack.compilation.Dependency) => {
if (dep instanceof ImportDependency) {
const { module: targetModule } = dep;
if (targetModule) {
let localAsyncImports: Map<string, ILocalImportMetadata> | undefined =
asyncImportMap.get(module);
if (!localAsyncImports) {
asyncImportMap.set(module, (localAsyncImports = new Map()));
}
const chunkGroup: webpack.compilation.ChunkGroup = dep.block.chunkGroup;
const chunkIds: number[] = chunkGroup
? chunkGroup.chunks.map((chunk) => chunk.id!).sort()
: [];
const idString: string = chunkIds.join(';');
let meta: IAsyncImportMetadata | undefined = asyncImportGroups.get(idString);
if (!meta) {
asyncImportGroups.set(
idString,
(meta = {
chunkCount: chunkIds.length,
chunkIds: chunkIds,
count: 0,
index: -1
})
);
}
meta.count++;
const stringKey: string = `${targetModule.id}`.replace(/[^A-Za-z0-9_$]/g, '_');
const key: string = `${ASYNC_IMPORT_PREFIX}${stringKey}`;
localAsyncImports.set(key, {
meta,
module: targetModule
});
}
}
});
}
}
const rankedImports: [string, IAsyncImportMetadata][] = [...asyncImportGroups]
.filter((x) => x[1].count > 1)
.sort((x, y) => {
let diff: number = y[1].count - x[1].count;
if (!diff) {
diff = y[1].chunkCount - x[1].chunkCount;
}
if (!diff) {
diff = x[0] > y[0] ? 1 : x[0] < y[0] ? -1 : 0;
}
return diff;
});
for (let i: number = 0, len: number = rankedImports.length; i < len; i++) {
rankedImports[i][1].index = i;
// console.log(rankedImports[i]);
}
rankedImportGroups = rankedImports.map((x) => x[1]);
const { dependencyTemplates } = compilation;
const defaultImplementation: IImportDependencyTemplate | undefined = dependencyTemplates.get(
ImportDependency
) as unknown as IImportDependencyTemplate;
if (!defaultImplementation) {
compilation.errors.push(new Error(`Could not find ImportDependencyTemplate`));
}
const customTemplate: IImportDependencyTemplate = {
apply(
dep: WebpackImportDependency,
source: ReplaceSource,
runtime: webpack.compilation.RuntimeTemplate
): void {
if (dep.module) {
const stringKey: string = `${dep.module.id}`.replace(/[^A-Za-z0-9_$]/g, '_');
const key: string = `${ASYNC_IMPORT_PREFIX}${stringKey}`;
const content: string = `__webpack_require__.ee(${key})`;
source.replace(dep.block.range[0], dep.block.range[1] - 1, content);
} else {
defaultImplementation?.apply(dep, source, runtime);
}
}
};
// Have to do this after the official plugin in order to override
// Typings in webpack are incorrect. This is a DependencyTemplate object
dependencyTemplates.set(ImportDependency, customTemplate as unknown as Tapable);
});
compilation.mainTemplate.hooks.requireExtensions.tap(
PLUGIN_NAME,
(source: string, chunk: webpack.compilation.Chunk) => {
if (!needChunkOnDemandLoadingCode(chunk)) {
return source;
}
const { requireFn } = compilation.mainTemplate;
return Template.asString([
`var asyncImportChunkGroups = [`,
rankedImportGroups
? rankedImportGroups.map((x) => Template.indent(JSON.stringify(x.chunkIds))).join(',\n')
: '',
`];`,
`${requireFn}.ee = function (groupOrId, moduleId, importType) {`,
Template.indent([
`return Promise.all((Array.isArray(groupOrId) ? groupOrId : asyncImportChunkGroups[groupOrId]).map(function (x) { return ${requireFn}.e(x); }))`,
`.then(importType ? ${requireFn}.t.bind(0,moduleId,importType) : ${requireFn}.bind(0,moduleId));`
]),
`};`,
source
]);
}
);
});
}
}
``` | /content/code_sandbox/webpack/webpack4-module-minifier-plugin/src/AsyncImportCompressionPlugin.ts | xml | 2016-09-30T00:28:20 | 2024-08-16T18:54:35 | rushstack | microsoft/rushstack | 5,790 | 2,375 |
```xml
export const base64image =
'data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEmyour_sha512_hashQePLl38MGBr8JCP+zs9myn/8GBqwpAPyour_sha512_hashvz8/your_sha256_hashcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pjyour_sha512_hashv70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pzyour_sha512_hash///8AAP9mZv///your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/your_sha256_hashyour_sha256_hash5QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/your_sha256_hashYA+your_sha256_hashqx+your_sha256_hashtsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/your_sha256_hashyour_sha256_hashHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+your_sha256_hashyour_sha256_hash6X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==';
``` | /content/code_sandbox/tests/fixtures/base64image.ts | xml | 2016-06-17T10:42:50 | 2024-08-16T05:57:17 | tsoa | lukeautry/tsoa | 3,408 | 975 |
```xml
// import * as nock from 'nock'
import { mocki } from './inquirer-mock-prompt'
import { Config } from 'prisma-cli-engine'
import Init from './init'
import { writeToStdIn, DOWN, ENTER } from '../../test/writeToStdin'
import { getTmpDir } from '../../test/getTmpDir'
import * as fs from 'fs-extra'
import * as path from 'path'
import * as cuid from 'scuid'
function makeMockConfig(mockInquirer?: any) {
const home = getTmpDir()
const cwd = path.join(home, cuid())
fs.mkdirpSync(cwd)
return {
config: new Config({ mock: true, home, cwd, mockInquirer }),
home,
cwd,
}
}
function getFolderContent(folder) {
return fs
.readdirSync(folder)
.map(f => {
let file = fs.readFileSync(path.join(folder, f), 'utf-8')
if (f === 'docker-compose.yml') {
file = normalizeDockerCompose(file)
}
return { [f]: file }
})
.reduce((acc, curr) => ({ ...acc, ...curr }), {})
}
async function testChoices(choices) {
const mockInquirer = mocki(choices)
const { config, home, cwd } = makeMockConfig(mockInquirer)
const result = await Init.mock({ mockConfig: config })
expect(getFolderContent(cwd)).toMatchSnapshot()
expect(makeOutputDeterministic(result.out.stdout.output)).toMatchSnapshot()
expect(makeOutputDeterministic(result.out.stderr.output)).toMatchSnapshot()
}
function makeOutputDeterministic(output: string) {
return output
.split('\n')
.filter(l => !l.includes('Connecting to database'))
.join('\n')
}
describe.skip('init', () => {
test('choose local', async () => {
await testChoices({
choice: 'local',
})
})
test('test project', async () => {
await testChoices({
choice: 'Use existing database',
dbType: 'postgres',
host: 'localhost',
port: 5432,
database: process.env.TEST_PG_DB,
user: process.env.TEST_PG_USER || 'postgres',
password: process.env.TEST_PG_PASSWORD,
schema: undefined,
alreadyData: false,
})
})
})
export function normalizeDockerCompose(dc) {
return dc
.split('\n')
.filter(
l =>
!l.trim().startsWith('user:') &&
!l.trim().startsWith('password:') &&
!l.trim().startsWith('database:') &&
!l.trim().startsWith('image:'),
)
.join('\n')
}
``` | /content/code_sandbox/cli/packages/prisma-cli-core/src/commands/init/init.test.ts | xml | 2016-09-25T12:54:40 | 2024-08-16T11:41:23 | prisma1 | prisma/prisma1 | 16,549 | 578 |
```xml
import { IgResponseError } from './ig-response.error';
export class IgInactiveUserError extends IgResponseError {}
``` | /content/code_sandbox/src/errors/ig-inactive-user.error.ts | xml | 2016-06-09T12:14:48 | 2024-08-16T10:07:22 | instagram-private-api | dilame/instagram-private-api | 5,877 | 24 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12120" systemVersion="16E195" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="cell" id="fLB-GI-A65" customClass="DescriptionCollectionViewCell" customModule="PopcornTime" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="334" height="19"/>
<autoresizingMask key="autoresizingMask" flexibleMaxY="YES"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="334" height="19"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" tag="1" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="right" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="nhL-4f-wAq">
<rect key="frame" x="0.0" y="0.5" width="75" height="18.5"/>
<constraints>
<constraint firstAttribute="height" relation="greaterThanOrEqual" constant="15" id="s3g-Cl-rr1"/>
<constraint firstAttribute="width" constant="75" id="tbK-Ap-6WW"/>
</constraints>
<fontDescription key="fontDescription" style="UICTFontTextStyleCaption1"/>
<color key="textColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" tag="2" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="jkU-Ya-dZx">
<rect key="frame" x="85" y="0.0" width="249" height="19"/>
<constraints>
<constraint firstAttribute="height" relation="greaterThanOrEqual" constant="15" id="tvQ-xg-gEf"/>
</constraints>
<fontDescription key="fontDescription" style="UICTFontTextStyleCaption1"/>
<color key="textColor" white="1" alpha="0.59724361800000003" colorSpace="calibratedWhite"/>
<nil key="highlightedColor"/>
</label>
</subviews>
</view>
<constraints>
<constraint firstItem="jkU-Ya-dZx" firstAttribute="leading" secondItem="nhL-4f-wAq" secondAttribute="trailing" constant="10" id="K0d-pz-wMx"/>
<constraint firstItem="nhL-4f-wAq" firstAttribute="top" secondItem="fLB-GI-A65" secondAttribute="top" id="PRP-gU-Fye"/>
<constraint firstAttribute="trailing" secondItem="jkU-Ya-dZx" secondAttribute="trailing" id="SRO-ZO-Quc"/>
<constraint firstItem="nhL-4f-wAq" firstAttribute="leading" secondItem="fLB-GI-A65" secondAttribute="leading" id="V3h-Kr-yC4"/>
<constraint firstItem="jkU-Ya-dZx" firstAttribute="top" secondItem="fLB-GI-A65" secondAttribute="top" id="ZEL-I0-rFj"/>
<constraint firstAttribute="bottom" secondItem="nhL-4f-wAq" secondAttribute="bottom" id="bfr-M4-gvH"/>
<constraint firstAttribute="bottom" secondItem="jkU-Ya-dZx" secondAttribute="bottom" id="qd9-iD-Bxg"/>
</constraints>
<size key="customSize" width="334" height="-99"/>
<connections>
<outlet property="keyLabel" destination="nhL-4f-wAq" id="XuH-eK-7o7"/>
<outlet property="valueLabel" destination="jkU-Ya-dZx" id="VIq-sf-BJY"/>
</connections>
<point key="canvasLocation" x="13" y="47.5"/>
</collectionViewCell>
</objects>
</document>
``` | /content/code_sandbox/PopcornTime/UI/iOS/Collection View Cells/DescriptionCollectionViewCell.xib | xml | 2016-08-07T10:18:41 | 2024-08-16T13:03:46 | PopcornTimeTV | PopcornTimeTV/PopcornTimeTV | 1,357 | 1,231 |
```xml
<!--
***********************************************************************************************
Microsoft.NET.Sdk.Publish.FileSystem.targets
WARNING: DO NOT MODIFY this file unless you are knowledgeable about MSBuild and have
created a backup copy. Incorrect changes to this file will make it
impossible to load or build your web deploy projects from the command-line or the IDE.
This file defines the steps in the standard build process to deploy web application projects.
***********************************************************************************************
-->
<Project xmlns="path_to_url">
<PropertyGroup>
<_DotNetPublishFiles>
FileSystemPublish;
</_DotNetPublishFiles>
</PropertyGroup>
<!--
***********************************************************************************************
TARGET : FileSystemPublish
***********************************************************************************************
-->
<PropertyGroup>
<FileSystemPublishDependsOn>
$(FileSystemPublishDependsOn);
_DeleteDestinationFilesIfSpecified;
_CopyEntityFrameworkScripts;
_GatherFilesFromPublishIntermediateOutputPath;
</FileSystemPublishDependsOn>
</PropertyGroup>
<Target Name="FileSystemPublish"
DependsOnTargets="$(FileSystemPublishDependsOn)"
Inputs="@(_PublishIntermediateOutputPathFiles)"
Outputs="@(_PublishIntermediateOutputPathFiles ->'$(PublishUrl)%(RecursiveDir)%(Filename)%(Extension)')">
<Copy
SourceFiles="@(_PublishIntermediateOutputPathFiles)"
DestinationFiles="@(_PublishIntermediateOutputPathFiles ->'$(PublishUrl)%(RecursiveDir)%(Filename)%(Extension)')" />
</Target>
<!--
***********************************************************************************************
TARGET : _DeleteDestinationFilesIfSpecified
***********************************************************************************************
-->
<Target Name="_DeleteDestinationFilesIfSpecified">
<PropertyGroup>
<PublishUrl Condition="'$(PublishUrl)' != '' And !HasTrailingSlash('$(PublishUrl)')">$(PublishUrl)\</PublishUrl>
</PropertyGroup>
<ItemGroup>
<_DestinationFiles Include="$(PublishUrl)**\*" />
</ItemGroup>
<Delete
Files="@(_DestinationFiles)"
Condition="'$(DeleteExistingFiles)' == 'true'" />
<RemoveDir
Directories="$(PublishUrl)"
Condition="'$(DeleteExistingFiles)' == 'true' And '$(PreserveDestinationFolder)' != 'true' And Exists('$(PublishUrl)')" />
<MakeDir
Directories="$(PublishUrl)"
Condition="'$(DeleteExistingFiles)' == 'true' And '$(PreserveDestinationFolder)' != 'true' And !Exists('$(PublishUrl)')"/>
</Target>
<!--
***********************************************************************************************
TARGET : _GatherFilesFromPublishIntermediateOutputPath
***********************************************************************************************
-->
<Target Name="_GatherFilesFromPublishIntermediateOutputPath">
<ItemGroup>
<_PublishIntermediateOutputPathFiles Include="$(PublishIntermediateOutputPath)**\*.*" />
</ItemGroup>
</Target>
<!--
***********************************************************************************************
TARGET : _CopyEntityFrameworkScripts
***********************************************************************************************
-->
<Target Name="_CopyEntityFrameworkScripts">
<Copy
Condition="@(_EFSQLScripts) != ''"
SourceFiles="@(_EFSQLScripts)"
DestinationFiles="@(_EFSQLScripts ->'$(PublishIntermediateOutputPath)$(EFSQLScriptsFolderName)\%(Filename)%(Extension)')"
ContinueOnError="true"/>
</Target>
</Project>
``` | /content/code_sandbox/src/WebSdk/Publish/Targets/PublishTargets/Microsoft.NET.Sdk.Publish.FileSystem.targets | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 693 |
```xml
<!--
Description:
-->
<feed xmlns="path_to_url">
</feed>
``` | /content/code_sandbox/testdata/parser/atom/version_atom10.xml | xml | 2016-01-23T02:44:34 | 2024-08-16T15:16:03 | gofeed | mmcdole/gofeed | 2,547 | 17 |
```xml
/*
tags: basic
<p> This example shows how to draw a mesh with regl </p>
*/
import REGL = require('../../regl')
import mat4 = require('gl-mat4')
import bunny = require('bunny')
const regl = REGL()
interface Uniforms {
model: REGL.Mat4;
view: REGL.Mat4;
projection: REGL.Mat4;
}
interface Attributes {
position: REGL.Vec3;
}
const drawBunny = regl<Uniforms, Attributes>({
vert: `
precision mediump float;
attribute vec3 position;
uniform mat4 model, view, projection;
void main() {
gl_Position = projection * view * model * vec4(position, 1);
}`,
frag: `
precision mediump float;
void main() {
gl_FragColor = vec4(1, 1, 1, 1);
}`,
// this converts the vertices of the mesh into the position attribute
attributes: {
position: bunny.positions
},
// and this converts the faces fo the mesh into elements
elements: bunny.cells,
uniforms: {
model: mat4.identity([]),
view: ({tick}) => {
const t = 0.01 * tick
return mat4.lookAt([],
[30 * Math.cos(t), 2.5, 30 * Math.sin(t)],
[0, 2.5, 0],
[0, 1, 0])
},
projection: ({viewportWidth, viewportHeight}) =>
mat4.perspective([],
Math.PI / 4,
viewportWidth / viewportHeight,
0.01,
1000)
}
})
regl.frame(() => {
regl.clear({
depth: 1,
color: [0, 0, 0, 1]
})
drawBunny()
})
``` | /content/code_sandbox/example/typescript/bunny.ts | xml | 2016-02-23T00:03:11 | 2024-08-15T22:14:06 | regl | regl-project/regl | 5,194 | 424 |
```xml
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Alert, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton } from '@proton/components';
import keyAndFileSvg from '@proton/styles/assets/img/illustrations/file-recovery.svg';
interface Props {
onRecovery: () => void;
onClose?: () => void;
recovering?: boolean;
}
const FilesRecoveryState = ({ onRecovery, onClose, recovering }: Props) => {
const title = c('Title').t`Restore your files`;
return (
<>
<ModalTwoHeader title={c('Title').t`File recovery process`} closeButtonProps={{ disabled: recovering }} />
<ModalTwoContent>
<div className="p-4 flex w-full">
<img src={keyAndFileSvg} alt={title} className="w-1/2 m-auto" />
</div>
<Alert className="my-4">
<div>{c('Info').jt`Would you like to restore your files?`}</div>
<div>{c('Info').jt`Recovery process might take some time.`}</div>
</Alert>
</ModalTwoContent>
<ModalTwoFooter>
<div className="flex justify-space-between w-full flex-nowrap">
<Button
disabled={recovering}
autoFocus
className="min-w-custom"
style={{ '--min-w-custom': '7em' }}
onClick={onClose}
>{c('Action').t`Cancel`}</Button>
<PrimaryButton
loading={recovering}
className="min-w-custom"
style={{ '--min-w-custom': '7em' }}
onClick={onRecovery}
>
{c('Action').t`Start recovering`}
</PrimaryButton>
</div>
</ModalTwoFooter>
</>
);
};
export default FilesRecoveryState;
``` | /content/code_sandbox/applications/drive/src/app/components/modals/FilesRecoveryModal/FilesRecoveryState.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 415 |
```xml
<layer-list xmlns:android="path_to_url">
<item android:drawable="@color/splashscreen_background"/>
</layer-list>
``` | /content/code_sandbox/example-expo/android/app/src/main/res/drawable/splashscreen.xml | xml | 2016-07-27T10:57:27 | 2024-08-14T16:51:53 | react-native-ble-plx | dotintent/react-native-ble-plx | 3,006 | 29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.