content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
namespace QA.Core.DPC.UI.Controls
{
public enum TextOverflow
{
None, Ellipsis, Clip
}
}
| 13.625 | 34 | 0.605505 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | QuantumArt/QA.DPC | QA.Core.DPC.UI/Controls/QP/TextOverflow.cs | 111 | C# |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
namespace Community.VisualStudio.Toolkit
{
/// <summary>
/// A helper class that can automatically theme any XAML control or window using the VS theme properties.
/// </summary>
/// <remarks>Should only be referenced from within .xaml files.</remarks>
/// <example>
/// <code>
/// <UserControl x:Class="MyClass"
/// xmlns:toolkit="clr-namespace:Community.VisualStudio.Toolkit;assembly=Community.VisualStudio.Toolkit"
/// toolkit:Themes.UseVsTheme="True">
/// </UserControl>
/// </code>
/// </example>
public static class Themes
{
private static readonly DependencyProperty _originalBackgroundProperty = DependencyProperty.RegisterAttached("OriginalBackground", typeof(object), typeof(Themes));
private static readonly DependencyProperty _originalForegroundProperty = DependencyProperty.RegisterAttached("OriginalForeground", typeof(object), typeof(Themes));
private static ResourceDictionary? _themeResources;
/// <summary>
/// The property to add to your XAML control.
/// </summary>
public static readonly DependencyProperty UseVsThemeProperty = DependencyProperty.RegisterAttached("UseVsTheme", typeof(bool), typeof(Themes), new PropertyMetadata(false, UseVsThemePropertyChanged));
/// <summary>
/// Sets the UseVsTheme property.
/// </summary>
public static void SetUseVsTheme(UIElement element, bool value) => element.SetValue(UseVsThemeProperty, value);
/// <summary>
/// Gets the UseVsTheme property from the specified element.
/// </summary>
public static bool GetUseVsTheme(UIElement element) => (bool)element.GetValue(UseVsThemeProperty);
private static void UseVsThemePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!DesignerProperties.GetIsInDesignMode(d))
{
if (d is FrameworkElement element)
{
if ((bool)e.NewValue)
{
OverrideProperty(element, Control.BackgroundProperty, _originalBackgroundProperty, ThemedDialogColors.WindowPanelBrushKey);
OverrideProperty(element, Control.ForegroundProperty, _originalForegroundProperty, ThemedDialogColors.WindowPanelTextBrushKey);
ThemedDialogStyleLoader.SetUseDefaultThemedDialogStyles(element, true);
ImageThemingUtilities.SetThemeScrollBars(element, true);
// Only merge the styles after the element has been initialized.
// If the element hasn't been initialized yet, add an event handler
// so that we can merge the styles once it has been initialized.
if (!element.IsInitialized)
{
element.Initialized += OnElementInitialized;
}
else
{
MergeStyles(element);
}
}
else
{
if (_themeResources is not null)
{
element.Resources.MergedDictionaries.Remove(_themeResources);
}
ImageThemingUtilities.SetThemeScrollBars(element, null);
ThemedDialogStyleLoader.SetUseDefaultThemedDialogStyles(element, false);
RestoreProperty(element, Control.ForegroundProperty, _originalForegroundProperty);
RestoreProperty(element, Control.BackgroundProperty, _originalBackgroundProperty);
}
}
}
}
private static void OverrideProperty(FrameworkElement element, DependencyProperty property, DependencyProperty backup, object value)
{
if (element is Control control)
{
object original = control.ReadLocalValue(property);
if (!ReferenceEquals(value, DependencyProperty.UnsetValue))
{
control.SetValue(backup, original);
}
control.SetResourceReference(property, value);
}
}
private static void RestoreProperty(FrameworkElement element, DependencyProperty property, DependencyProperty backup)
{
if (element is Control control)
{
object value = control.ReadLocalValue(backup);
if (!ReferenceEquals(value, DependencyProperty.UnsetValue))
{
control.SetValue(property, value);
}
else
{
control.ClearValue(property);
}
control.ClearValue(backup);
}
}
private static void OnElementInitialized(object sender, EventArgs args)
{
FrameworkElement element = (FrameworkElement)sender;
MergeStyles(element);
element.Initialized -= OnElementInitialized;
}
private static void MergeStyles(FrameworkElement element)
{
#if DEBUG
// Always reload the theme resources in DEBUG mode, because it allows
// them to be edited on disk without needing to restart Visual Studio,
// which makes it much easier to create and test new styles.
_themeResources = null;
#endif
if (_themeResources is null)
{
_themeResources = LoadThemeResources();
}
Collection<ResourceDictionary> dictionaries = element.Resources.MergedDictionaries;
if (!dictionaries.Contains(_themeResources))
{
dictionaries.Add(_themeResources);
}
}
private static ResourceDictionary LoadThemeResources()
{
try
{
return LoadResources();
}
catch (Exception ex) when (!ErrorHandler.IsCriticalException(ex))
{
ex.Log();
return new ResourceDictionary();
}
}
private static ResourceDictionary LoadResources(
#if DEBUG
[System.Runtime.CompilerServices.CallerFilePath] string? thisFilePath = null
#endif
)
{
#if DEBUG
// Load the resources from disk in DEBUG mode, because this allows
// you to edit the resources without needing to reload Visual Studio.
using (StreamReader reader = new(Path.Combine(Path.GetDirectoryName(thisFilePath), "ThemeResources.xaml")))
#else
using (StreamReader reader = new(typeof(Themes).Assembly.GetManifestResourceStream("Community.VisualStudio.Toolkit.Themes.ThemeResources.xaml")))
#endif
{
string content = reader.ReadToEnd();
// The XAML uses the `VsResourceKeys` type and needs to specify the assembly
// that the type is in, but the exact assembly name differs between the
// toolkit versions, so we need to replace the assembly name at runtime.
content = content.Replace(
"clr-namespace:Microsoft.VisualStudio.Shell;assembly=Microsoft.VisualStudio.Shell.15.0",
$"clr-namespace:Microsoft.VisualStudio.Shell;assembly={typeof(VsResourceKeys).Assembly.GetName().Name}"
);
// Do the same thing for the `CommonControlsColors` namespace.
content = content.Replace(
"clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0",
$"clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly={typeof(CommonControlsColors).Assembly.GetName().Name}"
);
return (ResourceDictionary)System.Windows.Markup.XamlReader.Parse(content);
}
}
}
} | 42.765306 | 207 | 0.600931 | [
"Apache-2.0"
] | Nirmal4G/visual-studio-toolkit | src/toolkit/Community.VisualStudio.Toolkit.Shared/Themes/Themes.cs | 8,382 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
namespace TechTalk.SpecFlow.Assist.ValueRetrievers
{
public class LongValueRetriever : IValueRetriever
{
public virtual long GetValue(string value)
{
long.TryParse(value, NumberStyles.Any, CultureInfo.CurrentCulture, out long returnValue);
return returnValue;
}
public object Retrieve(KeyValuePair<string, string> keyValuePair, Type targetType, Type propertyType)
{
return GetValue(keyValuePair.Value);
}
public bool CanRetrieve(KeyValuePair<string, string> keyValuePair, Type targetType, Type propertyType)
{
return propertyType == typeof(long);
}
}
} | 30.32 | 110 | 0.6781 | [
"Apache-2.0",
"MIT"
] | ImanMesgaran/SpecFlow | TechTalk.SpecFlow/Assist/ValueRetrievers/LongValueRetriever.cs | 760 | C# |
namespace Skight.eLiteWeb.Presentation.Web.FrontControllers
{
public interface WebRequest
{
WebInput Input { get; }
WebOutput Output { get; }
}
} | 20.333333 | 60 | 0.617486 | [
"BSD-3-Clause"
] | SkightTeam/eLiteWeb | Skight.eLiteWeb.Presentation/Web/FrontControllers/WebRequest.cs | 185 | C# |
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using Minax.Collections;
using Minax.Domain.Translation;
using Minax.Web.Translation;
using MinaxWebTranslator.Desktop.Commands;
using MinaxWebTranslator.Desktop.Models;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using AvalonDock.Layout;
namespace MinaxWebTranslator.Desktop.Views
{
/// <summary>
/// Dockable panel for Mapping tables
/// </summary>
public partial class MappingDockingPanel : LayoutAnchorable
{
public ICommand ProjConfSearchCmd => new SimpleCommand( o => true, x => _SearchText( x as string, DgMappingProjConf ) );
public ICommand GlossariesSearchCmd => new SimpleCommand( o => true, x => _SearchText( x as string, DgMappingGlossaries ) );
public ICommand AllSearchCmd => new SimpleCommand( o => true, x => _SearchText( x as string, DgMappingAll ) );
internal bool IsProjectChanged => mProjChanged;
public MappingDockingPanel() : this( Application.Current.MainWindow as MainWindow )
{
}
public MappingDockingPanel( MainWindow mainWindow )
{
mMainWindow = mainWindow;
InitializeComponent();
DgMappingAll.Items.Clear();
DgMappingGlossaries.Items.Clear();
DgMappingProjConf.Items.Clear();
DgMappingAll.ItemsSource = null;
DgMappingGlossaries.ItemsSource = null;
DgMappingProjConf.ItemsSource = null;
// acceess ICommand instances via DataContext
TbMappingAllSearch.DataContext = this;
TbMappingProjConfSearch.DataContext = this;
TbMappingGlossariesToolSearch.DataContext = this;
MessageHub.MessageReceived -= MsgHub_MessageRecevied;
MessageHub.MessageReceived += MsgHub_MessageRecevied;
}
// default Input Dialog setting for MahApps
private readonly MetroDialogSettings sInputSettings = new MetroDialogSettings {
AffirmativeButtonText = Languages.Global.Str0Ok, NegativeButtonText = Languages.Global.Str0Cancel,
DefaultButtonFocus = MessageDialogResult.Affirmative,
DialogResultOnCancel = MessageDialogResult.Canceled, OwnerCanCloseWithDialog = true,
};
private readonly MainWindow mMainWindow;
private ProjectModel mProject;
private bool mProjChanged = false;
private TranslatorSelector mCurrentXlator = null;
private RemoteType mCurrentRemoteTranslator = RemoteType.Excite;
private System.Predicate<object> _BuildTextFilter( string text )
{
return new System.Predicate<object>( item => {
var model = item as MappingMonitor.MappingModel;
if( model == null || model.OriginalText == null )
return false;
if( model.OriginalText != null && model.OriginalText.ToLowerInvariant().Contains( text ) )
return true;
if( model.MappingText != null && model.MappingText.ToLowerInvariant().Contains( text ) )
return true;
if( model.Description != null && model.Description.ToLowerInvariant().Contains( text ) )
return true;
if( model.Comment != null && model.Comment.ToLowerInvariant().Contains( text ) )
return true;
if( model.Category != null ) {
if( model.Category.ToString().ToLowerInvariant().Contains( text ) )
return true;
if( ((TextCategory)model.Category).ToL10nString().Contains( text ) )
return true;
}
return false;
} );
}
private void _SearchText( string text, DataGrid dg )
{
if( dg == null )
return;
ICollectionView cv = CollectionViewSource.GetDefaultView( dg.ItemsSource );
if( cv == null )
return;
if( string.IsNullOrWhiteSpace( text ) ) {
// when text is empty or button clicked, clear search results!!
if( cv.Filter != null ) {
dg.CancelEdit( DataGridEditingUnit.Row );
cv.Filter = null;
dg.InvalidateVisual();
}
return;
}
dg.CancelEdit( DataGridEditingUnit.Row );
cv.Filter = _BuildTextFilter( text.ToLowerInvariant() );
dg.InvalidateVisual();
}
private async void _SetProjChanged()
{
mProjChanged = true;
await MessageHub.SendMessageAsync( this, MessageType.ProjectChanged, mProject );
}
private async Task<bool> _ReloadAllMappingData( ProjectModel model )
{
if( model == null || model.Project == null || model.FullPathFileName == null ||
model.Project.SourceLanguage == SupportedSourceLanguage.AutoDetect )
return false;
// model shall open first
if( model.IsCurrent == false ) {
return false;
}
if( mProject == null )
mProject = model;
// de-subscribe all event of mapping data
_UnsubscribeAllChangedEvents();
// update TcMapping TabItems
TcMapping.Items.Clear();
var mon = ProjectManager.Instance.MappingMonitor;
if( mon == null )
return false;
DgMappingProjConf.ItemsSource = new List<MappingMonitor.MappingModel>();
DgMappingGlossaries.ItemsSource = DgMappingProjConf.ItemsSource;
DgMappingAll.ItemsSource = DgMappingProjConf.ItemsSource;
await Task.Delay( 200 );
// collect all glossary files' mapping models
var fileList = new List<string>( mon.MonitoringFileList );
if( fileList.Contains( model.FullPathFileName ) )
fileList.Remove( model.FullPathFileName );
// all glossary files and project mapping table are ready
// binding glossaries to DgMappingGlossaries
if( fileList.Count > 0 ) {
var glossaries = new ObservableList<MappingMonitor.MappingModel>();
foreach( var fn in fileList ) {
var coll = mon.GetMappingCollection( fn );
if( coll == null )
continue;
glossaries.AddRange( coll );
_SubscribeChangedEvents( coll );
}
var cvs = new CollectionViewSource() { Source = glossaries };
cvs.GroupDescriptions.Add( new PropertyGroupDescription( nameof( MappingMonitor.MappingModel.ProjectBasedFileName ) ) );
DgMappingGlossaries.ItemsSource = cvs.View;
TiMappingGlossaries.Visibility = Visibility.Visible;
if( TcMapping.Items.Contains(TiMappingGlossaries) == false )
TcMapping.Items.Insert( 0, TiMappingGlossaries );
}
bool hasGlossaryEntry = TcMapping.Items.Count > 0;
var projModels = mon.GetMappingCollection( model.FullPathFileName );
if( projModels == null ) {
projModels = new ObservableList<MappingMonitor.MappingModel>();
}
_SubscribeChangedEvents( projModels );
DgMappingProjConf.ItemsSource = projModels;
TiMappingProjConf.Header = model.ProjectName;
TiMappingProjConf.IsSelected = true;
if( TcMapping.Items.Contains(TiMappingProjConf) == false )
TcMapping.Items.Insert( 0, TiMappingProjConf );
if( hasGlossaryEntry ) {
CollectionViewSource cvs = new CollectionViewSource();
cvs.Source = mon.DescendedModels;
cvs.GroupDescriptions.Add( new PropertyGroupDescription( nameof( MappingMonitor.MappingModel.ProjectBasedFileName ) ) );
DgMappingAll.ItemsSource = cvs.View;
TiMappingAll.Visibility = Visibility.Visible;
if( TcMapping.Items.Contains(TiMappingAll) == false )
TcMapping.Items.Insert( 0, TiMappingAll );
}
return true;
}
private void _ReloadDataGridCvs( DataGrid dg, IReadOnlyList<MappingMonitor.MappingModel> newColl )
{
var cv = dg.ItemsSource as ICollectionView;
var cvs = new CollectionViewSource();
dg.ItemsSource = null;
if( newColl != null ) {
cvs.Source = newColl;
cvs.GroupDescriptions.Add( new PropertyGroupDescription( nameof( MappingMonitor.MappingModel.ProjectBasedFileName ) ) );
}
else if( cv != null && cv.SourceCollection is IReadOnlyCollection<MappingMonitor.MappingModel> aoc ) {
var newAoc = new ObservableList<MappingMonitor.MappingModel>();
newAoc.AddRange( aoc );
cvs.Source = newAoc;
cvs.GroupDescriptions.Add( new PropertyGroupDescription( nameof( MappingMonitor.MappingModel.ProjectBasedFileName ) ) );
}
dg.ItemsSource = cvs.View;
}
private void _SubscribeChangedEvents( IReadOnlyObservableList<MappingMonitor.MappingModel> projModels )
{
foreach( var entry in projModels ) {
entry.PropertyChanged -= MappingModel_PropertyChanged;
entry.PropertyChanged += MappingModel_PropertyChanged;
}
projModels.CollectionChanged -= MappingModelTables_CollectionChanged;
projModels.CollectionChanged += MappingModelTables_CollectionChanged;
}
private void _UnsubscribeAllChangedEvents()
{
var mon = ProjectManager.Instance.MappingMonitor;
if( mon == null )
return;
foreach( var fn in mon.MonitoringFileList ) {
var coll = mon.GetMappingCollection( fn );
if( coll == null )
continue;
coll.CollectionChanged -= MappingModelTables_CollectionChanged;
foreach( var entry in coll ) {
entry.PropertyChanged -= MappingModel_PropertyChanged;
}
}
}
private void _ModifyBindingWhenFileChanged( MessageType type, object data )
{
if( data == null || ProjectManager.Instance.MappingMonitor == null )
return;
var mon = ProjectManager.Instance.MappingMonitor;
var args = data as MappingMonitor.MappingEventArgs;
ObservableList<MappingMonitor.MappingModel> glossaries = null;
switch( type ) {
case MessageType.ProjectRenamed:
// most things were done by MainWindow, so just change title here
TiMappingProjConf.Header = mProject.ProjectName;
break;
case MessageType.ProjectUpdated:
if( args != null )
DgMappingProjConf.ItemsSource = mon.GetMappingCollection( args.FullPath );
break;
case MessageType.GlossaryRenamed:
_ReloadDataGridCvs( DgMappingGlossaries, null );
_ReloadDataGridCvs( DgMappingAll, null );
break;
case MessageType.GlossaryNew:
if( args == null )
break;
var cvNew = DgMappingGlossaries.ItemsSource as ICollectionView;
var collNew = mon.GetMappingCollection( args.FullPath );
if( collNew == null )
break;
if( cvNew == null || cvNew.SourceCollection is ObservableList<MappingMonitor.MappingModel> == false ) {
glossaries = new ObservableList<MappingMonitor.MappingModel>();
glossaries.AddRange( collNew );
var cvs = new CollectionViewSource { Source = glossaries };
cvs.GroupDescriptions.Add( new PropertyGroupDescription( nameof( MappingMonitor.MappingModel.ProjectBasedFileName ) ) );
DgMappingGlossaries.ItemsSource = cvs.View;
}
else {
glossaries = cvNew.SourceCollection as ObservableList<MappingMonitor.MappingModel>;
//glossaries.AddRange( collNew );
foreach( var ni in collNew ) {
glossaries.Add( ni );
}
}
break;
case MessageType.GlossaryDeleted:
var cv = DgMappingGlossaries.ItemsSource as ICollectionView;
if( cv == null || cv.IsEmpty || args == null )
return;
var coll = mon.GetMappingCollection( args.FullPath );
if( coll == null )
return;
// unbind MappingAll DataGrid ItemsSource first, otherwise its CVS would be incorrect
DgMappingAll.ItemsSource = null;
glossaries = cv.SourceCollection as ObservableList<MappingMonitor.MappingModel>;
if( glossaries != null ) {
glossaries.RemoveItems( coll );
}
// remove old Mapping file
mon.RemoveMonitoring( args.FullPath );
// bind MappingAll DataGrid ItemsSource with new CV
_ReloadDataGridCvs( DgMappingAll, mon.DescendedModels );
break;
case MessageType.GlossaryUpdated:
if( args == null )
break;
DgMappingGlossaries.ItemsSource = null;
DgMappingAll.ItemsSource = null;
// remove old Mapping file
mon.RemoveMonitoring( args.FullPath );
// try to parse updated file
var list = ProjectManager.Instance.TryParseAndExtractMappingEntries( args.FullPath );
if( list != null ) {
mon.AddMonitoring( args.FullPath, list );
}
glossaries = new ObservableList<MappingMonitor.MappingModel>();
// last is project conf. file, so ignore it
for( int i = 0; i < mon.MonitoringFileList.Count - 1; ++i ) {
var aoc = mon.GetMappingCollection( mon.MonitoringFileList[i] );
if( aoc != null )
glossaries.AddRange( aoc );
}
if( glossaries.Count > 0 ) {
_ReloadDataGridCvs( DgMappingGlossaries, glossaries );
_ReloadDataGridCvs( DgMappingAll, mon.DescendedModels );
}
break;
}
if( glossaries != null && glossaries.Count > 0 ) {
TiMappingGlossaries.Visibility = Visibility.Visible;
if( TcMapping.Items.Contains( TiMappingGlossaries ) == false )
TcMapping.Items.Add( TiMappingGlossaries );
if( TcMapping.Items.Contains( TiMappingAll ) == false )
TcMapping.Items.Insert( 0, TiMappingAll );
} else {
// hide the Glossary and All Tab
if( TcMapping.Items.Contains( TiMappingGlossaries ) )
TcMapping.Items.Remove( TiMappingGlossaries );
if( TcMapping.Items.Contains( TiMappingAll ) )
TcMapping.Items.Remove( TiMappingAll );
}
}
private async void MsgHub_MessageRecevied( object sender, MessageType type, object data )
{
if( sender == this )
return;
switch( type ) {
case MessageType.ProjectOpened:
if( data is ProjectModel pm ) {
mProject = pm;
}
else {
mProject = ProjectManager.Instance.CurrentProject;
}
if( mProject != null ) {
await _ReloadAllMappingData( mProject );
GdMappingProjConf.IsEnabled = true;
} else {
DgMappingAll.ItemsSource = null;
DgMappingGlossaries.ItemsSource = null;
DgMappingProjConf.ItemsSource = null;
GdMappingProjConf.IsEnabled = false;
}
break;
case MessageType.AppClosed:
case MessageType.AppClosing:
case MessageType.ProjectClosed:
DgMappingAll.ItemsSource = null;
DgMappingGlossaries.ItemsSource = null;
DgMappingProjConf.ItemsSource = null;
mProject = null;
GdMappingProjConf.IsEnabled = false;
break;
case MessageType.ProjectSaved:
mProjChanged = false;
break;
case MessageType.ProjectChanged:
if( data is ProjectModel projModel ) {
if( projModel != mProject )
mProject = projModel;
TiMappingProjConf.Header = mProject.ProjectName;
}
break;
case MessageType.DataReload:
if( data is ProjectModel reloadModel ) {
await _ReloadAllMappingData( reloadModel );
}
break;
// File Changed/Deleted/Updated
case MessageType.ProjectRenamed:
case MessageType.ProjectUpdated:
case MessageType.GlossaryNew:
case MessageType.GlossaryDeleted:
case MessageType.GlossaryRenamed:
case MessageType.GlossaryUpdated:
_ModifyBindingWhenFileChanged( type, data );
break;
case MessageType.XlatorSelected:
if( data is TranslatorSelector translatorSelector ) {
if( mCurrentXlator == translatorSelector )
break;
// different selector shall reload list!!
mCurrentXlator = translatorSelector;
if( mCurrentXlator != null )
mCurrentRemoteTranslator = mCurrentXlator.RemoteType;
await _ReloadAllMappingData( mProject );
}
break;
case MessageType.XlatingQuick:
case MessageType.XlatingSections:
if( data is bool onOffXlating ) {
GdMappingProjConf.IsEnabled = !onOffXlating;
}
break;
}
}
private void MappingModel_PropertyChanged( object sender, PropertyChangedEventArgs e )
{
var model = sender as MappingMonitor.MappingModel;
if( model == null )
return;
// sync. MappingModel with MappingEntry content
if( mProject != null && mProject.Project != null && mProject.Project.MappingTable != null &&
mProject.Project.MappingTable.Count > 0 &&
mProject.Project.MappingTable[0] is MappingMonitor.MappingModel == false ) {
var table = mProject.Project.MappingTable;
table.Clear();
table.AddRange( ProjectManager.Instance.MappingMonitor.GetMappingCollection( mProject.FullPathFileName ) );
}
_SetProjChanged();
}
private void MappingModelTables_CollectionChanged( object sender, NotifyCollectionChangedEventArgs e )
{
if( sender is ObservableList<MappingMonitor.MappingModel> coll ) {
if( mProject != null && mProject.Project != null ) {
var table = mProject.Project.MappingTable;
table.Clear();
table.AddRange( coll );
}
}
_SetProjChanged();
// no need update ListCollectionView in ItemsSource
}
private void TextBoxSearch_TextChanged( object sender, TextChangedEventArgs e )
{
var tb = sender as TextBox;
if( string.IsNullOrWhiteSpace( tb.Text ) == false )
return;
DataGrid dg = null;
if( sender == TbMappingProjConfSearch ) {
dg = DgMappingProjConf;
} else if( sender == TbMappingGlossariesToolSearch ) {
dg = DgMappingGlossaries;
} else if( sender == TbMappingAllSearch ) {
dg = DgMappingAll;
}
if( dg == null || dg.ItemsSource == null )
return;
ICollectionView cv = CollectionViewSource.GetDefaultView( dg.ItemsSource );
if( cv != null && cv.Filter != null ) {
dg.CancelEdit( DataGridEditingUnit.Row );
cv.Filter = null;
}
}
private void BtnMappingAllToolClearSorting_Click( object sender, RoutedEventArgs e )
{
DgMappingAll.ClearSort();
}
private async void BtnMappingProjConfNew_Click( object sender, RoutedEventArgs e )
{
var list = DgMappingProjConf.ItemsSource as ObservableList<MappingMonitor.MappingModel>;
if( list == null )
return;
var newOrig = await mMainWindow.ShowInputAsync( Languages.ProjectGlossary.Str0AddNewMapping,
Languages.ProjectGlossary.Str0NewOriginalText, sInputSettings );
// show warning about OriginalText is empty (it maybe full of whitespace characters!!)
if( string.IsNullOrEmpty( newOrig ) ) {
// user may cancel the Input dialog, so ignore null or empty newOrig directly
//await mMainWindow.ShowMessageAsync( Languages.ProjectGlossary.Str0OriginalTextError,
// Languages.ProjectGlossary.Str0OriginalTextShallNotEmpty );
return;
}
if( string.IsNullOrWhiteSpace( newOrig ) ) {
await mMainWindow.ShowMessageAsync( Languages.ProjectGlossary.Str0OriginalTextWarning,
Languages.ProjectGlossary.Str0OriginalTextWhitespaceTakeCare );
}
// show warning about OriginalText is only one word
if( newOrig.Length <= 1 ) {
await mMainWindow.ShowMessageAsync( Languages.ProjectGlossary.Str0OriginalTextWarning,
Languages.ProjectGlossary.Str0OriginalTextTooShortWarning );
}
// check orig is existed
var first = list.FirstOrDefault( item => item.OriginalText == newOrig );
if( first != null ) {
await mMainWindow.ShowMessageAsync( Languages.Global.Str0DuplicateText, string.Format( Languages.ProjectGlossary.Str1OriginalTextDupicatedWarning, newOrig ) );
DgMappingProjConf.SelectedItem = first;
return;
}
// add new Mapping entry to collection
var model = new MappingMonitor.MappingModel { OriginalText = newOrig, ProjectBasedFileName = mProject.FileName };
model.PropertyChanged += MappingModel_PropertyChanged;
mProject?.Project?.MappingTable?.Add( model );
list.Add( model );
_SetProjChanged();
// scroll to new Mapping entry
DgMappingProjConf.SelectedItem = model;
DgMappingProjConf.UpdateLayout();
DgMappingProjConf.ScrollIntoView( model );
}
private void BtnMappingProjConfDeleteEntry_Click( object sender, RoutedEventArgs e )
{
var entry = DgMappingProjConf.SelectedItem as MappingMonitor.MappingModel;
var list = DgMappingProjConf.ItemsSource as ObservableList<MappingMonitor.MappingModel>;
if( entry == null || list == null || list.Contains( entry ) == false )
return;
list.Remove( entry );
_SetProjChanged();
}
private void BtnMappingProjConfMoveUp_Click( object sender, RoutedEventArgs e )
{
var entry = DgMappingProjConf.SelectedItem as MappingMonitor.MappingModel;
var list = DgMappingProjConf.ItemsSource as ObservableList<MappingMonitor.MappingModel>;
if( entry == null || list == null || list.Contains( entry ) == false )
return;
var idx = list.IndexOf( entry );
if( idx <= 0 )
return;
list.Move( idx, idx - 1 );
_SetProjChanged();
}
private void BtnMappingProjConfMoveDown_Click( object sender, RoutedEventArgs e )
{
var entry = DgMappingProjConf.SelectedItem as MappingMonitor.MappingModel;
var list = DgMappingProjConf.ItemsSource as ObservableList<MappingMonitor.MappingModel>;
if( entry == null || list == null || list.Contains( entry ) == false )
return;
var idx = list.IndexOf( entry );
if( idx < 0 || idx >= list.Count - 1 )
return;
list.Move( idx, idx + 1 );
_SetProjChanged();
}
private void BtnMappingGlossariesToolClearSorting_Click( object sender, RoutedEventArgs e )
{
DgMappingGlossaries.ClearSort();
}
private void BtnMappingProjConfSearch_Click( object sender, RoutedEventArgs e )
{
_SearchText( TbMappingProjConfSearch.Text, DgMappingProjConf );
}
private void BtnMappingAllSearch_Click( object sender, RoutedEventArgs e )
{
_SearchText( TbMappingAllSearch.Text, DgMappingAll );
}
private void BtnMappingGlossariesToolSearch_Click( object sender, RoutedEventArgs e )
{
_SearchText( TbMappingGlossariesToolSearch.Text, DgMappingGlossaries );
}
private void DgMappingProjConf_SelectionChanged( object sender, SelectionChangedEventArgs e )
{
var en = DgMappingProjConf.SelectedItem != null;
BtnMappingProjConfDeleteEntry.IsEnabled = en;
BtnMappingProjConfMoveUp.IsEnabled = en;
BtnMappingProjConfMoveDown.IsEnabled = en;
}
}
}
| 33.200617 | 163 | 0.715859 | [
"MIT"
] | nuthrash/Minax | MinaxWebTranslator/MinaxWebTranslator.Desktop/Views/MappingDockingPanel.xaml.cs | 21,514 | C# |
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Configuration.Internal;
using Orleans.LeaseProviders;
namespace Orleans.Hosting
{
public static class SiloBuilderExtensions
{
/// <summary>
/// Configure silo to use azure queue persistent streams.
/// </summary>
public static ISiloHostBuilder AddAzureQueueStreams(this ISiloHostBuilder builder, string name,
Action<SiloAzureQueueStreamConfigurator> configure)
{
var configurator = new SiloAzureQueueStreamConfigurator(name,
configureServicesDelegate => builder.ConfigureServices(configureServicesDelegate),
configureAppPartsDelegate => builder.ConfigureApplicationParts(configureAppPartsDelegate));
configure?.Invoke(configurator);
return builder;
}
/// <summary>
/// Configure silo to use azure queue persistent streams with default settings
/// </summary>
public static ISiloHostBuilder AddAzureQueueStreams(this ISiloHostBuilder builder, string name, Action<OptionsBuilder<AzureQueueOptions>> configureOptions)
{
builder.AddAzureQueueStreams(name, b =>
b.ConfigureAzureQueue(configureOptions));
return builder;
}
/// <summary>
/// Configure silo to use azure queue persistent streams.
/// </summary>
public static ISiloBuilder AddAzureQueueStreams(this ISiloBuilder builder, string name,
Action<SiloAzureQueueStreamConfigurator> configure)
{
var configurator = new SiloAzureQueueStreamConfigurator(name,
configureServicesDelegate => builder.ConfigureServices(configureServicesDelegate),
configureAppPartsDelegate => builder.ConfigureApplicationParts(configureAppPartsDelegate));
configure?.Invoke(configurator);
return builder;
}
/// <summary>
/// Configure silo to use azure queue persistent streams with default settings
/// </summary>
public static ISiloBuilder AddAzureQueueStreams(this ISiloBuilder builder, string name, Action<OptionsBuilder<AzureQueueOptions>> configureOptions)
{
builder.AddAzureQueueStreams(name, b =>
b.ConfigureAzureQueue(configureOptions));
return builder;
}
/// <summary>
/// Configure silo to use azure blob lease provider
/// </summary>
public static ISiloBuilder UseAzureBlobLeaseProvider(this ISiloBuilder builder, Action<OptionsBuilder<AzureBlobLeaseProviderOptions>> configureOptions)
{
builder.ConfigureServices(services => ConfigureAzureBlobLeaseProviderServices(services, configureOptions));
return builder;
}
/// <summary>
/// Configure silo to use azure blob lease provider
/// </summary>
public static ISiloHostBuilder UseAzureBlobLeaseProvider(this ISiloHostBuilder builder, Action<OptionsBuilder<AzureBlobLeaseProviderOptions>> configureOptions)
{
builder.ConfigureServices(services => ConfigureAzureBlobLeaseProviderServices(services, configureOptions));
return builder;
}
private static void ConfigureAzureBlobLeaseProviderServices(IServiceCollection services, Action<OptionsBuilder<AzureBlobLeaseProviderOptions>> configureOptions)
{
configureOptions?.Invoke(services.AddOptions<AzureBlobLeaseProviderOptions>());
services.AddTransient<IConfigurationValidator, AzureBlobLeaseProviderOptionsValidator>();
services.ConfigureFormatter<AzureBlobLeaseProviderOptions>();
services.AddTransient<AzureBlobLeaseProvider>();
services.AddFromExisting<ILeaseProvider, AzureBlobLeaseProvider>();
}
/// <summary>
/// Configure silo to use azure blob lease provider
/// </summary>
public static void UseAzureBlobLeaseProvider(this ISiloPersistentStreamConfigurator configurator, Action<OptionsBuilder<AzureBlobLeaseProviderOptions>> configureOptions)
{
configurator.ConfigureDelegate(services =>
{
services.AddTransient(sp => AzureBlobLeaseProviderOptionsValidator.Create(sp, configurator.Name));
});
configurator.ConfigureComponent(AzureBlobLeaseProvider.Create, configureOptions);
}
}
}
| 46.530612 | 177 | 0.691447 | [
"MIT"
] | alexanderfedin/orleans | src/Azure/Orleans.Streaming.AzureStorage/Hosting/SiloBuilderExtensions.cs | 4,560 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Cadastro.Cliente
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.851852 | 70 | 0.646132 | [
"MIT"
] | dfcallili/CadastroClientes | Cadastro.Cliente/Program.cs | 698 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Nest
{
public class ReindexNode
{
[JsonProperty("name")]
public string Name { get; internal set; }
[JsonProperty("transport_address")]
public string TransportAddress { get; internal set; }
[JsonProperty("host")]
public string Host { get; internal set; }
[JsonProperty("ip")]
public string Ip { get; internal set; }
[JsonProperty("attributes")]
[JsonConverter(typeof(VerbatimDictionaryKeysJsonConverter))]
public Dictionary<string, string> Attributes { get; internal set; }
[JsonProperty("tasks")]
[JsonConverter(typeof(VerbatimDictionaryKeysJsonConverter))]
public Dictionary<TaskId, ReindexTask> Tasks { get; internal set; }
}
public class ReindexTask
{
[JsonProperty("node")]
public string Node { get; internal set; }
[JsonProperty("id")]
public long Id { get; internal set; }
[JsonProperty("type")]
public string Type { get; internal set; }
[JsonProperty("action")]
public string Action { get; internal set; }
[JsonProperty("status")]
public ReindexStatus Status { get; internal set; }
[JsonProperty("description")]
public string Description { get; internal set; }
[JsonProperty("start_time_in_millis")]
public long StartTimeInMilliseconds { get; internal set; }
[JsonProperty("running_time_in_nanos")]
public long RunningTimeInNanoseconds { get; internal set; }
}
public class ReindexStatus
{
[JsonProperty("total")]
public long Total { get; internal set; }
[JsonProperty("updated")]
public long Updated { get; internal set; }
[JsonProperty("created")]
public long Created { get; internal set; }
[JsonProperty("deleted")]
public long Deleted { get; internal set; }
[JsonProperty("batches")]
public long Batches { get; internal set; }
[JsonProperty("version_conflicts")]
public long VersionConflicts { get; internal set; }
[JsonProperty("noops")]
public long Noops { get; internal set; }
[JsonProperty("retries")]
public long Retries { get; internal set; }
[JsonProperty("throttled_millis")]
public long ThrottledInMilliseconds { get; internal set; }
[JsonProperty("requests_per_second")]
[JsonConverter(typeof(RequestsPerSecondConverter))]
public float RequestsPerSecond { get; internal set; }
[JsonProperty("throttled_until_millis")]
public long ThrottledUntilInMilliseconds { get; internal set; }
}
internal class RequestsPerSecondConverter : JsonConverter
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Integer)
return (float)reader.Value;
if (reader.TokenType == JsonToken.String)
{
var value = (string)reader.Value;
if (value == "unlimited")
return float.PositiveInfinity;
}
throw new JsonSerializationException($"cannot convert '{reader.Value}' to float");
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(float);
}
}
}
| 26.152 | 118 | 0.720098 | [
"Apache-2.0"
] | BedeGaming/elasticsearch-net | src/Nest/Document/Multiple/ReindexRethrottle/ReindexNode.cs | 3,271 | C# |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class HUD : MonoBehaviour {
public Sprite[] HealthSprites;
public Image HealthUI;
private Player plr;
// Use this for initialization
void Start () {
plr = GameObject.FindGameObjectWithTag ("Player").GetComponent<Player>();
}
// Update is called once per frame
void Update () {
if (plr.curHP >= 0 && plr.curHP <= 5)
HealthUI.sprite = HealthSprites [plr.curHP];
}
}
| 21.904762 | 75 | 0.706522 | [
"MIT"
] | marcelofg55/UnityOAMLdemo | Assets/Scripts/HUD.cs | 462 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using HUDEditor.Models;
namespace HUDEditor.Classes
{
/// <summary>
/// Sample Animation Script
/// Commands:
/// Animate (panel name) (variable) (target value) (interpolator) (start time) (duration)
/// Variables:
/// FgColor
/// BgColor
/// Position
/// Size
/// Blur (HUD panels only)
/// TextColor (HUD panels only)
/// Ammo2Color (HUD panels only)
/// Alpha (HUD weapon selection only)
/// SelectionAlpha (HUD weapon selection only)
/// TextScan (HUD weapon selection only)
/// Interpolator:
/// Linear
/// Accel - starts moving slow, ends fast
/// Deaccel - starts moving fast, ends slow
/// Spline - simple ease in/out curve
/// Pulse - ( freq ) over the duration, the value is pulsed (cosine) freq times ending at the dest value (assuming freq
/// is integral)
/// Flicker - ( randomness factor 0.0 to 1.0 ) over duration, each frame if random # is less than factor, use end
/// value, otherwise use prev value
/// Gain - ( bias ) Lower bias values bias towards 0.5 and higher bias values bias away from it.
/// Bias - ( bias ) Lower values bias the curve towards 0 and higher values bias it towards 1.
/// RunEvent (event name) (start time) - starts another even running at the specified time
/// StopEvent (event name) (start time) - stops another event that is current running at the specified time
/// StopAnimation (panel name) (variable) (start time) - stops all animations referring to the specified variable in
/// the specified panel
/// StopPanelAnimations (panel name) (start time) - stops all active animations operating on the specified panel
/// SetFont (panel name) (fontparameter) (fontname from scheme) (set time)
/// SetTexture (panel name) (textureidname) (texturefilename) (set time)
/// SetString (panel name) (string varname) (stringvalue) (set time)
/// </summary>
internal static class HUDAnimations
{
public static Dictionary<string, List<HUDAnimation>> Parse(string text)
{
var index = 0;
char[] ignoredCharacters = {' ', '\t', '\r', '\n'};
string Next(bool lookAhead = false)
{
var currentToken = "";
var x = index;
// Return EOF if we've reached the end of the text file.
if (x >= text.Length - 1) return "EOF";
// Discard any text that is preempted by a comment tag (//) until the next line.
while ((ignoredCharacters.Contains(text[x]) || text[x] == '/') && x < text.Length - 1)
{
if (text[x] == '/')
{
if (text[x + 1] == '/')
while (text[x] != '\n' && x < text.Length - 1)
x++;
}
else
x++;
if (x >= text.Length) return "EOF";
}
// If we encounter a quote, read the enclosed text until the next quotation mark.
if (text[x] == '"')
{
// Skip the opening quotation mark.
x++;
while (text[x] != '"' && x < text.Length - 1)
{
if (text[x] == '\n') throw new Exception($"Unexpected end of line at position {x}");
currentToken += text[x];
x++;
}
// Skip the closing quotation mark.
x++;
}
else
{
// Read the text until reaching whitespace or an end of the file.
while (x < text.Length && !ignoredCharacters.Contains(text[x]))
{
if (text[x] == '"') throw new Exception($"Unexpected double quote at position {x}");
currentToken += text[x];
x++;
}
}
if (!lookAhead) index = x;
return currentToken;
}
Dictionary<string, List<HUDAnimation>> ParseFile()
{
Dictionary<string, List<HUDAnimation>> animations = new();
var currentToken = Next();
while (string.Equals(currentToken, "event", StringComparison.CurrentCultureIgnoreCase))
{
var eventName = Next();
animations[eventName] = ParseEvent();
currentToken = Next();
}
return animations;
}
List<HUDAnimation> ParseEvent()
{
List<HUDAnimation> events = new();
var nextToken = Next();
if (string.Equals(nextToken, "{"))
while (nextToken != "}" && nextToken != "EOF")
{
// NextToken is not a closing brace therefore it is the animation type.
// Pass the animation type to the animation.
nextToken = Next();
if (nextToken != "}") events.Add(ParseAnimation(nextToken));
}
else
throw new Exception($"Unexpected ${nextToken} at position {index}! Are you missing an opening brace?");
return events;
}
void SetInterpolator(Animate animation)
{
var interpolator = Next().ToLower();
if (string.Equals(interpolator, "pulse", StringComparison.CurrentCultureIgnoreCase))
{
animation.Interpolator = interpolator;
animation.Frequency = Next();
}
else if (new[] {"gain", "bias"}.Contains(interpolator))
{
animation.Interpolator = interpolator[0].ToString().ToUpper() + interpolator[1..];
animation.Bias = Next();
}
else
{
animation.Interpolator = interpolator;
}
}
HUDAnimation ParseAnimation(string type)
{
dynamic animation;
type = type.ToLower();
switch (type)
{
case "animate":
animation = new Animate();
animation.Type = type;
animation.Element = Next();
animation.Property = Next();
animation.Value = Next();
SetInterpolator(animation);
animation.Delay = Next();
animation.Duration = Next();
break;
case "runevent":
animation = new RunEvent();
animation.Type = type;
animation.Event = Next();
animation.Delay = Next();
break;
case "stopevent":
animation = new StopEvent();
animation.Type = type;
animation.Event = Next();
animation.Delay = Next();
break;
case "setvisible":
animation = new SetVisible();
animation.Type = type;
animation.Element = Next();
animation.Delay = Next();
animation.Duration = Next();
break;
case "firecommand":
animation = new FireCommand();
animation.Type = type;
animation.Delay = Next();
animation.Command = Next();
break;
case "runeventchild":
animation = new RunEventChild();
animation.Type = type;
animation.Element = Next();
animation.Event = Next();
animation.Delay = Next();
break;
case "setinputenabled":
animation = new SetInputEnabled();
animation.Element = Next();
animation.Visible = int.Parse(Next());
animation.Delay = Next();
break;
case "playsound":
animation = new PlaySound();
animation.Delay = Next();
animation.Sound = Next();
break;
case "stoppanelanimations":
animation = new StopPanelAnimations();
animation.Element = Next();
animation.Delay = Next();
break;
default:
Debug.WriteLine(text.Substring(index - 25, 25));
throw new Exception($"Unexpected {type} at position {index}");
}
if (Next(true).StartsWith('[')) animation.OSTag = Next();
return animation;
}
return ParseFile();
}
public static string Stringify(Dictionary<string, List<HUDAnimation>> animations)
{
var stringValue = "";
const char tab = '\t';
const string newLine = "\r\n";
static string FormatWhiteSpace(string text)
{
return Regex.IsMatch(text, "\\s") ? $"\"{text}\"" : text;
}
static string GetInterpolator(Animate animation)
{
return animation.Interpolator.ToLower() switch
{
"Pulse" => $"Pulse {animation.Frequency}",
"Gain" or "Bias" => $"Gain {animation.Bias}",
_ => $"{animation.Interpolator}"
};
}
foreach (var key in animations.Keys)
{
stringValue += $"event {key}{newLine}{{{newLine}";
foreach (dynamic animation in animations[key])
{
stringValue += tab;
Type T = animation.GetType();
if (T == typeof(Animate))
stringValue +=
$"Animate {FormatWhiteSpace(animation.Element)} {FormatWhiteSpace(animation.Property)} {FormatWhiteSpace(animation.Value)} {GetInterpolator(animation)} {animation.Delay} {animation.Duration}";
else if (T == typeof(RunEvent) || T == typeof(StopEvent))
stringValue += $"RunEvent {FormatWhiteSpace(animation.Event)} {animation.Delay}";
else if (T == typeof(StopEvent))
stringValue += $"StopEvent {FormatWhiteSpace(animation.Event)} {animation.Delay}";
else if (T == typeof(SetVisible))
stringValue +=
$"SetVisible {FormatWhiteSpace(animation.Element)} {animation.Delay} {animation.Duration}";
else if (T == typeof(FireCommand))
stringValue += $"FireCommand {animation.Delay} {FormatWhiteSpace(animation.Command)}";
else if (T == typeof(RunEventChild))
stringValue +=
$"RunEventChild {FormatWhiteSpace(animation.Element)} {FormatWhiteSpace(animation.Event)} {animation.Delay}";
else if (T == typeof(SetVisible))
stringValue +=
$"SetVisible {FormatWhiteSpace(animation.Element)} {animation.Visible} {animation.Delay}";
else if (T == typeof(PlaySound))
stringValue += $"PlaySound {animation.Delay} {FormatWhiteSpace(animation.Sound)}";
if (animation.OSTag != null) stringValue += " " + animation.OSTag;
stringValue += newLine;
}
stringValue += $"}}{newLine}";
}
return stringValue;
}
}
} | 43.199324 | 220 | 0.459529 | [
"MIT"
] | Zeesastrous/TF2HUD.Editor | src/TF2HUD.Editor/Classes/HUD/HUDAnimations.cs | 12,787 | C# |
using Newtonsoft.Json;
namespace Tfl.Api.Presentation.Entities
{
public class NetworkStatus
{
[JsonProperty(PropertyName = "operator")]
public string Operator { get; set; }
[JsonProperty(PropertyName = "status")]
public string Status { get; set; }
[JsonProperty(PropertyName = "message")]
public string Message { get; set; }
[JsonProperty(PropertyName = "statusLevel")]
public int? StatusLevel { get; set; }
}
} | 25.842105 | 52 | 0.625255 | [
"MIT"
] | tnc1997/dotnet-multi-objective-shortest-path | Tfl.Api.Presentation.Entities/NetworkStatus.cs | 491 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _05.World_in_plural
{
class Program
{
static void Main(string[] args)
{
string word = Console.ReadLine();
if (word.EndsWith("y"))
{
word = word.Remove(word.Length - 1);
Console.WriteLine($"{word}ies");
}
else if (word.EndsWith("o") || word.EndsWith("ch") || word.EndsWith("s")
|| word.EndsWith("sh") || word.EndsWith("x") || word.EndsWith("z"))
{
Console.WriteLine($"{word}es");
}
else
{
Console.WriteLine($"{word}s");
}
}
}
}
| 18.69697 | 75 | 0.614263 | [
"MIT"
] | stanislaviv/Programming-Fundamentals-May-2017 | 02_Conditional-Statements-and-Loops/Conditional State-s Loops/05. World in plural/05. World in plural.cs | 619 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int contador = 1;
do
{
Console.WriteLine("Esta es la vez numero " + contador + " que pasa por aqui");
contador++;
} while (contador < 10);
Console.ReadKey();
}
}
} | 22 | 95 | 0.507905 | [
"MIT"
] | mauriciomejiae/do-while | do while/Program.cs | 508 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OldMSBuildConsoleApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OldMSBuildConsoleApp")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bda3df45-d8d4-43cf-b8c0-459632a42fbf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.054054 | 84 | 0.75071 | [
"MIT"
] | kekyo/VS2019Migration | OldMSBuildConsoleApp/Properties/AssemblyInfo.cs | 1,411 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
/// <summary> Delimited text read settings. </summary>
public partial class DelimitedTextReadSettings : FormatReadSettings
{
/// <summary> Initializes a new instance of DelimitedTextReadSettings. </summary>
public DelimitedTextReadSettings()
{
Type = "DelimitedTextReadSettings";
}
/// <summary> Initializes a new instance of DelimitedTextReadSettings. </summary>
/// <param name="type"> The read setting type. </param>
/// <param name="additionalProperties"> Additional Properties. </param>
/// <param name="skipLineCount"> Indicates the number of non-empty rows to skip when reading data from input files. Type: integer (or Expression with resultType integer). </param>
/// <param name="compressionProperties"> Compression settings. </param>
internal DelimitedTextReadSettings(string type, IDictionary<string, object> additionalProperties, object skipLineCount, CompressionReadSettings compressionProperties) : base(type, additionalProperties)
{
SkipLineCount = skipLineCount;
CompressionProperties = compressionProperties;
Type = type ?? "DelimitedTextReadSettings";
}
/// <summary> Indicates the number of non-empty rows to skip when reading data from input files. Type: integer (or Expression with resultType integer). </summary>
public object SkipLineCount { get; set; }
/// <summary> Compression settings. </summary>
public CompressionReadSettings CompressionProperties { get; set; }
}
}
| 46.538462 | 209 | 0.698623 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/DelimitedTextReadSettings.cs | 1,815 | C# |
using System;
using System.Collections.Generic;
using Disqord.Models;
namespace Disqord
{
/// <inheritdoc cref="IBearerAuthorization"/>
public class TransientBearerAuthorization : TransientEntity<AuthorizationJsonModel>, IBearerAuthorization
{
/// <inheritdoc/>
public IApplication Application => _application ??= new TransientApplication(Client, Model.Application);
private IApplication _application;
/// <inheritdoc/>
public IReadOnlyList<string> Scopes => Model.Scopes;
/// <inheritdoc/>
public DateTimeOffset ExpiresAt => Model.Expires;
/// <inheritdoc/>
public IUser User
{
get
{
if (!Model.User.HasValue)
return null;
return _user ??= new TransientUser(Client, Model.User.Value);
}
}
private IUser _user;
public TransientBearerAuthorization(IClient client, AuthorizationJsonModel model)
: base(client, model)
{ }
}
}
| 28.815789 | 113 | 0.588128 | [
"MIT"
] | Neuheit/Diqnod | src/Disqord.Core/Entities/Shared/Transient/TransientBearerAuthorization.cs | 1,097 | C# |
// This file was generated based on Library/Core/UnoCore/Source/Uno/Rect.uno.
// WARNING: Changes might be lost if you edit this file directly.
namespace Uno
{
[global::Uno.Compiler.ExportTargetInterop.DotNetTypeAttribute(null)]
public struct Rect
{
public float Left;
public float Top;
public float Right;
public float Bottom;
public Rect(float left, float top, float right, float bottom)
{
this.Left = left;
this.Top = top;
this.Right = right;
this.Bottom = bottom;
}
public Rect(Float2 pos, Float2 size)
{
this.Left = pos.X;
this.Top = pos.Y;
this.Right = float.IsInfinity(size.X) ? size.X : (this.Left + size.X);
this.Bottom = float.IsInfinity(size.Y) ? size.Y : (this.Top + size.Y);
}
public static bool Equals(Rect rect1, Rect rect2)
{
return (((rect1.Left == rect2.Left) && (rect1.Top == rect2.Top)) && (rect1.Right == rect2.Right)) && (rect1.Bottom == rect2.Bottom);
}
public bool Contains(Rect r)
{
return (((this.Left <= r.Left) && (this.Right >= r.Right)) && (this.Top <= r.Top)) && (this.Bottom >= r.Bottom);
}
public bool Contains(Float2 p)
{
return (((this.Left <= p.X) && (this.Right >= p.X)) && (this.Top <= p.Y)) && (this.Bottom >= p.Y);
}
public bool Intersects(Rect r)
{
return !((((r.Left > this.Right) || (r.Right < this.Left)) || (r.Top > this.Bottom)) || (r.Bottom < this.Top));
}
public override string ToString()
{
return (((((this.Left.ToString() + ", ") + this.Top.ToString()) + ", ") + this.Right.ToString()) + ", ") + this.Bottom.ToString();
}
public static Rect Union(Rect a, Rect b)
{
return new Rect(Math.Min(a.Left, b.Left), Math.Min(a.Top, b.Top), Math.Max(a.Right, b.Right), Math.Max(a.Bottom, b.Bottom));
}
public static Rect Intersect(Rect a, Rect b)
{
return new Rect(Math.Max(a.Left, b.Left), Math.Max(a.Top, b.Top), Math.Min(a.Right, b.Right), Math.Min(a.Bottom, b.Bottom));
}
public static Rect Translate(Rect r, Float2 offset)
{
return new Rect(r.Left + offset.X, r.Top + offset.Y, r.Right + offset.X, r.Bottom + offset.Y);
}
public static Rect Scale(Rect r, Float2 scale)
{
return new Rect(r.Left * scale.X, r.Top * scale.Y, r.Right * scale.X, r.Bottom * scale.Y);
}
public static Rect Scale(Rect r, float scale)
{
return Rect.Scale(r, new Float2(scale, scale));
}
public static Rect Inflate(Rect r, Float2 size)
{
return new Rect(r.Left - size.X, r.Top - size.Y, r.Right + size.X, r.Bottom + size.Y);
}
public static Rect Inflate(Rect r, float size)
{
return Rect.Inflate(r, new Float2(size, size));
}
public static Rect ContainingPoints(Float2 point0, Float2 point1)
{
float minX = point0.X;
float maxX = point0.X;
float minY = point0.Y;
float maxY = point0.Y;
minX = Math.Min(minX, point1.X);
maxX = Math.Max(maxX, point1.X);
minY = Math.Min(minY, point1.Y);
maxY = Math.Max(maxY, point1.Y);
return new Rect(minX, minY, maxX, maxY);
}
public static Rect ContainingPoints(Float2 point0, Float2 point1, Float2 point2, Float2 point3)
{
float minX = point0.X;
float maxX = point0.X;
float minY = point0.Y;
float maxY = point0.Y;
minX = Math.Min(minX, point1.X);
maxX = Math.Max(maxX, point1.X);
minY = Math.Min(minY, point1.Y);
maxY = Math.Max(maxY, point1.Y);
minX = Math.Min(minX, point2.X);
maxX = Math.Max(maxX, point2.X);
minY = Math.Min(minY, point2.Y);
maxY = Math.Max(maxY, point2.Y);
minX = Math.Min(minX, point3.X);
maxX = Math.Max(maxX, point3.X);
minY = Math.Min(minY, point3.Y);
maxY = Math.Max(maxY, point3.Y);
return new Rect(minX, minY, maxX, maxY);
}
public bool IsInfinite
{
get { return ((float.IsInfinity(this.Left) || float.IsInfinity(this.Top)) || float.IsInfinity(this.Right)) || float.IsInfinity(this.Bottom); }
}
public Float2 Minimum
{
get { return new Float2(this.Left, this.Top); }
set
{
this.Left = value.X;
this.Top = value.Y;
}
}
public Float2 Maximum
{
get { return new Float2(this.Right, this.Bottom); }
set
{
this.Right = value.X;
this.Bottom = value.Y;
}
}
public Float2 Center
{
get { return new Float2(this.Left + this.Right, this.Top + this.Bottom) * 0.5f; }
}
public Float2 LeftTop
{
get { return new Float2(this.Left, this.Top); }
}
public Float2 RightTop
{
get { return new Float2(this.Right, this.Top); }
}
public Float2 LeftBottom
{
get { return new Float2(this.Left, this.Bottom); }
}
public Float2 RightBottom
{
get { return new Float2(this.Right, this.Bottom); }
}
public Float2 Position
{
get { return this.Minimum; }
set
{
Float2 sz = this.Size;
this.Left = value.X;
this.Top = value.Y;
this.Size = sz;
}
}
public float Width
{
get { return float.IsInfinity(this.Right) ? this.Right : (this.Right - this.Left); }
set { this.Right = float.IsInfinity(value) ? value : (this.Left + value); }
}
public float Height
{
get { return float.IsInfinity(this.Bottom) ? this.Bottom : (this.Bottom - this.Top); }
set { this.Bottom = float.IsInfinity(value) ? value : (this.Top + value); }
}
public Float2 Size
{
get { return new Float2(this.Width, this.Height); }
set
{
this.Width = value.X;
this.Height = value.Y;
}
}
public float Area
{
get { return this.Width * this.Height; }
}
public static implicit operator Rect(Recti r)
{
return new Rect((float)r.Left, (float)r.Top, (float)r.Right, (float)r.Bottom);
}
}
}
| 31.684932 | 154 | 0.50209 | [
"MIT"
] | devadiab/uno | src/runtime/Uno.Runtime.Core/Uno/Rect.cs | 6,939 | C# |
using UnityEngine;
namespace LunaClient.Windows.Locks
{
public partial class LocksWindow
{
public override void DrawWindowContent(int windowId)
{
GUILayout.BeginVertical();
GUI.DragWindow(MoveRect);
GUILayout.BeginHorizontal();
GUILayout.EndHorizontal();
ScrollPos = GUILayout.BeginScrollView(ScrollPos, GUILayout.Width(WindowWidth - 5), GUILayout.Height(WindowHeight - 100));
PrintLocks();
GUILayout.EndScrollView();
GUILayout.EndVertical();
}
private void PrintLocks()
{
GUILayout.Label("Asteroid owner: " + _asteroidLockOwner, LabelStyle);
GUILayout.Space(10);
for (var i = 0; i < VesselLocks.Count; i++)
{
VesselLocks[i].Selected = GUILayout.Toggle(VesselLocks[i].Selected, VesselLocks[i].VesselId.ToString(), ButtonStyle);
if (VesselLocks[i].Selected)
{
GUILayout.Label(CreateLockText(VesselLocks[i]), LabelStyle);
}
}
}
private static string CreateLockText(VesselLockDisplay vesselLock)
{
StrBuilder.Length = 0;
StrBuilder.AppendLine(vesselLock.VesselName)
.Append("Loaded: ").Append(vesselLock.Loaded).AppendLine()
.Append("Packed: ").Append(vesselLock.Packed).AppendLine()
.Append("Control: ").Append(vesselLock.ControlLockOwner).AppendLine()
.Append("Update: ").Append(vesselLock.UpdateLockOwner).AppendLine()
.Append("UnlUpdate: ").Append(vesselLock.UnloadedUpdateLockOwner).AppendLine()
.Append("Exists in store: ").Append(vesselLock.ExistsInStore);
return StrBuilder.ToString();
}
}
}
| 35.150943 | 133 | 0.587225 | [
"MIT"
] | Sladernimo/LunaMultiplayer | Client/Windows/Locks/LocksDrawer.cs | 1,865 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Ryooka.Scripts.General {
public static class QuaternionR {
public static Quaternion Average(IEnumerable<Quaternion> qs) {
int length = qs.Count();
if (length == 0) return Quaternion.identity;
if (length == 1) return qs.ElementAt(0);
Vector4 cumulative = Vector4.zero;
Quaternion init = qs.ElementAt(0);
return qs.Where((_, i) => i > 0).Aggregate((_, q) =>
Math3d.AverageQuaternion(ref cumulative, q, init, length));
}
public static Quaternion Zip(Quaternion one, Quaternion two, Func<float, float, float> f) {
return new Quaternion(f(one.x, two.x), f(one.y, two.y), f(one.z, two.z), f(one.w, two.w));
}
public static Quaternion Map(this Quaternion self, Func<float, float> f) {
return new Quaternion(f(self.x), f(self.y), f(self.z), f(self.w));
}
public static Quaternion Smooth(this Quaternion self, Quaternion previous, float amount) {
Quaternion pq = previous;
Quaternion cq = self;
Quaternion rq = Quaternion.identity;
rq.x = MathR.Smooth(cq.x, pq.x, amount);
rq.y = MathR.Smooth(cq.y, pq.y, amount);
rq.z = MathR.Smooth(cq.z, pq.z, amount);
rq.w = MathR.Smooth(cq.w, pq.w, amount);
return rq;
}
}
}
| 33.358974 | 93 | 0.681015 | [
"MIT"
] | ryo0ka/Sightsync | Assets/Ryooka/Scripts/General/QuaternionR.cs | 1,303 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DISClient_4.5")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DISClient_4.5")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("33a7b945-8f12-43b3-bc8d-88313d14b777")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 39.333333 | 84 | 0.747881 | [
"Apache-2.0"
] | huaweicloud/huaweicloud-sdk-net-dis | DotNet/DISClient_4.5/Properties/AssemblyInfo.cs | 1,419 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace GPUImageViewer
{
/// <summary>
/// Логика взаимодействия для App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.444444 | 42 | 0.710843 | [
"MIT"
] | Boris-Barboris/GPUImageViewer | App.xaml.cs | 357 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Valve.VR
{
using System;
using UnityEngine;
public class SteamVR_Input_ActionSet_default : Valve.VR.SteamVR_ActionSet
{
public virtual SteamVR_Action_Boolean InteractUI
{
get
{
return SteamVR_Actions.default_InteractUI;
}
}
public virtual SteamVR_Action_Boolean Teleport
{
get
{
return SteamVR_Actions.default_Teleport;
}
}
public virtual SteamVR_Action_Boolean GrabPinch
{
get
{
return SteamVR_Actions.default_GrabPinch;
}
}
public virtual SteamVR_Action_Boolean GrabGrip
{
get
{
return SteamVR_Actions.default_GrabGrip;
}
}
public virtual SteamVR_Action_Pose Pose
{
get
{
return SteamVR_Actions.default_Pose;
}
}
public virtual SteamVR_Action_Skeleton SkeletonLeftHand
{
get
{
return SteamVR_Actions.default_SkeletonLeftHand;
}
}
public virtual SteamVR_Action_Skeleton SkeletonRightHand
{
get
{
return SteamVR_Actions.default_SkeletonRightHand;
}
}
public virtual SteamVR_Action_Single Squeeze
{
get
{
return SteamVR_Actions.default_Squeeze;
}
}
public virtual SteamVR_Action_Boolean HeadsetOnHead
{
get
{
return SteamVR_Actions.default_HeadsetOnHead;
}
}
public virtual SteamVR_Action_Boolean SnapTurnLeft
{
get
{
return SteamVR_Actions.default_SnapTurnLeft;
}
}
public virtual SteamVR_Action_Boolean SnapTurnRight
{
get
{
return SteamVR_Actions.default_SnapTurnRight;
}
}
public virtual SteamVR_Action_Boolean MenuClick
{
get
{
return SteamVR_Actions.default_MenuClick;
}
}
public virtual SteamVR_Action_Vibration Haptic
{
get
{
return SteamVR_Actions.default_Haptic;
}
}
}
}
| 24.176 | 80 | 0.463269 | [
"Unlicense"
] | SpicyGarlicAlbacoreRoll/AK_ATV | AK_ATV_Simulator/Assets/SteamVR_Input/ActionSetClasses/SteamVR_Input_ActionSet_default.cs | 3,022 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Internal.Reflection.Core.Execution;
// This file contains System.Private.TypeLoader dependencies. Since we're not porting that for now,
// we declare the dependencies here.
namespace Internal.TypeSystem
{
public enum CanonicalFormKind
{
Specific,
Universal,
}
}
namespace Internal.Runtime.TypeLoader
{
using Internal.TypeSystem;
public struct CanonicallyEquivalentEntryLocator
{
RuntimeTypeHandle _typeToFind;
public CanonicallyEquivalentEntryLocator(RuntimeTypeHandle typeToFind, CanonicalFormKind kind)
{
_typeToFind = typeToFind;
}
public int LookupHashCode
{
get
{
return _typeToFind.GetHashCode();
}
}
public bool IsCanonicallyEquivalent(RuntimeTypeHandle other)
{
return _typeToFind.Equals(other);
}
}
} | 24.425532 | 102 | 0.669861 | [
"MIT"
] | ZZHGit/corert | src/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/TypeLoaderDependencies.cs | 1,148 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace DTFiniteGraphMachine {
public partial class GraphAssetEditorWindow : EditorWindow {
private enum TransitionViewStyle {
NORMAL = 1,
SEMI_HIGHLIGHTED = 2,
HIGHLIGHTED = 3
}
private static class TransitionViewStyleUtil {
public static Color GetColor(TransitionViewStyle style) {
switch (style) {
case TransitionViewStyle.SEMI_HIGHLIGHTED:
return ColorUtil.HexStringToColor("#EFD9A6");
case TransitionViewStyle.HIGHLIGHTED:
return ColorUtil.HexStringToColor("#EEBE4D");
case TransitionViewStyle.NORMAL:
default:
return ColorUtil.HexStringToColor("#FFFFFF");
}
}
public static GUIStyle GetArrowStyle(TransitionViewStyle style) {
switch (style) {
case TransitionViewStyle.SEMI_HIGHLIGHTED:
return (GUIStyle)"TransitionArrowSemiHighlighted";
case TransitionViewStyle.HIGHLIGHTED:
return (GUIStyle)"TransitionArrowHighlighted";
case TransitionViewStyle.NORMAL:
default:
return (GUIStyle)"TransitionArrowNormal";
}
}
}
}
} | 30.714286 | 71 | 0.668217 | [
"MIT"
] | DarrenTsung/finite-graph-machine | FiniteGraphMachine/Editor/EditorWindow/GraphAssetEditorWindow.TransitionViewStyle.cs | 1,290 | C# |
using System.Text;
using Uno.Compiler.API.Domain.IL.Types;
namespace Uno.Compiler.API.Domain.IL.Expressions
{
public sealed class CallDelegate : CallExpression
{
public Expression[] Arguments;
public CallDelegate(Source src, Expression obj, params Expression[] args)
: base(src)
{
Object = obj;
Arguments = args;
}
public override ExpressionType ExpressionType => ExpressionType.CallDelegate;
public DelegateType DelegateType => (DelegateType)Object.ReturnType;
public override DataType ReturnType => DelegateType.ReturnType;
public override Function Function => DelegateType.Function;
public override void Disassemble(StringBuilder sb, ExpressionUsage u)
{
Object.Disassemble(sb, ExpressionUsage.Object);
sb.Append("(");
for (int i = 0; i < Arguments.Length; i++)
{
sb.CommaWhen(i > 0);
Arguments[i].Disassemble(sb);
}
sb.Append(")");
}
public override void Visit(Pass p, ExpressionUsage u)
{
p.Begin(ref Object, ExpressionUsage.Object);
Object.Visit(p, ExpressionUsage.Object);
p.End(ref Object, ExpressionUsage.Object);
for (int i = 0; i < Arguments.Length; i++)
{
p.Begin(ref Arguments[i]);
Arguments[i].Visit(p);
p.End(ref Arguments[i]);
}
}
public override Expression CopyExpression(CopyState state)
{
return new CallDelegate(Source, Object.CopyExpression(state), Arguments.Copy(state));
}
}
} | 29.844828 | 97 | 0.577123 | [
"MIT"
] | Nicero/uno | src/compiler/api/Domain/IL/Expressions/CallDelegate.cs | 1,731 | C# |
using DadSimulator.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace DadSimulator.Tests
{
public class GraphicsLoader
{
private static readonly ITemplateLoader m_loader;
static GraphicsLoader()
{
var sim = new DadSimulator();
sim.RunOneFrame();
m_loader = sim;
}
public static Texture2D LoadTemplate(Templates name)
{
return m_loader.LoadTemplate(name);
}
public static Color[,] LoadTemplateContent(Templates name)
{
return m_loader.LoadTemplateContent(name);
}
}
}
| 23.464286 | 66 | 0.611872 | [
"MIT"
] | BYTEzel/DadSimulator | DadSimulator.Tests/GraphicsLoader.cs | 659 | C# |
/*
* LeagueClient
*
* 7.23.209.3517
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
namespace LeagueClientApi.Model
{
/// <summary>
/// LolMatchmakingMatchmakingLowPriorityData
/// </summary>
[DataContract]
public partial class LolMatchmakingMatchmakingLowPriorityData : IEquatable<LolMatchmakingMatchmakingLowPriorityData>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="LolMatchmakingMatchmakingLowPriorityData" /> class.
/// </summary>
/// <param name="BustedLeaverAccessToken">BustedLeaverAccessToken.</param>
/// <param name="PenalizedSummonerIds">PenalizedSummonerIds.</param>
/// <param name="PenaltyTime">PenaltyTime.</param>
/// <param name="PenaltyTimeRemaining">PenaltyTimeRemaining.</param>
public LolMatchmakingMatchmakingLowPriorityData(string BustedLeaverAccessToken = default(string), List<long?> PenalizedSummonerIds = default(List<long?>), double? PenaltyTime = default(double?), double? PenaltyTimeRemaining = default(double?))
{
this.BustedLeaverAccessToken = BustedLeaverAccessToken;
this.PenalizedSummonerIds = PenalizedSummonerIds;
this.PenaltyTime = PenaltyTime;
this.PenaltyTimeRemaining = PenaltyTimeRemaining;
}
/// <summary>
/// Gets or Sets BustedLeaverAccessToken
/// </summary>
[DataMember(Name="bustedLeaverAccessToken", EmitDefaultValue=false)]
public string BustedLeaverAccessToken { get; set; }
/// <summary>
/// Gets or Sets PenalizedSummonerIds
/// </summary>
[DataMember(Name="penalizedSummonerIds", EmitDefaultValue=false)]
public List<long?> PenalizedSummonerIds { get; set; }
/// <summary>
/// Gets or Sets PenaltyTime
/// </summary>
[DataMember(Name="penaltyTime", EmitDefaultValue=false)]
public double? PenaltyTime { get; set; }
/// <summary>
/// Gets or Sets PenaltyTimeRemaining
/// </summary>
[DataMember(Name="penaltyTimeRemaining", EmitDefaultValue=false)]
public double? PenaltyTimeRemaining { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class LolMatchmakingMatchmakingLowPriorityData {\n");
sb.Append(" BustedLeaverAccessToken: ").Append(BustedLeaverAccessToken).Append("\n");
sb.Append(" PenalizedSummonerIds: ").Append(PenalizedSummonerIds).Append("\n");
sb.Append(" PenaltyTime: ").Append(PenaltyTime).Append("\n");
sb.Append(" PenaltyTimeRemaining: ").Append(PenaltyTimeRemaining).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as LolMatchmakingMatchmakingLowPriorityData);
}
/// <summary>
/// Returns true if LolMatchmakingMatchmakingLowPriorityData instances are equal
/// </summary>
/// <param name="other">Instance of LolMatchmakingMatchmakingLowPriorityData to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(LolMatchmakingMatchmakingLowPriorityData other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.BustedLeaverAccessToken == other.BustedLeaverAccessToken ||
this.BustedLeaverAccessToken != null &&
this.BustedLeaverAccessToken.Equals(other.BustedLeaverAccessToken)
) &&
(
this.PenalizedSummonerIds == other.PenalizedSummonerIds ||
this.PenalizedSummonerIds != null &&
this.PenalizedSummonerIds.SequenceEqual(other.PenalizedSummonerIds)
) &&
(
this.PenaltyTime == other.PenaltyTime ||
this.PenaltyTime != null &&
this.PenaltyTime.Equals(other.PenaltyTime)
) &&
(
this.PenaltyTimeRemaining == other.PenaltyTimeRemaining ||
this.PenaltyTimeRemaining != null &&
this.PenaltyTimeRemaining.Equals(other.PenaltyTimeRemaining)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.BustedLeaverAccessToken != null)
hash = hash * 59 + this.BustedLeaverAccessToken.GetHashCode();
if (this.PenalizedSummonerIds != null)
hash = hash * 59 + this.PenalizedSummonerIds.GetHashCode();
if (this.PenaltyTime != null)
hash = hash * 59 + this.PenaltyTime.GetHashCode();
if (this.PenaltyTimeRemaining != null)
hash = hash * 59 + this.PenaltyTimeRemaining.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 40.005814 | 251 | 0.596425 | [
"MIT"
] | wildbook/LeagueClientApi | Model/LolMatchmakingMatchmakingLowPriorityData.cs | 6,881 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the personalize-2018-05-22.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Personalize.Model
{
/// <summary>
/// Container for the parameters to the ListSolutions operation.
/// Returns a list of solutions that use the given dataset group. When a dataset group
/// is not specified, all the solutions associated with the account are listed. The response
/// provides the properties for each solution, including the Amazon Resource Name (ARN).
/// For more information on solutions, see <a>CreateSolution</a>.
/// </summary>
public partial class ListSolutionsRequest : AmazonPersonalizeRequest
{
private string _datasetGroupArn;
private int? _maxResults;
private string _nextToken;
/// <summary>
/// Gets and sets the property DatasetGroupArn.
/// <para>
/// The Amazon Resource Name (ARN) of the dataset group.
/// </para>
/// </summary>
[AWSProperty(Max=256)]
public string DatasetGroupArn
{
get { return this._datasetGroupArn; }
set { this._datasetGroupArn = value; }
}
// Check to see if DatasetGroupArn property is set
internal bool IsSetDatasetGroupArn()
{
return this._datasetGroupArn != null;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of solutions to return.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=100)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// A token returned from the previous call to <code>ListSolutions</code> for getting
/// the next set of solutions (if they exist).
/// </para>
/// </summary>
[AWSProperty(Max=1300)]
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 33.184466 | 110 | 0.601229 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Personalize/Generated/Model/ListSolutionsRequest.cs | 3,418 | C# |
namespace Telerik.UI.Xaml.Controls.Chart
{
internal abstract class HighLowIndicatorDataSourceBase : CategoricalSeriesDataSource
{
private DataPointBinding highBinding;
private DataPointBinding lowBinding;
public DataPointBinding HighBinding
{
get
{
return this.highBinding;
}
set
{
if (this.highBinding == value)
{
return;
}
this.highBinding = value;
this.highBinding.PropertyChanged += this.OnBoundItemPropertyChanged;
if (this.ItemsSource != null)
{
this.Rebind(false, null);
}
}
}
public DataPointBinding LowBinding
{
get
{
return this.lowBinding;
}
set
{
if (this.lowBinding == value)
{
return;
}
this.lowBinding = value;
this.lowBinding.PropertyChanged += this.OnBoundItemPropertyChanged;
if (this.ItemsSource != null)
{
this.Rebind(false, null);
}
}
}
}
}
| 24.672727 | 88 | 0.43552 | [
"Apache-2.0"
] | ChristianGutman/UI-For-UWP | Controls/Chart/Chart.UWP/Visualization/DataBinding/DataSources/Financial/HighLowIndicatorDataSourceBase.cs | 1,359 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void op_InequalityDouble()
{
var test = new VectorBooleanBinaryOpTest__op_InequalityDouble();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBooleanBinaryOpTest__op_InequalityDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__op_InequalityDouble testClass)
{
var result = _fld1 != _fld2;
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__op_InequalityDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public VectorBooleanBinaryOpTest__op_InequalityDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) != Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Vector128<Double>).GetMethod("op_Inequality", new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = _clsVar1 != _clsVar2;
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = op1 != op2;
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__op_InequalityDouble();
var result = test._fld1 != test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = _fld1 != _fld2;
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = test._fld1 != test._fld2;
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Double[] left, Double[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult |= (left[i] != right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_Inequality<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 43.15411 | 190 | 0.607571 | [
"MIT"
] | 333fred/runtime | src/tests/JIT/HardwareIntrinsics/General/Vector128_1/op_Inequality.Double.cs | 12,601 | C# |
using System;
using Android.Runtime;
using Com.Mapbox.Android.Core.Location;
using Java.Lang;
namespace Com.Mapbox.Mapboxsdk.Annotations
{
public partial class Marker
{
public override int CompareTo(Java.Lang.Object obj)
{
return CompareTo((Marker)obj);
}
}
public partial class Polygon
{
public override int CompareTo(Java.Lang.Object obj)
{
return CompareTo((Polygon)obj);
}
}
public partial class Polyline
{
public override int CompareTo(Java.Lang.Object obj)
{
return CompareTo((Polyline)obj);
}
}
public partial class MarkerOptions
{
public override BaseMarkerOptions This
{
get { return ThisMarkerOptions(); }
}
}
//public partial class MarkerViewOptions
//{
// public override BaseMarkerViewOptions This
// {
// get { return ThisMarkerViewOptions(); }
// }
//}
partial class PolygonOptions
{
static IntPtr id_addHole_arrayLjava_util_List_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.mapbox.mapboxsdk.annotations']/class[@name='PolygonOptions']/method[@name='addHole' and count(parameter)=1 and parameter[1][@type='java.util.List<com.mapbox.mapboxsdk.geometry.LatLng>...']]"
[Register("addHole", "([Ljava/util/List;)Lcom/mapbox/mapboxsdk/annotations/PolygonOptions;", "")]
public unsafe global::Com.Mapbox.Mapboxsdk.Annotations.PolygonOptions AddHole(params global::System.Collections.Generic.IList<global::Com.Mapbox.Mapboxsdk.Geometry.LatLng>[] p0)
{
if (id_addHole_arrayLjava_util_List_ == IntPtr.Zero)
id_addHole_arrayLjava_util_List_ = JNIEnv.GetMethodID(class_ref, "addHole", "([Ljava/util/List;)Lcom/mapbox/mapboxsdk/annotations/PolygonOptions;");
IntPtr native_p0 = JNIEnv.NewArray(p0);
try
{
JValue* __args = stackalloc JValue[1];
__args[0] = new JValue(native_p0);
global::Com.Mapbox.Mapboxsdk.Annotations.PolygonOptions __ret = Java.Lang.Object.GetObject<global::Com.Mapbox.Mapboxsdk.Annotations.PolygonOptions>(JNIEnv.CallObjectMethod(((global::Java.Lang.Object)this).Handle, id_addHole_arrayLjava_util_List_, __args), JniHandleOwnership.TransferLocalRef);
return __ret;
}
finally
{
if (p0 != null)
{
JNIEnv.CopyArray(native_p0, p0);
JNIEnv.DeleteLocalRef(native_p0);
}
}
}
}
public static class BaseOptionsExtensions
{
//public static T This<T>(this BaseMarkerOptions options) where T : BaseMarkerOptions
//{
// return (T)options.This;
//}
//public static T This<T>(this BaseMarkerViewOptions options) where T : BaseMarkerViewOptions
//{
// return (T)options.This;
//}
}
}
namespace Com.Mapbox.Mapboxsdk.Utils
{
partial class FileUtils
{
partial class CheckFileReadPermissionTask
{
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
{
return null;
}
}
partial class CheckFileWritePermissionTask
{
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
{
return null;
}
}
}
}
namespace Com.Mapbox.Mapboxsdk.Location
{
partial class LocationComponent
{
partial class LastLocationEngineCallback : ILocationEngineCallback
{
public void OnSuccess(Java.Lang.Object p0)
{
return;
}
}
partial class CurrentLocationEngineCallback : ILocationEngineCallback
{
public void OnSuccess(Java.Lang.Object p0)
{
return;
}
}
}
}
namespace Com.Mapbox.Mapboxsdk.Maps.Renderer.Egl
{
partial class EGLConfigChooser
{
partial class _1Config : Java.Lang.Object, Java.Lang.IComparable
{
public int CompareTo(Java.Lang.Object o)
{
return CompareTo((_1Config)o);
}
}
}
} | 29.197368 | 309 | 0.592835 | [
"MIT"
] | jploo/mapbox-android-binding | Naxam.Mapbox.Droid/Additions/Classes.cs | 4,440 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace MongoDB.Bson
{
/// <summary>
/// Represents the binary data subtype of a BsonBinaryData.
/// </summary>
#if NET452
[Serializable]
#endif
public enum BsonBinarySubType
{
/// <summary>
/// Binary data.
/// </summary>
Binary = 0x00,
/// <summary>
/// A function.
/// </summary>
Function = 0x01,
/// <summary>
/// Obsolete binary data subtype (use Binary instead).
/// </summary>
[Obsolete("Use Binary instead")]
OldBinary = 0x02,
/// <summary>
/// A UUID in a driver dependent legacy byte order.
/// </summary>
UuidLegacy = 0x03,
/// <summary>
/// A UUID in standard network byte order.
/// </summary>
UuidStandard = 0x04,
/// <summary>
/// An MD5 hash.
/// </summary>
MD5 = 0x05,
/// <summary>
/// User defined binary data.
/// </summary>
UserDefined = 0x80
}
}
| 28.627119 | 75 | 0.5672 | [
"MIT"
] | naivetang/2019MiniGame22 | Server/ThirdParty/MongoDBDriver/MongoDB.Bson/ObjectModel/BsonBinarySubType.cs | 1,691 | C# |
// -----------------------------------------------------------------------
// <copyright file="Program.cs" company="Asynkron HB">
// Copyright (C) 2015-2017 Asynkron HB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Threading;
using Proto;
class Program
{
static void Main(string[] args)
{
var c = 0;
var props = Actor.FromFunc(context =>
{
switch (context.Message)
{
case Started _:
Console.WriteLine($"{DateTime.Now} Started");
context.SetReceiveTimeout(TimeSpan.FromSeconds(1));
break;
case ReceiveTimeout _:
c++;
Console.WriteLine($"{DateTime.Now} ReceiveTimeout: {c}");
break;
case NoInfluence _:
Console.WriteLine($"{DateTime.Now} Received a no-influence message");
break;
case string s:
Console.WriteLine($"{DateTime.Now} Received message: {s}");
break;
}
return Actor.Done;
});
var pid = Actor.Spawn(props);
for (var i = 0; i < 6; i++)
{
pid.Tell("hello");
Thread.Sleep(500);
}
Console.WriteLine("Hit [return] to send no-influence messages");
Console.ReadLine();
for (var i = 0; i < 6; i++)
{
pid.Tell(new NoInfluence());
Thread.Sleep(500);
}
Console.WriteLine("Hit [return] to send a message to cancel the timeout");
Console.ReadLine();
pid.Tell("cancel");
Console.WriteLine("Hit [return] to finish");
Console.ReadLine();
}
}
internal class NoInfluence : INotInfluenceReceiveTimeout
{
} | 30.492308 | 90 | 0.447528 | [
"Apache-2.0"
] | amccool/protoactor-dotnet | examples/ReceiveTimeout/Program.cs | 1,984 | C# |
#if iOS
using OpenTK.Graphics.ES11;
using Foundation;
using ObjCRuntime;
using OpenGLES;
using TextureTarget = OpenTK.Graphics.ES11.All;
using TextureParameterName = OpenTK.Graphics.ES11.All;
using EnableCap = OpenTK.Graphics.ES11.All;
using ArrayCap = OpenTK.Graphics.ES11.All;
using BlendingFactorSrc = OpenTK.Graphics.ES11.All;
using BlendingFactorDest = OpenTK.Graphics.ES11.All;
using PixelStoreParameter = OpenTK.Graphics.ES11.All;
using VertexPointerType = OpenTK.Graphics.ES11.All;
using ColorPointerType = OpenTK.Graphics.ES11.All;
using ClearBufferMask = OpenTK.Graphics.ES11.All;
using TexCoordPointerType = OpenTK.Graphics.ES11.All;
using BeginMode = OpenTK.Graphics.ES11.All;
using DepthFunction = OpenTK.Graphics.ES11.All;
using MatrixMode = OpenTK.Graphics.ES11.All;
using PixelInternalFormat = OpenTK.Graphics.ES11.All;
using PixelFormat = OpenTK.Graphics.ES11.All;
using PixelType = OpenTK.Graphics.ES11.All;
using ShaderType = OpenTK.Graphics.ES11.All;
using VertexAttribPointerType = OpenTK.Graphics.ES11.All;
using ProgramParameter = OpenTK.Graphics.ES11.All;
using ShaderParameter = OpenTK.Graphics.ES11.All;
using CoreGraphics;
using UIKit;
#else
using OpenTK.Graphics.OpenGL;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Threading;
using OpenTK;
using OpenTK.Graphics;
using osum.AssetManager;
using osum.Audio;
using osum.GameModes;
using osum.Graphics;
using osum.Graphics.Sprites;
using osum.Helpers;
using osum.Input;
using osum.Localisation;
using osum.Support;
using osum.UI;
namespace osum
{
public abstract class GameBase
{
public static GameBase Instance;
public static Random Random = new Random();
/// <summary>
/// use for input handling, sprites etc.
/// </summary>
internal static Vector2 BaseSizeFixedWidth = new Vector2(640, 640 / 1.5f);
internal static Vector2 BaseSize = new Vector2(640, 640 / 1.5f);
internal static Vector2 GamefieldBaseSize = new Vector2(512, 384);
//calculations and internally, all textures are at 960-width-compatible sizes.
internal const float BASE_SPRITE_RES = 960;
internal static float SpriteResolution;
/// <summary>
/// Ratio of sprite size compared to their default habitat (SpriteResolution)
/// </summary>
internal static float SpriteToBaseRatio;
internal static float SpriteToNativeRatio;
internal static float ScaleFactor = 1;
internal static Size NativeSize;
public static pConfigManager Config;
/// <summary>
/// The ratio of actual-pixel window size in relation to the base resolution used internally.
/// </summary>
internal static float BaseToNativeRatio;
/// <summary>
/// The ratio of actual-pixel window size in relation to the base resolution used internally.
/// Includes realignment for the range of widths where sprite ratio does not change.
/// </summary>
internal static float BaseToNativeRatioAligned;
internal static Vector2 GamefieldOffsetVector1;
internal static readonly NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
public static Scheduler Scheduler = new Scheduler();
internal virtual bool DisableDimming { get; set; }
/// <summary>
/// A list of components which get updated every frame.
/// </summary>
public static List<IUpdateable> Components = new List<IUpdateable>();
/// <summary>
/// Top-level sprite manager. Draws above everything else.
/// </summary>
internal static SpriteManager MainSpriteManager = new SpriteManager();
//false for tablets etc.
internal static bool IsHandheld = true;
//true for iphone 3g etc.
internal static bool IsSlowDevice = false;
private readonly OsuMode startupMode;
public GameBase(OsuMode mode = OsuMode.Unknown)
{
startupMode = mode;
Instance = this;
CrashHandler.Initialize();
//initialise config before everything, because it may be used in Initialize() override.
Config = new pConfigManager(Instance.PathConfig + "osum.cfg");
Clock.USER_OFFSET = Config.GetValue("offset", 0);
}
internal static Vector2 BaseSizeHalf => new Vector2(BaseSizeFixedWidth.X / 2, BaseSizeFixedWidth.Y / 2);
internal static Vector2 GamefieldToStandard(Vector2 vec)
{
return (vec + GamefieldOffsetVector1) * (BASE_SPRITE_RES / SpriteResolution);
}
internal static Vector2 StandardToGamefield(Vector2 vec)
{
//base position is mapped using constant-width 640
//firstly we need to map this back over variable width
//*then* remove the offset.
return vec / (BASE_SPRITE_RES / SpriteResolution) - GamefieldOffsetVector1;
}
/// <summary>
/// MainLoop runs, starts the main loop and calls Initialize when ready.
/// </summary>
public abstract void Run();
public static event VoidDelegate OnScreenLayoutChanged;
private bool flipView;
public bool FlipView
{
get => flipView;
set
{
if (flipView == value) return;
flipView = value;
Instance.SetViewport();
}
}
public virtual void SetViewport()
{
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Viewport(0, 0, NativeSize.Width, NativeSize.Height);
GL.Ortho(0, NativeSize.Width, NativeSize.Height, 0, -1, 1);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
}
/// <summary>
/// Whether we are running on a device the destroys the limits of how wide a screen can be.
/// </summary>
public static bool IsSuperWide;
public virtual void UpdateSpriteResolution()
{
float res = 1136;
float aspectRatio = (float)NativeSize.Width / NativeSize.Height;
if (aspectRatio > 1.775f)
{
res *= aspectRatio / 1.775f;
IsSuperWide = true;
}
else
{
IsSuperWide = false;
}
SpriteResolution = (int)res;
}
/// <summary>
/// Setup viewport and projection matrix. Should be called after a resolution/orientation change.
/// </summary>
public virtual void SetupScreen()
{
float aspectRatio = (float)NativeSize.Width / NativeSize.Height;
//Setup window...
BaseSizeFixedWidth.Y = BaseSizeFixedWidth.X / aspectRatio;
GL.Disable(EnableCap.DepthTest);
GL.EnableClientState(ArrayCap.VertexArray);
GL.Disable(EnableCap.Lighting);
GL.DepthMask(false);
SetViewport();
BaseToNativeRatio = NativeSize.Width / BaseSizeFixedWidth.X;
int oldResolution = SpriteSheetResolution;
//define any available sprite sheets here.
if (NativeSize.Width < 720)
SpriteSheetResolution = 480;
else if (NativeSize.Width < 1280)
SpriteSheetResolution = 960;
else
SpriteSheetResolution = 1920;
//if we are switching to a new sprite sheet (resizing window on PC) let's refresh our textures.
if (SpriteSheetResolution != oldResolution && oldResolution > 0)
TextureManager.ReloadAll();
UpdateSpriteResolution();
InputToFixedWidthAlign = BASE_SPRITE_RES / SpriteResolution;
BaseToNativeRatioAligned = BaseToNativeRatio * InputToFixedWidthAlign;
SpriteToBaseRatio = BaseSizeFixedWidth.X / BASE_SPRITE_RES;
SpriteToBaseRatioAligned = BaseSizeFixedWidth.X / SpriteResolution;
BaseSize = new Vector2((NativeSize.Width / BaseToNativeRatioAligned), (NativeSize.Height / BaseToNativeRatioAligned));
GamefieldOffsetVector1 = new Vector2((BaseSize.X - GamefieldBaseSize.X) / 2,
Math.Max(31.5f, (BaseSize.Y - GamefieldBaseSize.Y) / 2));
SpriteToNativeRatio = NativeSize.Width / SpriteResolution;
//1024x = 1024/1024 = 1
//960x = 960/960 = 1
//480x = 480/960 = 0.5
#if FULL_DEBUG
Console.WriteLine("Base Resolution is " + BaseSize + " (fixed: " + BaseSizeFixedWidth + ")");
Console.WriteLine("Sprite Resolution is " + SpriteResolution + " with SpriteSheet " + SpriteSheetResolution);
Console.WriteLine("Sprite multiplier is " + SpriteToBaseRatio + " or aligned at " + SpriteToBaseRatioAligned);
#endif
TriggerLayoutChanged();
}
/// <summary>
/// As per Apple recommendations, we should pre-warm any mode changes before actually displaying to avoid stuttering.
/// </summary>
public void Warmup()
{
SpriteManager.TexturesEnabled = true;
SpriteManager.AlphaBlend = false;
SpriteManager.SetBlending(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);
GL.DrawArrays(BeginMode.TriangleFan, 0, 0);
SpriteManager.SetBlending(BlendingFactorSrc.One, BlendingFactorDest.One);
GL.DrawArrays(BeginMode.TriangleFan, 0, 0);
SpriteManager.SetBlending(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
GL.DrawArrays(BeginMode.TriangleFan, 0, 0);
SpriteManager.SetBlending(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One);
GL.DrawArrays(BeginMode.TriangleFan, 0, 0);
SpriteManager.AlphaBlend = true;
SpriteManager.SetBlending(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha);
GL.DrawArrays(BeginMode.TriangleFan, 0, 0);
SpriteManager.SetBlending(BlendingFactorSrc.One, BlendingFactorDest.One);
GL.DrawArrays(BeginMode.TriangleFan, 0, 0);
SpriteManager.SetBlending(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
GL.DrawArrays(BeginMode.TriangleFan, 0, 0);
SpriteManager.SetBlending(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One);
GL.DrawArrays(BeginMode.TriangleFan, 0, 0);
}
/// <summary>
/// This is where the magic happens.
/// </summary>
public virtual void Initialize()
{
SetupScreen();
Warmup();
InitializeAssetManager();
TextureManager.Initialize();
InputManager.Initialize();
InitializeInput();
if (InputManager.RegisteredSources.Count == 0)
throw new Exception("No input sources registered");
BackgroundAudioPlayer music = InitializeBackgroundAudio();
if (music == null)
throw new Exception("No background audio manager registered");
Clock.AudioTimeSource = music;
Components.Add(music);
SoundEffectPlayer effect = InitializeSoundEffects();
if (effect == null)
throw new Exception("No sound effect player registered");
Components.Add(effect);
AudioEngine.Initialize(effect, music);
#if !RELEASE
DebugOverlay.Update();
#endif
#if false
//benchmark
string path = SongSelectMode.BeatmapPath + "/Aperture Science Psychoacoustics Laboratory - Want You Gone (Larto).osz2";
Console.WriteLine(path);
Player.Beatmap = new osum.GameplayElements.Beatmaps.Beatmap(path);
Player.Difficulty = osum.GameplayElements.Difficulty.Expert;
Player.Autoplay = true;
Director.ChangeMode(OsuMode.Play, null);
#elif false
//results screen testing
Player.Beatmap = new GameplayElements.Beatmaps.Beatmap("Beatmaps/Lix - Phantom Ensemble -Ark Trance mix- (Dyaems).osf2");
Player.Difficulty = GameplayElements.Difficulty.Normal;
Results.RankableScore = new GameplayElements.Scoring.Score()
{
count100 = 55,
count50 = 128,
count300 = 387,
countMiss = 0,
date = DateTime.Now,
spinnerBonusScore = 1500,
comboBonusScore = 578420,
hitScore = 100000 - 578420,
maxCombo = 198
};
Director.ChangeMode(OsuMode.Results, null);
#else
//Load the main menu initially.
#if MONO && DEBUG
if (Director.PendingOsuMode == OsuMode.Unknown)
Director.ChangeMode(startupMode != OsuMode.Unknown ? startupMode : OsuMode.MainMenu, null);
#else
Director.ChangeMode(OsuMode.MainMenu, null);
#endif
#endif
Clock.Start();
}
public virtual string DeviceIdentifier => "1234567890123456789012345678901234567890";
/// <summary>
/// Initializes the sound effects engine.
/// </summary>
protected virtual SoundEffectPlayer InitializeSoundEffects()
{
//currently openAL implementation is used across the board.
return new SoundEffectPlayerOpenAL();
}
/// <summary>
/// Initializes the background audio playback engine.
/// </summary>
protected abstract BackgroundAudioPlayer InitializeBackgroundAudio();
/// <summary>
/// Initializes the input management subsystem.
/// </summary>
protected abstract void InitializeInput();
/// <summary>
/// Initializes the AssetManager.
/// Assets are skins, hitsounds, textures that come with the game.
/// These are, depending on the platform, located in the executable itself.
/// Maps are not included as assets to prevent oversized executables.
/// </summary>
/// <returns></returns>
protected virtual NativeAssetManager InitializeAssetManager()
{
return new NativeAssetManager();
}
/// <summary>
/// Main update cycle
/// </summary>
/// <returns>true if a draw should occur</returns>
public bool Update()
{
Clock.Update(false);
UpdateNotifications();
Scheduler.Update();
#if !RELEASE
DebugOverlay.Update();
#endif
#if FULLER_DEBUG
DebugOverlay.AddLine("GC: 0:" + GC.CollectionCount(0) + " 1:" + GC.CollectionCount(1) + " 2:" + GC.CollectionCount(2));
DebugOverlay.AddLine("Window Size: " + NativeSize.Width + "x" + NativeSize.Height + " Sprite Resolution: " + SpriteResolution);
#endif
TextureManager.Update();
MainSpriteManager.Update();
if (Director.Update())
InputManager.Update();
Components.ForEach(c => c.Update());
if (ActiveNotification != null) ActiveNotification.Update();
return true;
}
/// <summary>
/// Main draw cycle.
/// </summary>
public void Draw()
{
SpriteManager.Reset();
if (Director.ActiveTransition == null || !Director.ActiveTransition.SkipScreenClear)
//todo: Does clearing DEPTH as well here add a performance overhead?
GL.Clear(Constants.COLOR_DEPTH_BUFFER_BIT);
Director.Draw();
MainSpriteManager.Draw();
}
private static pDrawable loadingText;
private static pDrawable loadingCircle;
private static bool showLoadingOverlay;
public static bool ShowLoadingOverlay
{
get => showLoadingOverlay;
set
{
if (value == showLoadingOverlay) return;
showLoadingOverlay = value;
if (showLoadingOverlay)
{
loadingText = new pText(LocalisationManager.GetString(OsuString.Loading), 30, new Vector2(0, -25), 0.999f, true, Color4.LightGray)
{
DimImmune = true,
Origin = OriginTypes.Centre,
Field = FieldTypes.StandardSnapCentre,
Clocking = ClockTypes.Game,
Bold = true
};
MainSpriteManager.Add(loadingText);
loadingText.FadeInFromZero(300);
loadingCircle = new pSprite(TextureManager.Load(OsuTexture.songselect_audio_preview), FieldTypes.StandardSnapCentre, OriginTypes.Centre, ClockTypes.Game, new Vector2(0, 25), 0.999f, true, Color4.White)
{
ExactCoordinates = false,
DimImmune = true
};
loadingCircle.Transform(new TransformationF(TransformationType.Rotation, 0, MathHelper.Pi * 2, Clock.Time, Clock.Time + 1500) { Looping = true });
MainSpriteManager.Add(loadingCircle);
loadingCircle.FadeInFromZero(300);
}
else
{
loadingText.FadeOut(100);
loadingText.AlwaysDraw = false;
loadingCircle.Transformations.Clear();
loadingCircle.FadeOut(100);
loadingCircle.AlwaysDraw = false;
}
}
}
private static bool globallyDisableInput;
public static bool GloballyDisableInput
{
get => globallyDisableInput;
set
{
if (value == globallyDisableInput)
return;
globallyDisableInput = value;
ShowLoadingOverlay = globallyDisableInput;
}
}
public static bool ThrottleExecution;
public static void TriggerLayoutChanged()
{
if (OnScreenLayoutChanged != null)
OnScreenLayoutChanged();
}
internal static Notification ActiveNotification;
internal static Queue<Notification> NotificationQueue = new Queue<Notification>();
internal static int SpriteSheetResolution;
public static float InputToFixedWidthAlign;
public static float SpriteToBaseRatioAligned;
public static bool Mapper;
internal static int SuperWidePadding => IsSuperWide ? 30 : 0;
public static bool HasAuth => false;
internal static void Notify(string simple, BoolDelegate action = null)
{
Notify(new Notification(LocalisationManager.GetString(OsuString.Alert), simple, NotificationStyle.Okay, action));
}
internal static void Notify(Notification notification)
{
NotificationQueue.Enqueue(notification);
}
private void UpdateNotifications()
{
if (ActiveNotification != null && ActiveNotification.Dismissed)
ActiveNotification = null;
if (NotificationQueue.Count > 0 && ActiveNotification == null && !globallyDisableInput)
{
ActiveNotification = NotificationQueue.Dequeue();
ActiveNotification.Display();
//use the main sprite manager to handle input before anything else.
MainSpriteManager.Add(ActiveNotification);
}
}
public virtual Thread RunInBackground(VoidDelegate task)
{
Thread t = new Thread((ThreadStart)delegate { task(); });
t.Priority = ThreadPriority.Highest;
t.IsBackground = true;
t.Start();
return t;
}
public virtual void ShowWebView(string url, string title = "", StringBoolDelegate checkFinished = null)
{
OpenUrl(url);
}
public virtual void OpenUrl(string url)
{
Process.Start(url);
}
public virtual string PathConfig => string.Empty;
}
} | 34.760726 | 222 | 0.59136 | [
"MIT"
] | Beyley/osu-stream | osu!stream/GameBase.cs | 21,065 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UserInterface;
public enum WindowBuilderCanvas
{
Screen,
World
}
public static class WindowBuilder
{
public static readonly Dictionary<string, GameObject> OpenWindowDictionary = new Dictionary<string, GameObject>();
public static GameObject CreateWindow(string windowIdentifier, string headerText, GameObject content, WindowBuilderCanvas canvasType, bool canDrag = true, bool canResize = false, int minX = 200, int minY = 325, int maxX = 200, int maxY = 325)
{
if (OpenWindowDictionary.ContainsKey(windowIdentifier))
{
Debug.Log("Window already open!");
return null;
}
var window = GameObject.Instantiate(Resources.Load<GameObject>("Prefabs/UI/Windows/WindowBase"));
window.transform.SetParent(GameObject.Find("GlobalCanvas").transform, false);
var baseWindow = window.GetComponent<BasicWindow>();
if (!canDrag)
{
baseWindow.DragZone.SetActive(false);
}
if (canResize)
{
baseWindow.ResizeZone.GetComponent<ResizeHandler>().SetSizeLimits(minX, minY, maxX, maxY);
}
else
{
baseWindow.ResizeZone.SetActive(false);
}
content.transform.SetParent(baseWindow.Content.transform);
var width = content.transform.localScale.x > 200 ? content.transform.localScale.x : 200;
baseWindow.Panel.GetComponent<RectTransform>().sizeDelta = new Vector2(width, content.transform.localScale.y + 40);
OpenWindowDictionary.Add(windowIdentifier, window);
return window;
}
private static Transform GetCanvasTransform(WindowBuilderCanvas canvasType)
{
switch (canvasType)
{
case WindowBuilderCanvas.Screen:
return GameObject.FindGameObjectWithTag("ScreenCanvas").transform;
case WindowBuilderCanvas.World:
return GameObject.FindGameObjectWithTag("WorldCanvas").transform;
default:
throw new ArgumentOutOfRangeException(nameof(canvasType), canvasType, null);
}
}
}
| 32.485294 | 246 | 0.669534 | [
"MIT"
] | palmelund/prototype-rpg | Assets/Scripts/UserInterface/WindowBuilder.cs | 2,211 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
namespace CombatSystemComponent
{
//Manages common helper methods and helper functions that can be used by each character in the game
abstract class HelperBase : CharacterBase
{
//Action Helpers
protected void Move(Vector3 yAxisFacingDirection, string animationParameter = "")
{
Rotate(yAxisFacingDirection);
//set direction
Vector3 direction = new Vector3(yAxisFacingDirection.x, 0, yAxisFacingDirection.z);
direction = direction.normalized;
//set velocity
animator.SetBool(animationParameter, true);
if (animationParameter == grabWalking)
{
velocity.x = direction.x * gameStats.walkSpeed;
velocity.z = direction.z * gameStats.walkSpeed;
}
else if (animationParameter == grabSprinting)
{
velocity.x = direction.x * gameStats.sprintSpeed;
velocity.z = direction.z * gameStats.sprintSpeed;
}
}
protected void Rotate(Vector3 yAxisFacingDirection)
{
//set rotation
rotation = controller.transform.rotation.eulerAngles;
Vector3 newRotation = Quaternion.LookRotation(yAxisFacingDirection).eulerAngles;
rotation.y = newRotation.y;
}
protected void Jump()
{
if (IsGrounded())
{
velocity.y = Mathf.Sqrt(gameStats.jumpHeight * 2f * -gravity.y);
animator.SetTrigger(grabJump);
}
}
protected void Target(Transform target)
{
this.target = target;
}
protected virtual void Melee()
{
animator.SetTrigger(grabMelee);
}
protected virtual void Projectile(string name)
{
if (target != null)
{
Rotate(faceTarget); //might need to do something different with yAxisFacingDirection
GameObject projectile = Instantiate(assets.GetProjectileByName(name), controller.transform.position + (faceTarget.normalized + Vector3.up) * 5f, Quaternion.identity);
ProjectileBehavior projectileBehavior = projectile.GetComponent<ProjectileBehavior>();
projectileBehavior.speed = gameStats.projectileSpeed;
projectileBehavior.target = target;
projectileBehavior.sender = gameObject;
}
}
protected void Retarget(Collider[] enemies)
{
if (enemies.Length != 0)
{
target = enemies.OrderBy(c => (c.transform.position - controller.transform.position).sqrMagnitude).First().transform;
OnDecision = OnCombatDecision;
}
else
{
target = GetDefaultTarget();
OnDecision = OnPeacefulDecision;
}
}
//Update Helpers
protected void ResetDecisionValues()
{
animator.SetBool(grabWalking, false);
animator.SetBool(grabSprinting, false);
velocity.x = 0f;
velocity.z = 0f;
}
protected void UpdateCharacterController()
{
velocity.y = Mathf.Clamp(velocity.y + gravity.y * Time.deltaTime, gravity.y, float.MaxValue);
controller.Move(velocity * Time.deltaTime);
controller.transform.rotation = Quaternion.Lerp(controller.transform.rotation, Quaternion.Euler(rotation), 0.15f * 60f * Time.deltaTime);
}
protected void CheckIfCharacterIsGrounded()
{
if (controller.isGrounded)
animator.SetBool(grabGrounded, true);
else
animator.SetBool(grabGrounded, false);
}
//Make Decision Events
protected virtual void OnPeacefulDecision() { }
protected virtual void OnCombatDecision() { }
//Misc Helpers
protected bool IsGrounded()
{
return animator.GetBool(grabGrounded);
}
protected Vector3 faceTarget
{
get { return target.position - controller.transform.position; }
}
protected Vector3 faceRightOfTarget
{
get { return (target.position - controller.transform.position) + Vector3.right; }
}
protected virtual Transform GetDefaultTarget()
{
return GameObject.Find("Player").transform;
}
protected bool OnNearbyEnemies(float forwardOffset, float radius, Action<Collider[]> actionToPerform)
{
return OnNearbyEnemies(transform, gameObject.layer, forwardOffset, radius, actionToPerform);
}
public static bool OnNearbyEnemies(Transform allieTransform, int allieLayer, float forwardOffset, float radius, Action<Collider[]> actionToPerform)
{
string layerName = allieLayer == 10 ? "Allie" : "Enemy";
Collider[] colliders = Physics.OverlapSphere(allieTransform.position + (allieTransform.forward * forwardOffset), radius, LayerMask.GetMask(layerName));
actionToPerform(colliders);
return colliders.Length > 0;
}
protected void ApplyMeleeDamageTo(Collider[] enemies)
{
foreach (Collider enemy in enemies)
{
//damage calculation
int damageAmount = 0;
HelperBase enemyStats = enemy.transform.root.GetComponent<HelperBase>();
damageAmount = (int)DerivedStats.GetReductionDamage(this.gameStats.strength, enemyStats.gameStats.defense);
damageAmount = (int)(damageAmount * UnityEngine.Random.Range(0.8f, 1.2f));
Instantiate(assets.GetMeleeHit(), enemy.ClosestPointOnBounds(transform.position), Quaternion.identity);
enemyStats.TakeDamage(damageAmount);
ApplyMeleeDamageToEvent(enemy);
}
}
protected virtual void ApplyMeleeDamageToEvent(Collider collider) { }
public virtual void TakeDamage(float damageAmount)
{
health -= (int)damageAmount;
animator.SetTrigger(grabHit);
//show damage text
GameObject.Find("DamageMenu").GetComponent<DamageMenuBehavior>().ShowDamage(transform, damageAmount, damageTextColor, assets);
TakeDamageFX.Play();
}
protected virtual void MeleeContactEvent()
{
OnNearbyEnemies(meleeOffset, meleeRadius, ApplyMeleeDamageTo);
}
//Misc Setter
public void SetAssets(CombatSystemAssets assets)
{
this.assets = assets;
}
}
} | 38.679775 | 182 | 0.598112 | [
"MIT"
] | geodreamalpha/geodreamalpha | desktop/Unity/Assets/CombatSystem/Scripts/Model/Model 2/HelperBase.cs | 6,885 | C# |
using System;
namespace InsertionSort
{
class Program
{
static void PrintArray(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
System.Console.WriteLine(arr[i]);
}
}
static void InsertionSort(int[] nums)
{
for (int i = 1; i < nums.Length; i++)
{
//i -> Índice actual en la "caja"
int x = nums[i];
//x -> Valor actual en la "caja"
int j = i - 1;
//j -> Índice que estamos comparando con el de la caja
//nums[j] -> Valor que estamos comparando con el de la caja
//Condiciones del while
//1. No pasarnos del límite inferior de índices permitidos en array
// (llegar hasta el inicio)
//2. Detener la comparación de números hacia la izquierda en el momento
// en que nos encontráramos un valor que no fuera mayor al de la "caja"
while (j >= 0 && nums[j] > x)
{
//"Recorrer a la derecha"
nums[j + 1] = nums[j];
j = j - 1;
}
//En este momento, j está a la izquierda del "espacio vacío"
//j + 1 es el índice del espacio vacío
nums[j + 1] = x;
}
}
static void Main(string[] args)
{
int[] nums = new int[]{8, 9, 7, 6, 10, 4, 11, 9, 7};
System.Console.WriteLine("Antes de ordenar:");
PrintArray(nums);
InsertionSort(nums);
System.Console.WriteLine("Después de ordenar:");
PrintArray(nums);
}
}
} | 32.192982 | 90 | 0.434877 | [
"MIT"
] | TitanX1503/insertion-sort | insertionsort.cs | 1,847 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
{
[Export(typeof(IWpfTextViewConnectionListener))]
[ContentType(ContentTypeNames.CSharpContentType)]
[TextViewRole(PredefinedTextViewRoles.Interactive)]
internal class HACK_CSharpCreateServicesOnUIThread : HACK_AbstractCreateServicesOnUiThread
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public HACK_CSharpCreateServicesOnUIThread(IThreadingContext threadingContext, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
: base(threadingContext, serviceProvider, LanguageNames.CSharp)
{
}
}
}
| 42.548387 | 157 | 0.802881 | [
"MIT"
] | 06needhamt/roslyn | src/VisualStudio/CSharp/Impl/LanguageService/HACK_CSharpCreateServicesOnUIThread.cs | 1,321 | C# |
// Code generated by a template
// Project: Remember
// LastUpadteTime: 2019-12-03 10:32:23
using Domain.Entities;
using Repositories.Core;
using Repositories.Interface;
namespace Repositories.Implement
{
public partial class SettingRepository : BaseRepository<Setting>, ISettingRepository
{
private readonly RemDbContext _context;
public SettingRepository(RemDbContext context) : base(context)
{
this._context = context;
}
}
}
| 24.3 | 88 | 0.707819 | [
"Apache-2.0"
] | fossabot/remember | src/Libraries/Repositories/Auto/Implement/SettingRepository.cs | 486 | C# |
namespace _00.Practice
{
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
}
}
}
| 12.642857 | 37 | 0.553672 | [
"MIT"
] | Pazzobg/02.01.Programming-Fundamentals-SelfStudy | 06.Advanced-Collections/05.Dictionaries-Extended-1-Advanced-Collections_Lab/00.Practice/Program.cs | 179 | C# |
using System.Collections;
using UnityEngine;
public class Shot : MonoBehaviour {
void Start() {
var rb = GetComponent<Rigidbody>();
rb.AddForce(transform.forward * 30, ForceMode.Impulse);
StartCoroutine(DestroyAfterDelay());
}
IEnumerator DestroyAfterDelay() {
yield return new WaitForSeconds(0.8f);
Destroy(gameObject);
}
void OnCollisionEnter(Collision collision) {
var health = collision.collider.GetComponent<Health>();
if (health != null) {
health.current -= 10;
}
}
}
| 24.125 | 63 | 0.623489 | [
"MIT"
] | OneManMonkeySquad/SandboxAI | Example/Robot/Shot.cs | 581 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Devices.V20191104
{
public static class GetIotHubResourceEventHubConsumerGroup
{
public static Task<GetIotHubResourceEventHubConsumerGroupResult> InvokeAsync(GetIotHubResourceEventHubConsumerGroupArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetIotHubResourceEventHubConsumerGroupResult>("azure-nextgen:devices/v20191104:getIotHubResourceEventHubConsumerGroup", args ?? new GetIotHubResourceEventHubConsumerGroupArgs(), options.WithVersion());
}
public sealed class GetIotHubResourceEventHubConsumerGroupArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the Event Hub-compatible endpoint in the IoT hub.
/// </summary>
[Input("eventHubEndpointName", required: true)]
public string EventHubEndpointName { get; set; } = null!;
/// <summary>
/// The name of the consumer group to retrieve.
/// </summary>
[Input("name", required: true)]
public string Name { get; set; } = null!;
/// <summary>
/// The name of the resource group that contains the IoT hub.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the IoT hub.
/// </summary>
[Input("resourceName", required: true)]
public string ResourceName { get; set; } = null!;
public GetIotHubResourceEventHubConsumerGroupArgs()
{
}
}
[OutputType]
public sealed class GetIotHubResourceEventHubConsumerGroupResult
{
/// <summary>
/// The etag.
/// </summary>
public readonly string Etag;
/// <summary>
/// The Event Hub-compatible consumer group name.
/// </summary>
public readonly string Name;
/// <summary>
/// The tags.
/// </summary>
public readonly ImmutableDictionary<string, string> Properties;
/// <summary>
/// the resource type.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetIotHubResourceEventHubConsumerGroupResult(
string etag,
string name,
ImmutableDictionary<string, string> properties,
string type)
{
Etag = etag;
Name = name;
Properties = properties;
Type = type;
}
}
}
| 32.272727 | 255 | 0.622887 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Devices/V20191104/GetIotHubResourceEventHubConsumerGroup.cs | 2,840 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AliCloud.Nas
{
public static class GetAccessRules
{
/// <summary>
/// This data source provides AccessRule available to the user.
///
/// > **NOTE**: Available in 1.35.0+
/// </summary>
public static Task<GetAccessRulesResult> InvokeAsync(GetAccessRulesArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetAccessRulesResult>("alicloud:nas/getAccessRules:getAccessRules", args ?? new GetAccessRulesArgs(), options.WithVersion());
}
public sealed class GetAccessRulesArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Filter results by a specific AccessGroupName.
/// </summary>
[Input("accessGroupName", required: true)]
public string AccessGroupName { get; set; } = null!;
[Input("ids")]
private List<string>? _ids;
/// <summary>
/// A list of rule IDs.
/// </summary>
public List<string> Ids
{
get => _ids ?? (_ids = new List<string>());
set => _ids = value;
}
[Input("outputFile")]
public string? OutputFile { get; set; }
/// <summary>
/// Filter results by a specific RWAccess.
/// </summary>
[Input("rwAccess")]
public string? RwAccess { get; set; }
/// <summary>
/// Filter results by a specific SourceCidrIp.
/// </summary>
[Input("sourceCidrIp")]
public string? SourceCidrIp { get; set; }
/// <summary>
/// Filter results by a specific UserAccess.
/// </summary>
[Input("userAccess")]
public string? UserAccess { get; set; }
public GetAccessRulesArgs()
{
}
}
[OutputType]
public sealed class GetAccessRulesResult
{
public readonly string AccessGroupName;
/// <summary>
/// The provider-assigned unique ID for this managed resource.
/// </summary>
public readonly string Id;
/// <summary>
/// A list of rule IDs, Each element set to `access_rule_id` (Each element formats as `<access_group_name>:<access_rule_id>` before 1.53.0).
/// </summary>
public readonly ImmutableArray<string> Ids;
public readonly string? OutputFile;
/// <summary>
/// A list of AccessRules. Each element contains the following attributes:
/// </summary>
public readonly ImmutableArray<Outputs.GetAccessRulesRuleResult> Rules;
/// <summary>
/// RWAccess of the AccessRule.
/// </summary>
public readonly string? RwAccess;
/// <summary>
/// SourceCidrIp of the AccessRule.
/// </summary>
public readonly string? SourceCidrIp;
/// <summary>
/// UserAccess of the AccessRule
/// </summary>
public readonly string? UserAccess;
[OutputConstructor]
private GetAccessRulesResult(
string accessGroupName,
string id,
ImmutableArray<string> ids,
string? outputFile,
ImmutableArray<Outputs.GetAccessRulesRuleResult> rules,
string? rwAccess,
string? sourceCidrIp,
string? userAccess)
{
AccessGroupName = accessGroupName;
Id = id;
Ids = ids;
OutputFile = outputFile;
Rules = rules;
RwAccess = rwAccess;
SourceCidrIp = sourceCidrIp;
UserAccess = userAccess;
}
}
}
| 30.346154 | 179 | 0.577693 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-alicloud | sdk/dotnet/Nas/GetAccessRules.cs | 3,945 | C# |
using System;
using Microsoft.Extensions.Logging;
using Microsoft.Maui.Controls.Internals;
using Microsoft.Maui.Controls.Shapes;
using Microsoft.Maui.Graphics;
namespace Microsoft.Maui.Controls
{
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="Type[@FullName='Microsoft.Maui.Controls.RadioButton']/Docs" />
public partial class RadioButton : TemplatedView, IElementConfiguration<RadioButton>, ITextElement, IFontElement, IBorderElement
{
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='CheckedVisualState']/Docs" />
public const string CheckedVisualState = "Checked";
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='UncheckedVisualState']/Docs" />
public const string UncheckedVisualState = "Unchecked";
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='TemplateRootName']/Docs" />
public const string TemplateRootName = "Root";
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='CheckedIndicator']/Docs" />
public const string CheckedIndicator = "CheckedIndicator";
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='UncheckedButton']/Docs" />
public const string UncheckedButton = "Button";
internal const string GroupNameChangedMessage = "RadioButtonGroupNameChanged";
internal const string ValueChangedMessage = "RadioButtonValueChanged";
// Template Parts
TapGestureRecognizer _tapGestureRecognizer;
View _templateRoot;
static readonly Brush RadioButtonCheckMarkThemeColor = ResolveThemeColor("RadioButtonCheckMarkThemeColor");
static readonly Brush RadioButtonThemeColor = ResolveThemeColor("RadioButtonThemeColor");
static ControlTemplate s_defaultTemplate;
readonly Lazy<PlatformConfigurationRegistry<RadioButton>> _platformConfigurationRegistry;
static bool? s_rendererAvailable;
public event EventHandler<CheckedChangedEventArgs> CheckedChanged;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='ContentProperty']/Docs" />
public static readonly BindableProperty ContentProperty =
BindableProperty.Create(nameof(Content), typeof(object), typeof(RadioButton), null);
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='ValueProperty']/Docs" />
public static readonly BindableProperty ValueProperty =
BindableProperty.Create(nameof(Value), typeof(object), typeof(RadioButton), null,
propertyChanged: (b, o, n) => ((RadioButton)b).OnValuePropertyChanged());
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='IsCheckedProperty']/Docs" />
public static readonly BindableProperty IsCheckedProperty = BindableProperty.Create(
nameof(IsChecked), typeof(bool), typeof(RadioButton), false,
propertyChanged: (b, o, n) => ((RadioButton)b).OnIsCheckedPropertyChanged((bool)n),
defaultBindingMode: BindingMode.TwoWay);
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='GroupNameProperty']/Docs" />
public static readonly BindableProperty GroupNameProperty = BindableProperty.Create(
nameof(GroupName), typeof(string), typeof(RadioButton), null,
propertyChanged: (b, o, n) => ((RadioButton)b).OnGroupNamePropertyChanged((string)o, (string)n));
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='TextColorProperty']/Docs" />
public static readonly BindableProperty TextColorProperty = TextElement.TextColorProperty;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='CharacterSpacingProperty']/Docs" />
public static readonly BindableProperty CharacterSpacingProperty = TextElement.CharacterSpacingProperty;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='TextTransformProperty']/Docs" />
public static readonly BindableProperty TextTransformProperty = TextElement.TextTransformProperty;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='FontAttributesProperty']/Docs" />
public static readonly BindableProperty FontAttributesProperty = FontElement.FontAttributesProperty;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='FontFamilyProperty']/Docs" />
public static readonly BindableProperty FontFamilyProperty = FontElement.FontFamilyProperty;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='FontSizeProperty']/Docs" />
public static readonly BindableProperty FontSizeProperty = FontElement.FontSizeProperty;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='FontAutoScalingEnabledProperty']/Docs" />
public static readonly BindableProperty FontAutoScalingEnabledProperty = FontElement.FontAutoScalingEnabledProperty;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='BorderColorProperty']/Docs" />
public static readonly BindableProperty BorderColorProperty = BorderElement.BorderColorProperty;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='CornerRadiusProperty']/Docs" />
public static readonly BindableProperty CornerRadiusProperty = BorderElement.CornerRadiusProperty;
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='BorderWidthProperty']/Docs" />
public static readonly BindableProperty BorderWidthProperty = BorderElement.BorderWidthProperty;
// If Content is set to a string, the string will be displayed using the native Text property
// on platforms which support that; in a ControlTemplate it will be automatically converted
// to a Label. If Content is set to a View, the View will be displayed on platforms which
// support Content natively or in the ContentPresenter of the ControlTemplate, if a ControlTemplate
// is set. If a ControlTemplate is not set and the platform does not natively support arbitrary
// Content, the ToString() representation of Content will be displayed.
// For all types other than View and string, the ToString() representation of Content will be displayed.
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='Content']/Docs" />
public object Content
{
get => GetValue(ContentProperty);
set => SetValue(ContentProperty, value);
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='Value']/Docs" />
public object Value
{
get => GetValue(ValueProperty);
set => SetValue(ValueProperty, value);
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='IsChecked']/Docs" />
public bool IsChecked
{
get { return (bool)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='GroupName']/Docs" />
public string GroupName
{
get { return (string)GetValue(GroupNameProperty); }
set { SetValue(GroupNameProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='TextColor']/Docs" />
public Color TextColor
{
get { return (Color)GetValue(TextColorProperty); }
set { SetValue(TextColorProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='CharacterSpacing']/Docs" />
public double CharacterSpacing
{
get { return (double)GetValue(CharacterSpacingProperty); }
set { SetValue(CharacterSpacingProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='TextTransform']/Docs" />
public TextTransform TextTransform
{
get { return (TextTransform)GetValue(TextTransformProperty); }
set { SetValue(TextTransformProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='FontAttributes']/Docs" />
public FontAttributes FontAttributes
{
get { return (FontAttributes)GetValue(FontAttributesProperty); }
set { SetValue(FontAttributesProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='FontFamily']/Docs" />
public string FontFamily
{
get { return (string)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='FontSize']/Docs" />
[System.ComponentModel.TypeConverter(typeof(FontSizeConverter))]
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='FontAutoScalingEnabled']/Docs" />
public bool FontAutoScalingEnabled
{
get => (bool)GetValue(FontAutoScalingEnabledProperty);
set => SetValue(FontAutoScalingEnabledProperty, value);
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='BorderWidth']/Docs" />
public double BorderWidth
{
get { return (double)GetValue(BorderWidthProperty); }
set { SetValue(BorderWidthProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='BorderColor']/Docs" />
public Color BorderColor
{
get { return (Color)GetValue(BorderColorProperty); }
set { SetValue(BorderColorProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='CornerRadius']/Docs" />
public int CornerRadius
{
get { return (int)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='.ctor']/Docs" />
public RadioButton()
{
_platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<RadioButton>>(() =>
new PlatformConfigurationRegistry<RadioButton>(this));
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='On']/Docs" />
public IPlatformElementConfiguration<T, RadioButton> On<T>() where T : IConfigPlatform
{
return _platformConfigurationRegistry.Value.On<T>();
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='DefaultTemplate']/Docs" />
public static ControlTemplate DefaultTemplate
{
get
{
if (s_defaultTemplate == null)
{
s_defaultTemplate = new ControlTemplate(() => BuildDefaultTemplate());
}
return s_defaultTemplate;
}
}
void ITextElement.OnTextTransformChanged(TextTransform oldValue, TextTransform newValue)
=> InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
void ITextElement.OnTextColorPropertyChanged(Color oldValue, Color newValue)
{
}
void ITextElement.OnCharacterSpacingPropertyChanged(double oldValue, double newValue)
=> InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
void IFontElement.OnFontFamilyChanged(string oldValue, string newValue) =>
HandleFontChanged();
void IFontElement.OnFontSizeChanged(double oldValue, double newValue) =>
HandleFontChanged();
void IFontElement.OnFontAttributesChanged(FontAttributes oldValue, FontAttributes newValue) =>
HandleFontChanged();
void IFontElement.OnFontChanged(Font oldValue, Font newValue) =>
HandleFontChanged();
void IFontElement.OnFontAutoScalingEnabledChanged(bool oldValue, bool newValue) =>
HandleFontChanged();
void HandleFontChanged()
{
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
}
double IFontElement.FontSizeDefaultValueCreator() =>
this.GetDefaultFontSize();
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='UpdateFormsText']/Docs" />
public virtual string UpdateFormsText(string source, TextTransform textTransform)
=> TextTransformUtilites.GetTransformedText(source, textTransform);
int IBorderElement.CornerRadiusDefaultValue => (int)BorderElement.CornerRadiusProperty.DefaultValue;
Color IBorderElement.BorderColorDefaultValue => (Color)BorderElement.BorderColorProperty.DefaultValue;
double IBorderElement.BorderWidthDefaultValue => (double)BorderElement.BorderWidthProperty.DefaultValue;
void IBorderElement.OnBorderColorPropertyChanged(Color oldValue, Color newValue)
{
}
bool IBorderElement.IsCornerRadiusSet() => IsSet(BorderElement.CornerRadiusProperty);
bool IBorderElement.IsBackgroundColorSet() => IsSet(BackgroundColorProperty);
bool IBorderElement.IsBackgroundSet() => IsSet(BackgroundProperty);
bool IBorderElement.IsBorderColorSet() => IsSet(BorderElement.BorderColorProperty);
bool IBorderElement.IsBorderWidthSet() => IsSet(BorderElement.BorderWidthProperty);
protected internal override void ChangeVisualState()
{
ApplyIsCheckedState();
base.ChangeVisualState();
}
IPlatformSizeService _platformSizeService;
protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
{
if (ControlTemplate == null)
{
if (Handler != null)
return new SizeRequest(Handler.GetDesiredSize(widthConstraint, heightConstraint));
_platformSizeService ??= DependencyService.Get<IPlatformSizeService>();
return _platformSizeService.GetPlatformSize(this, widthConstraint, heightConstraint);
}
return base.OnMeasure(widthConstraint, heightConstraint);
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='ResolveControlTemplate']/Docs" />
public override ControlTemplate ResolveControlTemplate()
{
var template = base.ResolveControlTemplate();
if (template == null)
{
if (!RendererAvailable)
{
ControlTemplate = DefaultTemplate;
}
}
return ControlTemplate;
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
_templateRoot = (this as IControlTemplated)?.TemplateRoot as View;
ApplyIsCheckedState();
UpdateIsEnabled();
}
internal override void OnControlTemplateChanged(ControlTemplate oldValue, ControlTemplate newValue)
{
base.OnControlTemplateChanged(oldValue, newValue);
}
void UpdateIsEnabled()
{
if (ControlTemplate == null)
{
return;
}
if (_tapGestureRecognizer == null)
{
_tapGestureRecognizer = new TapGestureRecognizer();
}
if (IsEnabled)
{
_tapGestureRecognizer.Tapped += SelectRadioButton;
GestureRecognizers.Add(_tapGestureRecognizer);
}
else
{
_tapGestureRecognizer.Tapped -= SelectRadioButton;
GestureRecognizers.Remove(_tapGestureRecognizer);
}
}
static bool RendererAvailable
{
get
{
if (!s_rendererAvailable.HasValue)
{
s_rendererAvailable = Internals.Registrar.Registered.GetHandlerType(typeof(RadioButton)) != null;
}
return s_rendererAvailable.Value;
}
}
static Brush ResolveThemeColor(string key)
{
if (Application.Current.TryGetResource(key, out object color))
{
return (Brush)color;
}
if (Application.Current?.RequestedTheme == OSAppTheme.Dark)
{
return Brush.White;
}
return Brush.Black;
}
void ApplyIsCheckedState()
{
if (IsChecked)
{
VisualStateManager.GoToState(this, CheckedVisualState);
if (_templateRoot != null)
{
VisualStateManager.GoToState(_templateRoot, CheckedVisualState);
}
}
else
{
VisualStateManager.GoToState(this, UncheckedVisualState);
if (_templateRoot != null)
{
VisualStateManager.GoToState(_templateRoot, UncheckedVisualState);
}
}
}
void SelectRadioButton(object sender, EventArgs e)
{
if (IsEnabled)
{
IsChecked = true;
}
}
void OnIsCheckedPropertyChanged(bool isChecked)
{
if (isChecked)
RadioButtonGroup.UpdateRadioButtonGroup(this);
ChangeVisualState();
CheckedChanged?.Invoke(this, new CheckedChangedEventArgs(isChecked));
}
void OnValuePropertyChanged()
{
if (!IsChecked || string.IsNullOrEmpty(GroupName))
{
return;
}
MessagingCenter.Send(this, ValueChangedMessage,
new RadioButtonValueChanged(RadioButtonGroup.GetVisualRoot(this)));
}
void OnGroupNamePropertyChanged(string oldGroupName, string newGroupName)
{
if (!string.IsNullOrEmpty(newGroupName))
{
if (string.IsNullOrEmpty(oldGroupName))
{
MessagingCenter.Subscribe<RadioButton, RadioButtonGroupSelectionChanged>(this,
RadioButtonGroup.GroupSelectionChangedMessage, HandleRadioButtonGroupSelectionChanged);
MessagingCenter.Subscribe<Maui.ILayout, RadioButtonGroupValueChanged>(this,
RadioButtonGroup.GroupValueChangedMessage, HandleRadioButtonGroupValueChanged);
}
MessagingCenter.Send(this, GroupNameChangedMessage,
new RadioButtonGroupNameChanged(RadioButtonGroup.GetVisualRoot(this), oldGroupName));
}
else
{
if (!string.IsNullOrEmpty(oldGroupName))
{
MessagingCenter.Unsubscribe<RadioButton, RadioButtonGroupSelectionChanged>(this, RadioButtonGroup.GroupSelectionChangedMessage);
MessagingCenter.Unsubscribe<Maui.ILayout, RadioButtonGroupValueChanged>(this, RadioButtonGroup.GroupValueChangedMessage);
}
}
}
bool MatchesScope(RadioButtonScopeMessage message)
{
return RadioButtonGroup.GetVisualRoot(this) == message.Scope;
}
void HandleRadioButtonGroupSelectionChanged(RadioButton selected, RadioButtonGroupSelectionChanged args)
{
if (!IsChecked || selected == this || string.IsNullOrEmpty(GroupName) || GroupName != selected.GroupName || !MatchesScope(args))
{
return;
}
IsChecked = false;
}
void HandleRadioButtonGroupValueChanged(Maui.ILayout layout, RadioButtonGroupValueChanged args)
{
if (IsChecked || string.IsNullOrEmpty(GroupName) || GroupName != args.GroupName || Value != args.Value || !MatchesScope(args))
{
return;
}
IsChecked = true;
}
static void BindToTemplatedParent(BindableObject bindableObject, params BindableProperty[] properties)
{
foreach (var property in properties)
{
bindableObject.SetBinding(property, new Binding(property.PropertyName,
source: RelativeBindingSource.TemplatedParent));
}
}
static View BuildDefaultTemplate()
{
var frame = new Frame
{
HasShadow = false,
Padding = 6
};
BindToTemplatedParent(frame, BackgroundColorProperty, Microsoft.Maui.Controls.Frame.BorderColorProperty, HorizontalOptionsProperty,
MarginProperty, OpacityProperty, RotationProperty, ScaleProperty, ScaleXProperty, ScaleYProperty,
TranslationYProperty, TranslationXProperty, VerticalOptionsProperty);
var grid = new Grid
{
RowSpacing = 0,
ColumnDefinitions = new ColumnDefinitionCollection {
new ColumnDefinition { Width = GridLength.Auto },
new ColumnDefinition { Width = GridLength.Star }
},
RowDefinitions = new RowDefinitionCollection {
new RowDefinition { Height = GridLength.Auto }
}
};
var normalEllipse = new Ellipse
{
Fill = Brush.Transparent,
Aspect = Stretch.Uniform,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
HeightRequest = 21,
WidthRequest = 21,
StrokeThickness = 2,
Stroke = RadioButtonThemeColor,
InputTransparent = true
};
var checkMark = new Ellipse
{
Fill = RadioButtonCheckMarkThemeColor,
Aspect = Stretch.Uniform,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
HeightRequest = 11,
WidthRequest = 11,
Opacity = 0,
InputTransparent = true
};
var contentPresenter = new ContentPresenter
{
HorizontalOptions = LayoutOptions.Fill,
VerticalOptions = LayoutOptions.Fill
};
contentPresenter.SetBinding(MarginProperty, new Binding("Padding", source: RelativeBindingSource.TemplatedParent));
contentPresenter.SetBinding(BackgroundColorProperty, new Binding(BackgroundColorProperty.PropertyName,
source: RelativeBindingSource.TemplatedParent));
grid.Add(normalEllipse);
grid.Add(checkMark);
grid.Add(contentPresenter, 1, 0);
frame.Content = grid;
INameScope nameScope = new NameScope();
NameScope.SetNameScope(frame, nameScope);
nameScope.RegisterName(TemplateRootName, frame);
nameScope.RegisterName(UncheckedButton, normalEllipse);
nameScope.RegisterName(CheckedIndicator, checkMark);
nameScope.RegisterName("ContentPresenter", contentPresenter);
VisualStateGroupList visualStateGroups = new VisualStateGroupList();
var common = new VisualStateGroup() { Name = "Common" };
common.States.Add(new VisualState() { Name = VisualStateManager.CommonStates.Normal });
common.States.Add(new VisualState() { Name = VisualStateManager.CommonStates.Disabled });
visualStateGroups.Add(common);
var checkedStates = new VisualStateGroup() { Name = "CheckedStates" };
VisualState checkedVisualState = new VisualState() { Name = CheckedVisualState };
checkedVisualState.Setters.Add(new Setter() { Property = OpacityProperty, TargetName = CheckedIndicator, Value = 1 });
checkedVisualState.Setters.Add(new Setter() { Property = Shape.StrokeProperty, TargetName = UncheckedButton, Value = RadioButtonCheckMarkThemeColor });
checkedStates.States.Add(checkedVisualState);
VisualState uncheckedVisualState = new VisualState() { Name = UncheckedVisualState };
uncheckedVisualState.Setters.Add(new Setter() { Property = OpacityProperty, TargetName = CheckedIndicator, Value = 0 });
uncheckedVisualState.Setters.Add(new Setter() { Property = Shape.StrokeProperty, TargetName = UncheckedButton, Value = RadioButtonThemeColor });
checkedStates.States.Add(uncheckedVisualState);
visualStateGroups.Add(checkedStates);
VisualStateManager.SetVisualStateGroups(frame, visualStateGroups);
return frame;
}
/// <include file="../../docs/Microsoft.Maui.Controls/RadioButton.xml" path="//Member[@MemberName='ContentAsString']/Docs" />
public string ContentAsString()
{
var content = Content;
if (content is View)
{
Application.Current?.FindMauiContext()?.CreateLogger<RadioButton>()?.LogWarning("Warning - {RuntimePlatform} does not support View as the {PropertyName} property of RadioButton; the return value of the ToString() method will be displayed instead.", Device.RuntimePlatform, ContentProperty.PropertyName);
}
return content?.ToString();
}
}
}
| 38.388704 | 307 | 0.744526 | [
"MIT"
] | Xero-9/maui | src/Controls/src/Core/RadioButton.cs | 23,110 | C# |
/*
Copyright 2014 Alex Dyachenko
This file is part of the MPIR Library.
The MPIR Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
The MPIR Library 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 GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the MPIR Library. If not, see http://www.gnu.org/licenses/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MPIR.Tests.HugeFloatTests
{
[TestClass]
public class ExpressionTests
{
[TestInitialize]
public void Setup()
{
HugeFloat.DefaultPrecision = 64;
}
[TestMethod]
public void FloatTestAllExpressions()
{
var baseExpr = typeof(FloatExpression);
var allExpressions =
baseExpr.Assembly.GetTypes()
.Where(x => baseExpr.IsAssignableFrom(x) && !x.IsAbstract)
.ToList();
var one = Platform.Ui(1UL, 1U);
using (var a = new HugeFloat(-9))
using (var b = new HugeFloat(4))
using (var c = new HugeInt(3))
using(var r = MpirRandom.Default())
{
var expr = a + (-a * 2) * 3 * (a.Abs() * -2 + -64 + a * a) + (one * 116U) + a;
VerifyPartialResult(r, expr, 44);
expr = expr + a * 5 + (a+b) * (b + 1) * (b + -3) * b + (b * -a) - (b * (one * 25U)) - a + (b << 3) - ((a*b) << 1);
VerifyPartialResult(r, expr, -52);
expr = expr - 2 - 3U + (b - (a << 1)) + (b * b - 15U) * (b - a) * (a - 11) * (b - (one * 3U)) - (-340 - a) + ((one * 20U) - b);
VerifyPartialResult(r, expr, 52);
expr = expr + (-7 - 2 * a) + (28U - 4 * b) + -(a + b * 2) + (3 * a).Abs();
VerifyPartialResult(r, expr, 103);
expr = 36 * (expr / a + expr / (3 * b) - a / b) - b / (a + 10) + 6;
VerifyPartialResult(r, expr, -20);
expr = expr + (b >> 1) + ((b / -7) + (a / (one * 7U))) * 7 + (7 / a) - ((one * 2U) / (b + 5));
VerifyPartialResult(r, expr, -32);
expr = expr - (b + 13 + 64) / a / -3;
VerifyPartialResult(r, expr, -35);
expr = expr + b.SquareRoot() + HugeFloat.SquareRoot(25) + ((b - 2) ^ 3) - (-b).RelativeDifferenceFrom(a + 1);
VerifyPartialResult(r, expr, -19);
expr = expr - (a / 4).Floor() + (b / 3).Ceiling() - (a / b).Truncate();
VerifyPartialResult(r, expr, -12);
expr = expr + (r.GetFloatBits(64) * 10).Ceiling();
VerifyPartialResult(r, expr, -10);
//float random generation seems to give different results in Win32 and Win64. Thus, we're having to adjust the results for Win32.
expr = expr + (r.GetFloatLimbsChunky(128 / MpirSettings.BITS_PER_LIMB, 256 / MpirSettings.BITS_PER_LIMB) << 233 >> Platform.Ui(0, 480)).Ceiling();
VerifyPartialResult(r, expr, -6);
expr = expr + (r.GetFloat() * 10).Floor() - Platform.Ui(0, 3);
VerifyPartialResult(r, expr, -2);
expr = expr + (r.GetFloatChunky(3) << 101 >> Platform.Ui(177, 23)).Truncate();
VerifyPartialResult(r, expr, 13);
MarkExpressionsUsed(allExpressions, expr);
}
Assert.AreEqual(0, allExpressions.Count, "Expression types not exercised: " + string.Join("",
allExpressions.Select(x => Environment.NewLine + x.Name).OrderBy(x => x)));
}
private void VerifyPartialResult(MpirRandom rnd, FloatExpression expr, long expected)
{
rnd.Seed(123);
using (var r = new HugeFloat())
{
using (var exp = new HugeFloat(expected))
using (var epsilon = new HugeFloat("0.001"))
{
r.Value = expr;
Assert.IsTrue(r - epsilon < exp && r + epsilon > exp, "Expected {0}, Actual {1}", exp, r);
}
}
}
private void MarkExpressionsUsed(List<Type> allExpressions, FloatExpression expr)
{
var type = expr.GetType();
allExpressions.Remove(type);
var children = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(x => typeof(FloatExpression).IsAssignableFrom(x.FieldType))
.Select(x => (FloatExpression)x.GetValue(expr))
.Where(x => x != null)
.ToList();
foreach (var childExpr in children)
MarkExpressionsUsed(allExpressions, childExpr);
}
}
}
| 43.322314 | 162 | 0.540824 | [
"Apache-2.0"
] | CrypToolProject/CrypTool-2 | LibSource/mpir/mpir.net/mpir.net-tests/HugeFloatTests/ExpressionTests.cs | 5,244 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Business_Management_WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
| 22.241379 | 45 | 0.71938 | [
"MIT"
] | mota-b/Business-Management | Business-Management_WPF/MainWindow.xaml.cs | 647 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Runtime.Loader
{
public partial class AssemblyLoadContext
{
// Keep in sync with MonoManagedAssemblyLoadContextInternalState in object-internals.h
private enum InternalState
{
/// <summary>
/// The ALC is alive (default)
/// </summary>
Alive,
/// <summary>
/// The unload process has started, the Unloading event will be called
/// once the underlying LoaderAllocator has been finalized
/// </summary>
Unloading
}
private static volatile Dictionary<long, WeakReference<AssemblyLoadContext>>? s_allContexts;
private static long s_nextId;
[MemberNotNull(nameof(s_allContexts))]
private static Dictionary<long, WeakReference<AssemblyLoadContext>> AllContexts =>
s_allContexts ??
Interlocked.CompareExchange(ref s_allContexts, new Dictionary<long, WeakReference<AssemblyLoadContext>>(), null) ??
s_allContexts;
#region private data members
// If you modify this field, you must also update the
// AssemblyLoadContextBaseObject structure in object.h
// and MonoManagedAssemblyLoadContext in object-internals.h
// Contains the reference to VM's representation of the AssemblyLoadContext
private readonly IntPtr _nativeAssemblyLoadContext;
#endregion
// synchronization primitive to protect against usage of this instance while unloading
private readonly object _unloadLock;
private event Func<Assembly, string, IntPtr>? _resolvingUnmanagedDll;
private event Func<AssemblyLoadContext, AssemblyName, Assembly>? _resolving;
private event Action<AssemblyLoadContext>? _unloading;
private readonly string? _name;
// Id used by s_allContexts
private readonly long _id;
// Indicates the state of this ALC (Alive or in Unloading state)
private InternalState _state;
private readonly bool _isCollectible;
protected AssemblyLoadContext() : this(false, false, null)
{
}
protected AssemblyLoadContext(bool isCollectible) : this(false, isCollectible, null)
{
}
public AssemblyLoadContext(string? name, bool isCollectible = false) : this(false, isCollectible, name)
{
}
private protected AssemblyLoadContext(bool representsTPALoadContext, bool isCollectible, string? name)
{
// Initialize the VM side of AssemblyLoadContext if not already done.
_isCollectible = isCollectible;
_name = name;
// The _unloadLock needs to be assigned after the IsCollectible to ensure proper behavior of the finalizer
// even in case the following allocation fails or the thread is aborted between these two lines.
_unloadLock = new object();
if (!isCollectible)
{
// For non collectible AssemblyLoadContext, the finalizer should never be called and thus the AssemblyLoadContext should not
// be on the finalizer queue.
GC.SuppressFinalize(this);
}
// If this is a collectible ALC, we are creating a weak handle tracking resurrection otherwise we use a strong handle
var thisHandle = GCHandle.Alloc(this, IsCollectible ? GCHandleType.WeakTrackResurrection : GCHandleType.Normal);
var thisHandlePtr = GCHandle.ToIntPtr(thisHandle);
_nativeAssemblyLoadContext = InitializeAssemblyLoadContext(thisHandlePtr, representsTPALoadContext, isCollectible);
// Add this instance to the list of alive ALC
Dictionary<long, WeakReference<AssemblyLoadContext>> allContexts = AllContexts;
lock (allContexts)
{
_id = s_nextId++;
allContexts.Add(_id, new WeakReference<AssemblyLoadContext>(this, true));
}
}
~AssemblyLoadContext()
{
// Use the _unloadLock as a guard to detect the corner case when the constructor of the AssemblyLoadContext was not executed
// e.g. due to the JIT failing to JIT it.
if (_unloadLock != null)
{
// Only valid for a Collectible ALC. Non-collectible ALCs have the finalizer suppressed.
Debug.Assert(IsCollectible);
// We get here only in case the explicit Unload was not initiated.
Debug.Assert(_state != InternalState.Unloading);
InitiateUnload();
}
}
private void RaiseUnloadEvent()
{
// Ensure that we raise the Unload event only once
Interlocked.Exchange(ref _unloading, null!)?.Invoke(this);
}
private void InitiateUnload()
{
RaiseUnloadEvent();
// When in Unloading state, we are not supposed to be called on the finalizer
// as the native side is holding a strong reference after calling Unload
lock (_unloadLock)
{
Debug.Assert(_state == InternalState.Alive);
var thisStrongHandle = GCHandle.Alloc(this, GCHandleType.Normal);
var thisStrongHandlePtr = GCHandle.ToIntPtr(thisStrongHandle);
// The underlying code will transform the original weak handle
// created by InitializeLoadContext to a strong handle
PrepareForAssemblyLoadContextRelease(_nativeAssemblyLoadContext, thisStrongHandlePtr);
_state = InternalState.Unloading;
}
Dictionary<long, WeakReference<AssemblyLoadContext>> allContexts = AllContexts;
lock (allContexts)
{
allContexts.Remove(_id);
}
}
public IEnumerable<Assembly> Assemblies
{
get
{
foreach (Assembly a in GetLoadedAssemblies())
{
AssemblyLoadContext? alc = GetLoadContext(a);
if (alc == this)
{
yield return a;
}
}
}
}
// Event handler for resolving native libraries.
// This event is raised if the native library could not be resolved via
// the default resolution logic [including AssemblyLoadContext.LoadUnmanagedDll()]
//
// Inputs: Invoking assembly, and library name to resolve
// Returns: A handle to the loaded native library
public event Func<Assembly, string, IntPtr>? ResolvingUnmanagedDll
{
#if MONO
[DynamicDependency(nameof(MonoResolveUnmanagedDllUsingEvent))]
#endif
add
{
_resolvingUnmanagedDll += value;
}
remove
{
_resolvingUnmanagedDll -= value;
}
}
// Event handler for resolving managed assemblies.
// This event is raised if the managed assembly could not be resolved via
// the default resolution logic [including AssemblyLoadContext.Load()]
//
// Inputs: The AssemblyLoadContext and AssemblyName to be loaded
// Returns: The Loaded assembly object.
public event Func<AssemblyLoadContext, AssemblyName, Assembly?>? Resolving
{
#if MONO
[DynamicDependency(nameof(MonoResolveUsingResolvingEvent))]
#endif
add
{
_resolving += value;
}
remove
{
_resolving -= value;
}
}
public event Action<AssemblyLoadContext>? Unloading
{
add
{
_unloading += value;
}
remove
{
_unloading -= value;
}
}
#region AppDomainEvents
// Occurs when an Assembly is loaded
#if MONO
[method: DynamicDependency(nameof(OnAssemblyLoad))]
#endif
internal static event AssemblyLoadEventHandler? AssemblyLoad;
// Occurs when resolution of type fails
#if MONO
[method: DynamicDependency(nameof(OnTypeResolve))]
#endif
internal static event ResolveEventHandler? TypeResolve;
// Occurs when resolution of resource fails
#if MONO
[method: DynamicDependency(nameof(OnResourceResolve))]
#endif
internal static event ResolveEventHandler? ResourceResolve;
// Occurs when resolution of assembly fails
// This event is fired after resolve events of AssemblyLoadContext fails
#if MONO
[method: DynamicDependency(nameof(OnAssemblyResolve))]
#endif
internal static event ResolveEventHandler? AssemblyResolve;
#endregion
public static AssemblyLoadContext Default => DefaultAssemblyLoadContext.s_loadContext;
public bool IsCollectible => _isCollectible;
public string? Name => _name;
public override string ToString() => $"\"{Name}\" {GetType()} #{_id}";
public static IEnumerable<AssemblyLoadContext> All
{
get
{
_ = Default; // Ensure default is initialized
Dictionary<long, WeakReference<AssemblyLoadContext>>? allContexts = s_allContexts;
Debug.Assert(allContexts != null, "Creating the default context should have initialized the contexts collection.");
WeakReference<AssemblyLoadContext>[] alcSnapshot;
lock (allContexts)
{
// To make this thread safe we need a quick snapshot while locked
alcSnapshot = new WeakReference<AssemblyLoadContext>[allContexts.Count];
int pos = 0;
foreach (KeyValuePair<long, WeakReference<AssemblyLoadContext>> item in allContexts)
{
alcSnapshot[pos++] = item.Value;
}
}
foreach (WeakReference<AssemblyLoadContext> weakAlc in alcSnapshot)
{
if (weakAlc.TryGetTarget(out AssemblyLoadContext? alc))
{
yield return alc;
}
}
}
}
/// <summary>
/// Get or sets the function that is used to create the AssemblyLoadContext when a C++/CLI assembly
/// (an assembly that is native library and .net assembly at the same time) is loaded via its native entry point.
/// When the property is set to null (default) the mixed assembly is loaded such that its dependencies are isolated.
/// </summary>
public static Func<string, AssemblyLoadContext>? MixedAssemblyLoadContextFactory
{
get
{
#if MONO
throw new PlatformNotSupportedException();
#else
return Internal.Runtime.InteropServices.InMemoryAssemblyLoader.AssemblyLoadContextFactory;
#endif
}
set
{
#if MONO
throw new PlatformNotSupportedException();
#else
Internal.Runtime.InteropServices.InMemoryAssemblyLoader.AssemblyLoadContextFactory = value;
#endif
}
}
// Helper to return AssemblyName corresponding to the path of an IL assembly
public static AssemblyName GetAssemblyName(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
return AssemblyName.GetAssemblyName(assemblyPath);
}
// Custom AssemblyLoadContext implementations can override this
// method to perform custom processing and use one of the protected
// helpers above to load the assembly.
protected virtual Assembly? Load(AssemblyName assemblyName)
{
return null;
}
#if !CORERT
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
if (assemblyName == null)
throw new ArgumentNullException(nameof(assemblyName));
// Attempt to load the assembly, using the same ordering as static load, in the current load context.
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.InternalLoad(assemblyName, ref stackMark, this);
}
#endif
// These methods load assemblies into the current AssemblyLoadContext
// They may be used in the implementation of an AssemblyLoadContext derivation
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public Assembly LoadFromAssemblyPath(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
if (PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, assemblyPath), nameof(assemblyPath));
}
lock (_unloadLock)
{
VerifyIsAlive();
return InternalLoadFromPath(assemblyPath, null);
}
}
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public Assembly LoadFromNativeImagePath(string nativeImagePath, string? assemblyPath)
{
if (nativeImagePath == null)
{
throw new ArgumentNullException(nameof(nativeImagePath));
}
if (PathInternal.IsPartiallyQualified(nativeImagePath))
{
throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, nativeImagePath), nameof(nativeImagePath));
}
if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, assemblyPath), nameof(assemblyPath));
}
lock (_unloadLock)
{
VerifyIsAlive();
return InternalLoadFromPath(assemblyPath, nativeImagePath);
}
}
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public Assembly LoadFromStream(Stream assembly)
{
return LoadFromStream(assembly, null);
}
[RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")]
public Assembly LoadFromStream(Stream assembly, Stream? assemblySymbols)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
int iAssemblyStreamLength = (int)assembly.Length;
if (iAssemblyStreamLength <= 0)
{
throw new BadImageFormatException(SR.BadImageFormat_BadILFormat);
}
// Allocate the byte[] to hold the assembly
byte[] arrAssembly = new byte[iAssemblyStreamLength];
// Copy the assembly to the byte array
assembly.Read(arrAssembly, 0, iAssemblyStreamLength);
// Get the symbol stream in byte[] if provided
byte[]? arrSymbols = null;
if (assemblySymbols != null)
{
int iSymbolLength = (int)assemblySymbols.Length;
arrSymbols = new byte[iSymbolLength];
assemblySymbols.Read(arrSymbols, 0, iSymbolLength);
}
lock (_unloadLock)
{
VerifyIsAlive();
return InternalLoad(arrAssembly, arrSymbols);
}
}
// This method provides a way for overriders of LoadUnmanagedDll() to load an unmanaged DLL from a specific path in a
// platform-independent way. The DLL is loaded with default load flags.
protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath)
{
if (unmanagedDllPath == null)
{
throw new ArgumentNullException(nameof(unmanagedDllPath));
}
if (unmanagedDllPath.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyPath, nameof(unmanagedDllPath));
}
if (PathInternal.IsPartiallyQualified(unmanagedDllPath))
{
throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, unmanagedDllPath), nameof(unmanagedDllPath));
}
return NativeLibrary.Load(unmanagedDllPath);
}
// Custom AssemblyLoadContext implementations can override this
// method to perform the load of unmanaged native dll
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
// defer to default coreclr policy of loading unmanaged dll
return IntPtr.Zero;
}
public void Unload()
{
if (!IsCollectible)
{
throw new InvalidOperationException(SR.AssemblyLoadContext_Unload_CannotUnloadIfNotCollectible);
}
GC.SuppressFinalize(this);
InitiateUnload();
}
internal static void OnProcessExit()
{
Dictionary<long, WeakReference<AssemblyLoadContext>>? allContexts = s_allContexts;
if (allContexts is null)
{
// If s_allContexts was never initialized, there are no contexts for which to raise an unload event.
return;
}
lock (allContexts)
{
foreach (KeyValuePair<long, WeakReference<AssemblyLoadContext>> alcAlive in allContexts)
{
if (alcAlive.Value.TryGetTarget(out AssemblyLoadContext? alc))
{
alc.RaiseUnloadEvent();
}
}
}
}
private void VerifyIsAlive()
{
if (_state != InternalState.Alive)
{
throw new InvalidOperationException(SR.AssemblyLoadContext_Verify_NotUnloading);
}
}
private static AsyncLocal<AssemblyLoadContext?>? s_asyncLocalCurrent;
/// <summary>Nullable current AssemblyLoadContext used for context sensitive reflection APIs</summary>
/// <remarks>
/// This is an advanced setting used in reflection assembly loading scenarios.
///
/// There are a set of contextual reflection APIs which load managed assemblies through an inferred AssemblyLoadContext.
/// * <see cref="System.Activator.CreateInstance" />
/// * <see cref="System.Reflection.Assembly.Load" />
/// * <see cref="System.Reflection.Assembly.GetType" />
/// * <see cref="System.Type.GetType" />
///
/// When CurrentContextualReflectionContext is null, the AssemblyLoadContext is inferred.
/// The inference logic is simple.
/// * For static methods, it is the AssemblyLoadContext which loaded the method caller's assembly.
/// * For instance methods, it is the AssemblyLoadContext which loaded the instance's assembly.
///
/// When this property is set, the CurrentContextualReflectionContext value is used by these contextual reflection APIs for loading.
///
/// This property is typically set in a using block by
/// <see cref="System.Runtime.Loader.AssemblyLoadContext.EnterContextualReflection"/>.
///
/// The property is stored in an AsyncLocal<AssemblyLoadContext>. This means the setting can be unique for every async or thread in the process.
///
/// For more details see https://github.com/dotnet/runtime/blob/main/docs/design/features/AssemblyLoadContext.ContextualReflection.md
/// </remarks>
public static AssemblyLoadContext? CurrentContextualReflectionContext => s_asyncLocalCurrent?.Value;
private static void SetCurrentContextualReflectionContext(AssemblyLoadContext? value)
{
if (s_asyncLocalCurrent == null)
{
Interlocked.CompareExchange<AsyncLocal<AssemblyLoadContext?>?>(ref s_asyncLocalCurrent, new AsyncLocal<AssemblyLoadContext?>(), null);
}
s_asyncLocalCurrent!.Value = value; // Remove ! when compiler specially-recognizes CompareExchange for nullability
}
/// <summary>Enter scope using this AssemblyLoadContext for ContextualReflection</summary>
/// <returns>A disposable ContextualReflectionScope for use in a using block</returns>
/// <remarks>
/// Sets CurrentContextualReflectionContext to this instance.
/// <see cref="System.Runtime.Loader.AssemblyLoadContext.CurrentContextualReflectionContext"/>
///
/// Returns a disposable ContextualReflectionScope for use in a using block. When the using calls the
/// Dispose() method, it restores the ContextualReflectionScope to its previous value.
/// </remarks>
public ContextualReflectionScope EnterContextualReflection()
{
return new ContextualReflectionScope(this);
}
/// <summary>Enter scope using this AssemblyLoadContext for ContextualReflection</summary>
/// <param name="activating">Set CurrentContextualReflectionContext to the AssemblyLoadContext which loaded activating.</param>
/// <returns>A disposable ContextualReflectionScope for use in a using block</returns>
/// <remarks>
/// Sets CurrentContextualReflectionContext to to the AssemblyLoadContext which loaded activating.
/// <see cref="System.Runtime.Loader.AssemblyLoadContext.CurrentContextualReflectionContext"/>
///
/// Returns a disposable ContextualReflectionScope for use in a using block. When the using calls the
/// Dispose() method, it restores the ContextualReflectionScope to its previous value.
/// </remarks>
public static ContextualReflectionScope EnterContextualReflection(Assembly? activating)
{
if (activating == null)
return new ContextualReflectionScope(null);
AssemblyLoadContext? assemblyLoadContext = GetLoadContext(activating);
if (assemblyLoadContext == null)
{
// All RuntimeAssemblies & Only RuntimeAssemblies have an AssemblyLoadContext
throw new ArgumentException(SR.Arg_MustBeRuntimeAssembly, nameof(activating));
}
return assemblyLoadContext.EnterContextualReflection();
}
/// <summary>Opaque disposable struct used to restore CurrentContextualReflectionContext</summary>
/// <remarks>
/// This is an implmentation detail of the AssemblyLoadContext.EnterContextualReflection APIs.
/// It is a struct, to avoid heap allocation.
/// It is required to be public to avoid boxing.
/// <see cref="System.Runtime.Loader.AssemblyLoadContext.EnterContextualReflection"/>
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public struct ContextualReflectionScope : IDisposable
{
private readonly AssemblyLoadContext? _activated;
private readonly AssemblyLoadContext? _predecessor;
private readonly bool _initialized;
internal ContextualReflectionScope(AssemblyLoadContext? activating)
{
_predecessor = AssemblyLoadContext.CurrentContextualReflectionContext;
AssemblyLoadContext.SetCurrentContextualReflectionContext(activating);
_activated = activating;
_initialized = true;
}
public void Dispose()
{
if (_initialized)
{
// Do not clear initialized. Always restore the _predecessor in Dispose()
// _initialized = false;
AssemblyLoadContext.SetCurrentContextualReflectionContext(_predecessor);
}
}
}
#if !CORERT
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static Assembly? Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target)!;
return context.ResolveUsingLoad(assemblyName);
}
[UnconditionalSuppressMessage("SingleFile", "IL3000: Avoid accessing Assembly file path when publishing as a single file",
Justification = "The code handles the Assembly.Location equals null")]
private Assembly? GetFirstResolvedAssemblyFromResolvingEvent(AssemblyName assemblyName)
{
Assembly? resolvedAssembly = null;
Func<AssemblyLoadContext, AssemblyName, Assembly>? resolvingHandler = _resolving;
if (resolvingHandler != null)
{
// Loop through the event subscribers and return the first non-null Assembly instance
foreach (Func<AssemblyLoadContext, AssemblyName, Assembly> handler in resolvingHandler.GetInvocationList())
{
resolvedAssembly = handler(this, assemblyName);
#if CORECLR
if (AssemblyLoadContext.IsTracingEnabled())
{
AssemblyLoadContext.TraceResolvingHandlerInvoked(
assemblyName.FullName,
handler.Method.Name,
this != AssemblyLoadContext.Default ? ToString() : Name,
resolvedAssembly?.FullName,
resolvedAssembly != null && !resolvedAssembly.IsDynamic ? resolvedAssembly.Location : null);
}
#endif // CORECLR
if (resolvedAssembly != null)
{
return resolvedAssembly;
}
}
}
return null;
}
private static Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string? requestedSimpleName)
{
if (string.IsNullOrEmpty(requestedSimpleName))
{
throw new ArgumentException(SR.ArgumentNull_AssemblyNameName);
}
// Get the name of the loaded assembly
string? loadedSimpleName = null;
// Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly
// which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder),
// we need to check for RuntimeAssembly.
RuntimeAssembly? rtLoadedAssembly = GetRuntimeAssembly(assembly);
if (rtLoadedAssembly != null)
{
loadedSimpleName = rtLoadedAssembly.GetSimpleName();
}
// The simple names should match at the very least
if (string.IsNullOrEmpty(loadedSimpleName) || !requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase))
{
throw new InvalidOperationException(SR.Argument_CustomAssemblyLoadContextRequestedNameMismatch);
}
return assembly;
}
private Assembly? ResolveUsingLoad(AssemblyName assemblyName)
{
string? simpleName = assemblyName.Name;
Assembly? assembly = Load(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
return assembly;
}
private Assembly? ResolveUsingEvent(AssemblyName assemblyName)
{
string? simpleName = assemblyName.Name;
// Invoke the Resolving event callbacks if wired up
Assembly? assembly = GetFirstResolvedAssemblyFromResolvingEvent(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
return assembly;
}
// This method is called by the VM.
private static void OnAssemblyLoad(RuntimeAssembly assembly)
{
AssemblyLoad?.Invoke(AppDomain.CurrentDomain, new AssemblyLoadEventArgs(assembly));
}
// This method is called by the VM.
private static RuntimeAssembly? OnResourceResolve(RuntimeAssembly assembly, string resourceName)
{
return InvokeResolveEvent(ResourceResolve, assembly, resourceName);
}
// This method is called by the VM
private static RuntimeAssembly? OnTypeResolve(RuntimeAssembly assembly, string typeName)
{
return InvokeResolveEvent(TypeResolve, assembly, typeName);
}
// This method is called by the VM.
private static RuntimeAssembly? OnAssemblyResolve(RuntimeAssembly assembly, string assemblyFullName)
{
return InvokeResolveEvent(AssemblyResolve, assembly, assemblyFullName);
}
[UnconditionalSuppressMessage("SingleFile", "IL3000: Avoid accessing Assembly file path when publishing as a single file",
Justification = "The code handles the Assembly.Location equals null")]
private static RuntimeAssembly? InvokeResolveEvent(ResolveEventHandler? eventHandler, RuntimeAssembly assembly, string name)
{
if (eventHandler == null)
return null;
var args = new ResolveEventArgs(name, assembly);
foreach (ResolveEventHandler handler in eventHandler.GetInvocationList())
{
Assembly? asm = handler(AppDomain.CurrentDomain, args);
#if CORECLR
if (eventHandler == AssemblyResolve && AssemblyLoadContext.IsTracingEnabled())
{
AssemblyLoadContext.TraceAssemblyResolveHandlerInvoked(
name,
handler.Method.Name,
asm?.FullName,
asm != null && !asm.IsDynamic ? asm.Location : null);
}
#endif // CORECLR
RuntimeAssembly? ret = GetRuntimeAssembly(asm);
if (ret != null)
return ret;
}
return null;
}
#endif // !CORERT
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "Satellite assemblies have no code in them and loading is not a problem")]
[UnconditionalSuppressMessage("SingleFile", "IL3000: Avoid accessing Assembly file path when publishing as a single file",
Justification = "This call is fine because native call runs before this and checks BindSatelliteResourceFromBundle")]
private Assembly? ResolveSatelliteAssembly(AssemblyName assemblyName)
{
// Called by native runtime when CultureName is not empty
Debug.Assert(assemblyName.CultureName?.Length > 0);
const string SatelliteSuffix = ".resources";
if (assemblyName.Name == null || !assemblyName.Name.EndsWith(SatelliteSuffix, StringComparison.Ordinal))
return null;
string parentAssemblyName = assemblyName.Name.Substring(0, assemblyName.Name.Length - SatelliteSuffix.Length);
Assembly parentAssembly = LoadFromAssemblyName(new AssemblyName(parentAssemblyName));
AssemblyLoadContext parentALC = GetLoadContext(parentAssembly)!;
string? parentDirectory = Path.GetDirectoryName(parentAssembly.Location);
if (parentDirectory == null)
return null;
string assemblyPath = Path.Combine(parentDirectory, assemblyName.CultureName!, $"{assemblyName.Name}.dll");
bool exists = System.IO.FileSystem.FileExists(assemblyPath);
if (!exists && PathInternal.IsCaseSensitive)
{
#if CORECLR
if (AssemblyLoadContext.IsTracingEnabled())
{
AssemblyLoadContext.TraceSatelliteSubdirectoryPathProbed(assemblyPath, HResults.COR_E_FILENOTFOUND);
}
#endif // CORECLR
assemblyPath = Path.Combine(parentDirectory, assemblyName.CultureName!.ToLowerInvariant(), $"{assemblyName.Name}.dll");
exists = System.IO.FileSystem.FileExists(assemblyPath);
}
Assembly? asm = exists ? parentALC.LoadFromAssemblyPath(assemblyPath) : null;
#if CORECLR
if (AssemblyLoadContext.IsTracingEnabled())
{
AssemblyLoadContext.TraceSatelliteSubdirectoryPathProbed(assemblyPath, exists ? HResults.S_OK : HResults.COR_E_FILENOTFOUND);
}
#endif // CORECLR
return asm;
}
internal IntPtr GetResolvedUnmanagedDll(Assembly assembly, string unmanagedDllName)
{
IntPtr resolvedDll = IntPtr.Zero;
Func<Assembly, string, IntPtr>? dllResolveHandler = _resolvingUnmanagedDll;
if (dllResolveHandler != null)
{
// Loop through the event subscribers and return the first non-null native library handle
foreach (Func<Assembly, string, IntPtr> handler in dllResolveHandler.GetInvocationList())
{
resolvedDll = handler(assembly, unmanagedDllName);
if (resolvedDll != IntPtr.Zero)
{
return resolvedDll;
}
}
}
return IntPtr.Zero;
}
}
internal sealed class DefaultAssemblyLoadContext : AssemblyLoadContext
{
internal static readonly AssemblyLoadContext s_loadContext = new DefaultAssemblyLoadContext();
internal DefaultAssemblyLoadContext() : base(true, false, "Default")
{
}
}
internal sealed class IndividualAssemblyLoadContext : AssemblyLoadContext
{
internal IndividualAssemblyLoadContext(string name) : base(false, false, name)
{
}
}
}
| 40.549943 | 158 | 0.620091 | [
"MIT"
] | szilvaa-adsk/runtime | src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs | 35,319 | C# |
namespace BlizzardApiReader.Diablo.Models
{
public class Skill
{
public string Slug { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public long Level { get; set; }
public string TooltipUrl { get; set; }
public string Description { get; set; }
public string DescriptionHtml { get; set; }
}
}
| 28 | 51 | 0.589286 | [
"MIT"
] | avivbiton/BlizzardApiReader | BlizzardApiReader.Diablo/Models/Skill.cs | 394 | C# |
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Text;
namespace AOTMapper.Benchmark.Data
{
public class UserEntity
{
public UserEntity()
{
}
public UserEntity(Guid id, string firstName, string lastName)
{
this.Id = id;
this.FirstName = firstName;
this.LastName = lastName;
}
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name { get; set; }
}
}
| 20.342857 | 69 | 0.566011 | [
"MIT"
] | byme8/AOTMapper | AOTMapper.Benchmark/Data/User.cs | 714 | C# |
namespace SampleCoinigy
{
using System.Windows;
using System.Windows.Threading;
public partial class App
{
private void ApplicationDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(MainWindow, e.Exception.ToString());
e.Handled = true;
}
}
} | 22.285714 | 110 | 0.775641 | [
"Apache-2.0"
] | DimTrdr/StockSharp | Samples/Coinigy/SampleCoinigy/App.xaml.cs | 312 | C# |
using System;
using System.Web;
using EPiServer.Cms.UI.AspNetIdentity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
[assembly: OwinStartup(typeof(TimeProperty.AlloySample.Startup))]
namespace TimeProperty.AlloySample
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Add CMS integration for ASP.NET Identity
app.AddCmsAspNetIdentity<ApplicationUser>();
// Remove to block registration of administrators
app.UseAdministratorRegistrationPage(() => HttpContext.Current.Request.IsLocal);
// Use cookie authentication
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString(Global.LoginPath),
Provider = new CookieAuthenticationProvider
{
// If the "/util/login.aspx" has been used for login otherwise you don't need it you can remove OnApplyRedirect.
OnApplyRedirect = cookieApplyRedirectContext =>
{
app.CmsOnCookieApplyRedirect(cookieApplyRedirectContext, cookieApplyRedirectContext.OwinContext.Get<ApplicationSignInManager<ApplicationUser>>());
},
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager<ApplicationUser>, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user))
}
});
}
}
}
| 41.877551 | 170 | 0.652534 | [
"Apache-2.0"
] | advanced-cms/time-property | src/TimeProperty.AlloySample/Startup.cs | 2,052 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace Squircle
{
public class InputHandler
{
KeyboardState _currentKeyboardState;
KeyboardState _previousKeyboardState;
GamePadState _currentGamepadState;
GamePadState _previousGamepadState;
public KeyboardState KeyboardState { get { return _currentKeyboardState; } }
public GamePadState GamePadState { get { return _currentGamepadState; } }
public InputHandler()
{
_currentKeyboardState = Keyboard.GetState();
_previousKeyboardState = _currentKeyboardState;
_currentGamepadState = GamePad.GetState(PlayerIndex.One);
_previousGamepadState = _currentGamepadState;
}
public bool IsUp(Keys key)
{
return _currentKeyboardState.IsKeyUp(key);
}
public bool IsUp(Buttons button)
{
return _currentGamepadState.IsConnected && _currentGamepadState.IsButtonUp(button);
}
public bool IsDown(Keys key)
{
return _currentKeyboardState.IsKeyDown(key);
}
public bool IsDown(Buttons button)
{
return _currentGamepadState.IsConnected && _currentGamepadState.IsButtonDown(button);
}
public bool WasTriggered(Keys key)
{
return _currentKeyboardState.IsKeyDown(key) && _previousKeyboardState.IsKeyUp(key);
}
public bool WasTriggered(Buttons button)
{
return _currentGamepadState.IsConnected && _currentGamepadState.IsButtonDown(button) && _previousGamepadState.IsButtonUp(button);
}
public bool WasReleased(Keys key)
{
return _previousKeyboardState.IsKeyDown(key) && _currentKeyboardState.IsKeyUp(key);
}
public bool WasReleased(Buttons button)
{
return _currentGamepadState.IsConnected && _currentGamepadState.IsButtonUp(button) && _previousGamepadState.IsButtonDown(button);
}
public void Update(GameTime gameTime)
{
_previousKeyboardState = _currentKeyboardState;
_currentKeyboardState = Keyboard.GetState();
_previousGamepadState = _currentGamepadState;
_currentGamepadState = GamePad.GetState(PlayerIndex.One);
}
}
}
| 31.444444 | 142 | 0.639183 | [
"MIT"
] | GretelF/squircle | source/Squircle/Squircle/InputHandler.cs | 2,549 | C# |
using System;
public static partial class Extension
{
/// <summary>
/// An object extension method that converts the @this to a nullable character.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a char?</returns>
public static char? ToNullableChar(this object @this)
{
return @this == null || @this == DBNull.Value ? (char?)null : Convert.ToChar(@this);
}
} | 31.785714 | 92 | 0.617978 | [
"MIT"
] | Cactus-Blade/Cactus.Blade.Core | Core/System.Object/Convert/ToValueType/Object.ToNullableChar.cs | 447 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace MyHeritage.App.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
}
}
| 24.857143 | 95 | 0.784483 | [
"MIT"
] | nimeshvaghasiya/MyHeritage | src/MyHeritage.App/Models/ApplicationUser.cs | 350 | C# |
using System.Collections.Generic;
using FootballApp.Services.Dtos.Standings;
namespace FootballApp.Services.DataServices.Contracts
{
public interface IStandingService
{
ICollection<StandingDto> GetByCountry(string country);
}
}
| 22.727273 | 62 | 0.772 | [
"MIT"
] | VanGog06/FootballApp | Services/FootballApp.Services.DataServices/Contracts/IStandingService.cs | 252 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Grasshopper.Kernel;
namespace Objectivism
{
class AccessChecker
{
private Dictionary<string, PropertyAccess> accessRecorder;
private HashSet<string> warningsToThrow;
private IGH_Component hostRef;
public AccessChecker(IGH_Component @this)
{
this.accessRecorder = new Dictionary<string, PropertyAccess>();
this.warningsToThrow = new HashSet<string>();
this.hostRef = @this;
}
public void AccessCheck(ObjectProperty prop, string name)
{
if (accessRecorder.ContainsKey(name))
{
if (accessRecorder[name] != prop.Access)
{
warningsToThrow.Add(name);
}
}
else
{
accessRecorder.Add(name, prop.Access);
}
}
public void ThrowWarnings()
{
foreach(var name in warningsToThrow)
{
hostRef.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Access not consistent for {name} property. Output data tree may be messy and not consistent");
}
}
public PropertyAccess BestGuessAccess(string name)
{
if(accessRecorder.ContainsKey(name))
{
return accessRecorder[name];
}
else
{
try
{
var data = hostRef.Params.Input[0].VolatileData.AllData(true);
foreach (var goo in data)
{
if (goo is GH_ObjectivismObject ghObj)
{
if (ghObj.Value.HasProperty(name))
{
return ghObj.Value.GetProperty(name).Access;
}
}
}
return PropertyAccess.Item;
}
catch
{
return PropertyAccess.Item;
}
}
}
}
}
| 29.039474 | 170 | 0.469869 | [
"MIT"
] | DominicBeer/Objectivism | Components/ComponentUtil/AccessChecker.cs | 2,209 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using System.Reflection;
using static Root;
partial struct Enums
{
public static Index<T> numeric<E,T>()
where E : unmanaged, Enum
where T : unmanaged
=> typeof(E).Fields().Select(f => ClrLiterals.value<T>(f));
}
} | 29.1 | 79 | 0.417526 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/clr/src/services/enums/numeric.cs | 582 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioSwitch : MonoBehaviour {
public AudioSource source;
public AudioClip switchTo;
void OnTriggerEnter2D(Collider2D other) {
switchAudio ();
}
void switchAudio() {
source.Stop();
source.loop = true;
source.PlayOneShot (switchTo);
}
}
| 17.3 | 42 | 0.745665 | [
"MIT"
] | chenvictor/lumohacks-2018 | Assets/MyAssets/MainCharacter/Controller/AudioSwitch.cs | 348 | C# |
using MIRI.Serialization;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.IO;
using System.Runtime.Serialization.Json;
namespace MIRI
{
/// <summary>
/// Provides methods used to search and scrape data from Manga-Updates.
/// </summary>
public class MangaUpdatesSearch : IMangaUpdatesSearch
{
/// <summary>
/// Initializes a new instance of the MangaUpdatesSearch class.
/// </summary>
public MangaUpdatesSearch()
{
}
public async Task<ISeriesData> SearchAsync(string series)
{
return await Task.Run(() => Search(series));
}
public async Task<ISeriesData> SearchAsync(string series, SearchResultOutput outputType)
{
return await Task.Run(() => Search(series, outputType));
}
public ISeriesData Search(string series)
{
return Search(series, SearchResultOutput.Json);
}
public ISeriesData Search(string series, SearchResultOutput outputType)
{
byte[] response = null;
string seriesSanitized = null;
Serialization.IResults results = null;
System.Collections.Specialized.NameValueCollection param = null;
try
{
seriesSanitized = Helpers.Search.FormatParameters(series);
param = new NameValueCollection();
param.Add("act", "series");
param.Add("stype", "title");
param.Add("session", string.Empty);
param.Add("search", seriesSanitized);
param.Add("x", "0");
param.Add("y", "0");
// Todo: Check, probably not best practice to convert an enum to string like this.
param.Add("output", outputType.ToString().ToLower());
response = Helpers.Downloader.Instance.UploadValues(new Uri(Properties.Resources.SeriesSearchUri), param);
if (response != null && response.Length > 0)
{
using (var serializeResults = new SerializeResults())
{
results = serializeResults.Serialize(response);
}
// Todo: Do a proper word-boundary comparison.
var item = results.Items.FirstOrDefault(i => string.Compare(i.Title, series, true) == 0);
var info = FetchSeriesData(item.Id);
return info;
}
else
{
return null;
}
}
finally
{
response = null;
seriesSanitized = null;
// Todo: Implement IDisposable and dispose.
results = null;
if (param != null)
{
param.Clear();
param = null;
}
}
}
public ISeriesData FetchSeriesData(int id)
{
return FetchSeriesData(new Uri(string.Format(Properties.Resources.SeriesUriFormat, id)));
}
public ISeriesData FetchSeriesData(Uri uri)
{
ISeriesData parsedContent = null;
parsedContent = new SeriesData(Helpers.Downloader.Instance.DownloadString(uri));
return parsedContent;
}
/// Todo: Move Search(string) code to FetchSeriesData
/// Search will do a literal search and return the results as IResults.
/// FetchSeriesData is intended to do what Search(string) currently does.
public ISeriesData FetchSeriesData(string series)
{
throw new NotImplementedException();
}
public IResults SearchSite(string query)
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("search", Helpers.Search.FormatParameters(query));
parameters.Add("x", "0");
parameters.Add("y", "0");
byte[] response = Helpers.Downloader.Instance.UploadValues(new Uri("https://www.mangaupdates.com/search.html"), parameters);
IResults results = null;
if (response.Length > 0)
{
////string resp = Encoding.UTF8.GetString(response);
////results.StartIndex = 0;
////results.TotalResults = 0;
////results.itemsPerPage = 0;
////IResultItem item = new Item()
////{
//// Id = 5
////};
// Todo: Uncomment
//results = new SerializeResultsSiteSearch().Serialize(response);
}
return results;
}
public ISiteSearchResult PerformSiteSearch(string query)
{
NameValueCollection parameters = new NameValueCollection();
parameters.Add("search", Helpers.Search.FormatParameters(query));
parameters.Add("x", "0");
parameters.Add("y", "0");
byte[] response = Helpers.Downloader.Instance.UploadValues(new Uri("https://www.mangaupdates.com/search.html"), parameters);
ISiteSearchResult results = null;
if (response.Length > 0)
{
// TODO: Uncomment
//results = new SerializeResultsSiteSearch().Serialize(response);
}
return results;
}
}
}
| 30.913514 | 136 | 0.543976 | [
"BSD-3-Clause"
] | JedBurke/MIRI | MIRI/MangaUpdatesSearch.cs | 5,721 | C# |
// ReSharper disable InconsistentNaming
namespace AlphaVantage.Net.Core
{
/// <summary>
/// Possible functions of Alpha Vantage API
/// </summary>
public enum ApiFunction
{
// Stock Time Series Data
TIME_SERIES_INTRADAY,
TIME_SERIES_DAILY,
TIME_SERIES_DAILY_ADJUSTED,
TIME_SERIES_WEEKLY,
TIME_SERIES_WEEKLY_ADJUSTED,
TIME_SERIES_MONTHLY,
TIME_SERIES_MONTHLY_ADJUSTED,
BATCH_STOCK_QUOTES,
// Foreign Exchange (FX)
FX_DAILY,
// Digital & Crypto Currencies
DIGITAL_CURRENCY_INTRADAY,
DIGITAL_CURRENCY_DAILY,
DIGITAL_CURRENCY_WEEKLY,
DIGITAL_CURRENCY_MONTHLY,
// Stock Technical Indicators
SMA,
EMA,
WMA,
DEMA,
TEMA,
TRIMA,
KAMA,
MAMA,
T3,
MACD,
MACDEXT,
STOCH,
STOCHF,
RSI,
STOCHRSI,
WILLR,
ADX,
ADXR,
APO,
PPO,
MOM,
BOP,
CCI,
CMO,
ROC,
ROCR,
AROON,
AROONOSC,
MFI,
TRIX,
ULTOSC,
DX,
MINUS_DI,
PLUS_DI,
MINUS_DM,
PLUS_DM,
BBANDS,
MIDPOINT,
MIDPRICE,
SAR,
TRANGE,
ATR,
NATR,
AD,
ADOSC,
OBV,
HT_TRENDLINE,
HT_SINE,
HT_TRENDMODE,
HT_DCPERIOD,
HT_DCPHASE,
HT_PHASOR,
// Sector Performances
SECTOR,
SYMBOL_SEARCH
}
} | 18.816092 | 47 | 0.485644 | [
"MIT"
] | infine8/AlphaVantage.Net | AlphaVantage.Net/src/AlphaVantage.Net.Core/ApiFunction.cs | 1,639 | C# |
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
using System;
using System.IO;
using System.Net;
namespace SignalR.Client._20.Http
{
public class HttpWebResponseWrapper : IResponse
{
private readonly HttpWebResponse m_response;
public HttpWebResponseWrapper(HttpWebResponse response)
{
m_response = response;
}
public string ReadAsString()
{
return HttpHelper.ReadAsString(m_response);
}
public Stream GetResponseStream()
{
return m_response.GetResponseStream();
}
public void Close()
{
((IDisposable)m_response).Dispose();
}
public bool IsFaulted { get; set; }
public Exception Exception { get; set; }
}
}
#endif | 21.447368 | 63 | 0.61227 | [
"MIT"
] | BrianPeek/Scavenger | src/Unity/Assets/PlayFabSdk/Shared/SignalR.NET20/Http/HttpWebResponseWrapper.cs | 817 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Builder SDK Github:
// https://github.com/Microsoft/BotBuilder
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Dialogs.Internals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Microsoft.Bot.Builder.History
{
/// <summary>
/// Class to collect and then replay activities as a transcript.
/// </summary>
public sealed class ReplayTranscript
{
private IBotToUser _botToUser;
private Func<IActivity, string> _header;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="botToUser">Where to replay transcript.</param>
/// <param name="header">Function for defining the transcript header on each message.</param>
public ReplayTranscript(IBotToUser botToUser, Func<IActivity, string> header = null)
{
_botToUser = botToUser;
if (_header == null)
{
_header = (activity) => $"({activity.From.Name} {activity.Timestamp:g})";
}
}
/// <summary>
/// Replay activity to IBotToUser.
/// </summary>
/// <param name="activity">Activity.</param>
/// <returns>Task.</returns>
public async Task Replay(IActivity activity)
{
if (activity is IMessageActivity)
{
var msg = _botToUser.MakeMessage();
msg.Text = _header(activity);
await _botToUser.PostAsync(msg);
var act = JsonConvert.DeserializeObject<Activity>(JsonConvert.SerializeObject(activity));
if (act.ChannelId != msg.ChannelId)
{
act.ChannelData = null;
}
act.From = msg.From;
act.Recipient = msg.Recipient;
act.ReplyToId = msg.ReplyToId;
act.ChannelId = msg.ChannelId;
act.Conversation = msg.Conversation;
await _botToUser.PostAsync(act);
}
}
}
}
| 37.329787 | 106 | 0.62126 | [
"MIT"
] | KenichiKawamura/MS-BotBuilder | CSharp/Library/Microsoft.Bot.Builder.History/ReplayTranscript.cs | 3,511 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HallOfBeorn.Models.LotR.Scenarios.Haradrim
{
public class BeneathTheSandsScenario : Scenarios.TheSandsOfHarad.TheSandsOfHaradScenario
{
public BeneathTheSandsScenario()
{
Title = "Beneath the Sands";
ProductName = "Beneath the Sands";
GroupName = "Haradrim";
Number = 3;
RulesUrl = "https://images-cdn.fantasyflightgames.com/filer_public/a5/a8/a5a88cea-5920-4c3c-b9c0-aa8d7bd3c455/mec58_web_beneath_the_sands-rules.pdf";
QuestCompanionSlug = "haradrim-cycle-quest-beneath-the-sands";
DifficultyRating = 6.0f;
Votes = 3;
AddMrUnderhillLink(Title + " - Vigilant Dúnadan", "FWCsh8cnAY4");
AddWanderingTookVideoLink("Twitch Recast: " + Title, "wKhhTLSemJE");
AddVisionOfThePalantirLink("https://visionofthepalantir.com/2020/07/28/beneath-the-sands/");
AddEncounterSet(EncounterSet.BeneathTheSands);
AddEncounterSet(EncounterSet.DesertCreatures);
AddEncounterSet(EncounterSet.HaradTerritory);
AddQuestCardId("Searching-the-Caves-BtS");
AddQuestCardId("Getting-Closer-BtS");
AddQuestCardId("The-Spiders'-Hive-BtS");
excludeDesertCreatures();
excludeHaradTerritory();
/*
ExcludeFromEasyMode("-BtS", 1);
ExcludeFromEasyMode("-BtS", 1);
ExcludeFromEasyMode("-BtS", 1);
ExcludeFromEasyMode("-BtS", 1);
*/
}
}
} | 37.066667 | 161 | 0.618106 | [
"MIT"
] | danpoage/hall-of-beorn | src/HallOfBeorn/Models/LotR/Scenarios/Haradrim/BeneathTheSandsScenario.cs | 1,671 | C# |
// WinterLeaf Entertainment
// Copyright (c) 2014, WinterLeaf Entertainment LLC
//
// All rights reserved.
//
// The use of the WinterLeaf Entertainment LLC OMNI "Community Edition" is governed by this license agreement ("Agreement").
//
// These license terms are an agreement between WinterLeaf Entertainment LLC and you. Please read them. They apply to the source code and any other assets or works that are included with the product named above, which includes the media on which you received it, if any. These terms also apply to any updates, supplements, internet-based services, and support services for this software and its associated assets, unless other terms accompany those items. If so, those terms apply. You must read and agree to this Agreement terms BEFORE installing OMNI "Community Edition" to your hard drive or using OMNI in any way. If you do not agree to the license terms, do not download, install or use OMNI. Please make copies of this Agreement for all those in your organization who need to be familiar with the license terms.
//
// This license allows companies of any size, government entities or individuals to create, sell, rent, lease, or otherwise profit commercially from, games using executables created from the source code that accompanies OMNI "Community Edition".
//
// BY CLICKING THE ACCEPTANCE BUTTON AND/OR INSTALLING OR USING OMNI "Community Edition", THE INDIVIDUAL ACCESSING OMNI ("LICENSEE") IS CONSENTING TO BE BOUND BY AND BECOME A PARTY TO THIS AGREEMENT. IF YOU DO NOT ACCEPT THESE TERMS, DO NOT INSTALL OR USE OMNI. IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW:
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the all copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// With respect to any Product that the Licensee develop using the Software:
// Licensee shall:
// display the OMNI Logo, in the start-up sequence of the Product (unless waived by WinterLeaf Entertainment);
// display in the "About" box or in the credits screen of the Product the text "OMNI by WinterLeaf Entertainment";
// display the OMNI Logo, on all external Product packaging materials and the back cover of any printed instruction manual or the end of any electronic instruction manual;
// notify WinterLeaf Entertainment in writing that You are publicly releasing a Product that was developed using the Software within the first 30 days following the release; and
// the Licensee hereby grant WinterLeaf Entertainment permission to refer to the Licensee or the name of any Product the Licensee develops using the Software for marketing purposes. All goodwill in each party's trademarks and logos will inure to the sole benefit of that party.
// Neither the name of WinterLeaf Entertainment LLC or OMNI nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// The following restrictions apply to the use of OMNI "Community Edition":
// Licensee may not:
// create any derivative works of OMNI Engine, including but not limited to translations, localizations, or game making software other than Games;
// redistribute, encumber, sell, rent, lease, sublicense, or otherwise transfer rights to OMNI "Community Edition"; or
// remove or alter any trademark, logo, copyright or other proprietary notices, legends, symbols or labels in OMNI Engine; or
// use the Software to develop or distribute any software that competes with the Software without WinterLeaf Entertainment’s prior written consent; or
// use the Software for any illegal purpose.
//
// THIS SOFTWARE IS PROVIDED BY WINTERLEAF ENTERTAINMENT LLC ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WINTERLEAF ENTERTAINMENT LLC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System.ComponentModel;
using WinterLeaf.Demo.Full.Models.User.Extendable;
using WinterLeaf.Engine;
using WinterLeaf.Engine.Classes.Decorations;
using WinterLeaf.Engine.Classes.Extensions;
using WinterLeaf.Engine.Classes.Helpers;
using WinterLeaf.Engine.Classes.View.Creators;
using WinterLeaf.Engine.Containers;
namespace WinterLeaf.Demo.Full.Models.User.GameCode.Tools.GuiEditor.gui.CodeBehind
{
[TypeConverter(typeof (TypeConverterGeneric<GuiEditorGroup>))]
public class GuiEditorGroup : ScriptObject
{
internal GuiControl groupObject
{
get { return this["groupObject"]; }
set { this["groupObject"] = value; }
}
internal GuiControl groupParent
{
get { return this["groupParent"]; }
set { this["groupParent"] = value; }
}
internal int count
{
get { return this["count"].AsInt(); }
set { this["count"] = value.AsString(); }
}
[ConsoleInteraction]
public string getGlobalBounds()
{
int minX = 2147483647;
int minY = 2147483647;
int maxX = -2147483647;
int maxY = -2147483647;
for (int i = 0; i < this.count; i ++)
{
GuiControl ctrl = this["ctrl[" + i + "]"];
string pos = ctrl.getGlobalPosition().AsString();
string extent = ctrl.getExtent().AsString();
// Min.
int posX = Util.getWord(pos, 0).AsInt();
int posY = Util.getWord(pos, 1).AsInt();
if (posX < minX)
minX = posX;
if (posY < minY)
minY = posY;
// Max.
posX += Util.getWord(extent, 0).AsInt();
posY += Util.getWord(extent, 1).AsInt();
if (posX > maxX)
maxX = posX;
if (posY > maxY)
maxY = posY;
}
return (minX + ' ' + minY + ' ' + (maxX - minX) + ' ' + (maxY - minY)).AsString();
}
[ConsoleInteraction]
/// Create a new GuiControl and move all the controls contained in the GuiEditorGroup into it.
public void group()
{
GuiControl parent = this.groupParent;
// Create group.
GuiControl group = new ObjectCreator("GuiControl").Create();
parent.addGuiControl(group);
this.groupObject = group;
// Make group fit around selection.
string bounds = this.getGlobalBounds();
string parentGlobalPos = parent.getGlobalPosition().AsString();
int x = Util.getWord(bounds, 0).AsInt() - Util.getWord(parentGlobalPos, 0).AsInt();
int y = Util.getWord(bounds, 1).AsInt() - Util.getWord(parentGlobalPos, 1).AsInt();
group.setPosition(x, y);
group.setExtent(new Point2F(Util.getWord(bounds, 2).AsFloat(), Util.getWord(bounds, 3).AsFloat()));
// Reparent all objects to group.
for (int i = 0; i < this.count; i ++)
{
GuiControl ctrl = this["ctrl[" + i + "]"];
// Save parent for undo.
this["ctrlParent[" + i + "]"] = ctrl.parentGroup;
// Reparent.
group.addGuiControl(ctrl);
// Move into place in new parent.
string pos = ctrl.getPosition().AsString();
ctrl.setPosition(Util.getWord(pos, 0).AsInt() - x, Util.getWord(pos, 1).AsInt() - y);
}
}
[ConsoleInteraction]
/// Move all controls out of group to either former parent or group parent.
public void ungroup()
{
GuiControl defaultParent = this.groupParent;
string groupPos = this.groupObject.getPosition().AsString();
int x = Util.getWord(groupPos, 0).AsInt();
int y = Util.getWord(groupPos, 1).AsInt();
// Move each control to its former parent (or default parent when
// there is no former parent).
for (int i = 0; i < this.count; i ++)
{
GuiControl ctrl = this["ctrl[" + i + "]"];
GuiControl parent = defaultParent;
if (this["ctrlParent[" + i + "]"].isObject())
parent = this["ctrlParent[" + i + "]"];
parent.addGuiControl(ctrl);
// Move into place in new parent.
string ctrlPos = ctrl.getPosition().AsString();
ctrl.setPosition(Util.getWord(ctrlPos, 0).AsInt() + x, Util.getWord(ctrlPos, 1).AsInt() + y);
}
// Delete old group object.
this.groupObject.delete();
}
#region ProxyObjects Operator Overrides
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator ==(GuiEditorGroup ts, string simobjectid)
{
return ReferenceEquals(ts, null) ? ReferenceEquals(simobjectid, null) : ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (this._ID == (string) myReflections.ChangeType(obj, typeof (string)));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static bool operator !=(GuiEditorGroup ts, string simobjectid)
{
if (ReferenceEquals(ts, null))
return !ReferenceEquals(simobjectid, null);
return !ts.Equals(simobjectid);
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator string(GuiEditorGroup ts)
{
return ReferenceEquals(ts, null) ? "0" : ts._ID;
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator GuiEditorGroup(string ts)
{
uint simobjectid = resolveobject(ts);
return (GuiEditorGroup) Omni.self.getSimObject(simobjectid, typeof (GuiEditorGroup));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator int(GuiEditorGroup ts)
{
return (int) ts._iID;
}
/// <summary>
///
/// </summary>
/// <param name="simobjectid"></param>
/// <returns></returns>
public static implicit operator GuiEditorGroup(int simobjectid)
{
return (GuiEditorGroup) Omni.self.getSimObject((uint) simobjectid, typeof (GuiEditorGroup));
}
/// <summary>
///
/// </summary>
/// <param name="ts"></param>
/// <returns></returns>
public static implicit operator uint(GuiEditorGroup ts)
{
return ts._iID;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static implicit operator GuiEditorGroup(uint simobjectid)
{
return (GuiEditorGroup) Omni.self.getSimObject(simobjectid, typeof (GuiEditorGroup));
}
#endregion
}
} | 44.832192 | 819 | 0.598656 | [
"MIT",
"Unlicense"
] | RichardRanft/OmniEngine.Net | Templates/C#-Empty/Winterleaf.Demo.Full/Models.User/GameCode/Tools/GuiEditor/gui/CodeBehind/GuiEditorGroup.ed.cs | 12,804 | C# |
#if UNITY_2020_1_OR_NEWER
using System.Collections.Generic;
using UnityEngine;
namespace Unity.MLAgents.Extensions.Sensors
{
/// <summary>
/// Utility class to track a hierarchy of ArticulationBodies.
/// </summary>
public class ArticulationBodyPoseExtractor : PoseExtractor
{
ArticulationBody[] m_Bodies;
public ArticulationBodyPoseExtractor(ArticulationBody rootBody)
{
if (rootBody == null)
{
return;
}
if (!rootBody.isRoot)
{
Debug.Log("Must pass ArticulationBody.isRoot");
return;
}
var bodies = rootBody.GetComponentsInChildren <ArticulationBody>();
if (bodies[0] != rootBody)
{
Debug.Log("Expected root body at index 0");
return;
}
var numBodies = bodies.Length;
m_Bodies = bodies;
int[] parentIndices = new int[numBodies];
parentIndices[0] = -1;
var bodyToIndex = new Dictionary<ArticulationBody, int>();
for (var i = 0; i < numBodies; i++)
{
bodyToIndex[m_Bodies[i]] = i;
}
for (var i = 1; i < numBodies; i++)
{
var currentArticBody = m_Bodies[i];
// Component.GetComponentInParent will consider the provided object as well.
// So start looking from the parent.
var currentGameObject = currentArticBody.gameObject;
var parentGameObject = currentGameObject.transform.parent;
var parentArticBody = parentGameObject.GetComponentInParent<ArticulationBody>();
parentIndices[i] = bodyToIndex[parentArticBody];
}
Setup(parentIndices);
}
/// <inheritdoc/>
protected internal override Vector3 GetLinearVelocityAt(int index)
{
return m_Bodies[index].velocity;
}
/// <inheritdoc/>
protected internal override Pose GetPoseAt(int index)
{
var body = m_Bodies[index];
var go = body.gameObject;
var t = go.transform;
return new Pose { rotation = t.rotation, position = t.position };
}
internal ArticulationBody[] Bodies => m_Bodies;
}
}
#endif // UNITY_2020_1_OR_NEWER | 31.205128 | 96 | 0.55341 | [
"Apache-2.0"
] | CYBER-CROP/ml-agents | com.unity.ml-agents.extensions/Runtime/Sensors/ArticulationBodyPoseExtractor.cs | 2,434 | C# |
using System;
using MachinaTrader.Globals.Structure.Enums;
namespace MachinaTrader.Globals.Structure.Models
{
public class ExchangeOptions
{
public Exchange Exchange { get; set; }
public string ApiKey { get; set; }
public string ApiSecret { get; set; }
public string PassPhrase { get; set; }
public DateTime SimulationCurrentDate { get; set; }
public DateTime SimulationEndDate { get; set; }
public bool IsSimulation { get; set; }
public string SimulationCandleSize { get; set; } = "15";
public decimal SimulationStartingWallet { get; set; } = 0.3m;
}
}
| 29.181818 | 69 | 0.652648 | [
"MIT"
] | Binkus/MachinaTrader | MachinaTrader.Globals.Structure/Models/ExchangeOptions.cs | 642 | C# |
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace Alipay.AopSdk.Core.Domain
{
/// <summary>
/// KbAdvertAdvChannelResponse Data Structure.
/// </summary>
[Serializable]
public class KbAdvertAdvChannelResponse : AopObject
{
/// <summary>
/// 广告内容模型
/// </summary>
[XmlArray("adv_content_list")]
[XmlArrayItem("kb_advert_adv_content_response")]
public List<KbAdvertAdvContentResponse> AdvContentList { get; set; }
/// <summary>
/// 广告id
/// </summary>
[XmlElement("adv_id")]
public string AdvId { get; set; }
/// <summary>
/// 渠道ID
/// </summary>
[XmlElement("channel_id")]
public string ChannelId { get; set; }
/// <summary>
/// 渠道名称
/// </summary>
[XmlElement("channel_name")]
public string ChannelName { get; set; }
/// <summary>
/// 渠道类型
/// </summary>
[XmlElement("channel_type")]
public string ChannelType { get; set; }
}
}
| 24.644444 | 76 | 0.550947 | [
"MIT"
] | leixf2005/Alipay.AopSdk.Core | Alipay.AopSdk.Core/Domain/KbAdvertAdvChannelResponse.cs | 1,145 | C# |
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.Logging;
using Nier.ACME.Core;
namespace Nier.ACME.AspNetCore.Kestrel
{
public class AutoRefreshServerCertificateSelector : IServerCertificateSelector, IDisposable
{
private readonly ICertReader _certReader;
private readonly ILogger<AutoRefreshServerCertificateSelector> _logger;
private X509Certificate2 _currentCert;
private readonly TimeSpan _refreshThreshold = TimeSpan.FromHours(1);
private readonly TimeSpan _errorBackoffTime = TimeSpan.FromMinutes(10);
private bool _stopped;
public AutoRefreshServerCertificateSelector(ICertReader certReader,
ILogger<AutoRefreshServerCertificateSelector> logger)
{
_certReader = certReader;
_logger = logger;
FirstRun();
}
public X509Certificate2 SelectServerCertificate(ConnectionContext connectionContext, string hostName)
{
return _currentCert;
}
private void FirstRun()
{
Task.Run(async () =>
{
while (!_stopped)
{
var hasError = false;
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
try
{
RefreshCert(now);
}
catch (Exception e)
{
hasError = true;
_logger.LogWarning($"Error when refresh cert {e}");
}
TimeSpan waitTime = _errorBackoffTime;
if (hasError || _currentCert == null)
{
waitTime = _errorBackoffTime;
}
else
{
long notAfter = new DateTimeOffset(_currentCert.NotAfter).ToUnixTimeMilliseconds();
if (notAfter > now)
{
long diff = notAfter - now;
if (diff > 4 * _refreshThreshold.TotalMilliseconds)
{
waitTime = TimeSpan.FromMilliseconds(diff - 4 * _refreshThreshold.TotalMilliseconds);
}
else
{
waitTime = _refreshThreshold / 2;
}
}
}
_logger.LogInformation($"Wait after {waitTime.TotalMilliseconds}ms to refresh cert");
await Task.Delay(waitTime);
}
});
}
private void RefreshCert(long now)
{
if (_currentCert == null || (now + _refreshThreshold.TotalMilliseconds >
new DateTimeOffset(_currentCert.NotAfter).ToUnixTimeMilliseconds()))
{
SetCert(now, now);
if (_currentCert == null)
{
// fallback to any cert
SetCert(0, now);
}
}
}
private void SetCert(long fromTs, long toTs)
{
X509Certificate2 cert = _certReader.GetActiveCertificateAsync(fromTs, toTs).Result;
if (cert != null)
{
_logger.LogInformation(
$"Set current cert active in ts {fromTs}->{toTs}, cert NotAfter {cert.NotAfter}");
_currentCert = cert;
}
}
public void Dispose()
{
_stopped = true;
}
}
} | 35.183486 | 117 | 0.491265 | [
"MIT"
] | bladepan/Nier.ACME | Nier.ACME.AspNetCore/Kestrel/AutoRefreshServerCertificateSelector.cs | 3,835 | C# |
using System;
using System.Collections.Generic;
using Simpler.Core.Tasks;
namespace Simpler.Core
{
public class InjectTasksAttribute : EventsAttribute
{
readonly List<string> _injectedSubTaskPropertyNames = new List<string>();
public override void BeforeExecute(Task task)
{
var inject = new InjectTasks { In = { TaskContainingSubTasks = task } };
inject.Execute();
_injectedSubTaskPropertyNames.AddRange(inject.Out.InjectedSubTaskPropertyNames);
}
public override void AfterExecute(Task task)
{
var dispose = new DisposeTasks { In = { Owner = task, InjectedTaskNames = _injectedSubTaskPropertyNames.ToArray() } };
dispose.Execute();
}
public override void OnError(Task task, Exception exception) {}
}
}
| 31.259259 | 130 | 0.658768 | [
"MIT"
] | gregoryjscott/Simpler | api/Simpler/Core/InjectTasksAttribute.cs | 844 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Dbg = System.Management.Automation;
using System.Management.Automation.Internal;
namespace System.Management.Automation
{
/// <summary>
/// Exposes the Cmdlet Family Providers to the Cmdlet base class. The methods of this class
/// use the providers to perform operations.
/// </summary>
public sealed class ProviderIntrinsics
{
#region Constructors
/// <summary>
/// Hide the default constructor since we always require an instance of SessionState
/// </summary>
private ProviderIntrinsics()
{
Dbg.Diagnostics.Assert(
false,
"This constructor should never be called. Only the constructor that takes an instance of SessionState should be called.");
} // ProviderIntrinsics private
/// <summary>
/// Constructs a facade over the "real" session state API
/// </summary>
///
/// <param name="cmdlet">
/// An instance of the cmdlet.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="cmdlet"/> is null.
/// </exception>
///
internal ProviderIntrinsics(Cmdlet cmdlet)
{
if (cmdlet == null)
{
throw PSTraceSource.NewArgumentNullException("cmdlet");
}
_cmdlet = cmdlet;
Item = new ItemCmdletProviderIntrinsics(cmdlet);
ChildItem = new ChildItemCmdletProviderIntrinsics(cmdlet);
Content = new ContentCmdletProviderIntrinsics(cmdlet);
Property = new PropertyCmdletProviderIntrinsics(cmdlet);
SecurityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(cmdlet);
} // ProviderIntrinsics internal
/// <summary>
/// Constructs a facade over the "real" session state API
/// </summary>
///
/// <param name="sessionState">
/// An instance of the cmdlet.
/// </param>
///
internal ProviderIntrinsics(SessionStateInternal sessionState)
{
if (sessionState == null)
{
throw PSTraceSource.NewArgumentNullException("sessionState");
}
Item = new ItemCmdletProviderIntrinsics(sessionState);
ChildItem = new ChildItemCmdletProviderIntrinsics(sessionState);
Content = new ContentCmdletProviderIntrinsics(sessionState);
Property = new PropertyCmdletProviderIntrinsics(sessionState);
SecurityDescriptor = new SecurityDescriptorCmdletProviderIntrinsics(sessionState);
} // ProviderIntrinsics internal
#endregion Constructors
#region Public members
/// <summary>
/// Gets the object that exposes the verbs for the item noun for Cmdlet Providers
/// </summary>
public ItemCmdletProviderIntrinsics Item { get; }
/// <summary>
/// Gets the object that exposes the verbs for the childItem noun for Cmdlet Providers
/// </summary>
public ChildItemCmdletProviderIntrinsics ChildItem { get; }
/// <summary>
/// Gets the object that exposes the verbs for the content noun for Cmdlet Providers
/// </summary>
public ContentCmdletProviderIntrinsics Content { get; }
/// <summary>
/// Gets the object that exposes the verbs for the property noun for Cmdlet Providers
/// </summary>
public PropertyCmdletProviderIntrinsics Property { get; }
/// <summary>
/// Gets the object that exposes the verbs for the SecurityDescriptor noun for Cmdlet Providers
/// </summary>
public SecurityDescriptorCmdletProviderIntrinsics SecurityDescriptor { get; }
#endregion Public members
#region private data
private InternalCommand _cmdlet;
#endregion private data
} // ProviderIntrinsics
}
| 35.443478 | 138 | 0.622669 | [
"Apache-2.0",
"MIT-0"
] | Lolle2000la/PowerShell | src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs | 4,076 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Notebooks.V1.Snippets
{
using Google.Api.Gax;
using Google.Cloud.Notebooks.V1;
using System;
using System.Linq;
using System.Threading.Tasks;
public sealed partial class GeneratedNotebookServiceClientStandaloneSnippets
{
/// <summary>Snippet for ListSchedulesAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task ListSchedulesResourceNamesAsync()
{
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
ScheduleName parent = ScheduleName.FromProjectLocationSchedule("[PROJECT]", "[LOCATION]", "[SCHEDULE]");
// Make the request
PagedAsyncEnumerable<ListSchedulesResponse, Schedule> response = notebookServiceClient.ListSchedulesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Schedule item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSchedulesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Schedule item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Schedule> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Schedule item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
}
| 41.92 | 126 | 0.631997 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/notebooks/v1/google-cloud-notebooks-v1-csharp/Google.Cloud.Notebooks.V1.StandaloneSnippets/NotebookServiceClient.ListSchedulesResourceNamesAsyncSnippet.g.cs | 3,144 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Network.Models;
namespace Azure.ResourceManager.Network
{
/// <summary> A class representing collection of VirtualNetworkPeering and their operations over its parent. </summary>
public partial class VirtualNetworkPeeringCollection : ArmCollection, IEnumerable<VirtualNetworkPeering>, IAsyncEnumerable<VirtualNetworkPeering>
{
private readonly ClientDiagnostics _virtualNetworkPeeringClientDiagnostics;
private readonly VirtualNetworkPeeringsRestOperations _virtualNetworkPeeringRestClient;
/// <summary> Initializes a new instance of the <see cref="VirtualNetworkPeeringCollection"/> class for mocking. </summary>
protected VirtualNetworkPeeringCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="VirtualNetworkPeeringCollection"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the parent resource that is the target of operations. </param>
internal VirtualNetworkPeeringCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_virtualNetworkPeeringClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Network", VirtualNetworkPeering.ResourceType.Namespace, DiagnosticOptions);
Client.TryGetApiVersion(VirtualNetworkPeering.ResourceType, out string virtualNetworkPeeringApiVersion);
_virtualNetworkPeeringRestClient = new VirtualNetworkPeeringsRestOperations(_virtualNetworkPeeringClientDiagnostics, Pipeline, DiagnosticOptions.ApplicationId, BaseUri, virtualNetworkPeeringApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != VirtualNetwork.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, VirtualNetwork.ResourceType), nameof(id));
}
/// <summary> Creates or updates a peering in the specified virtual network. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="virtualNetworkPeeringName"> The name of the peering. </param>
/// <param name="virtualNetworkPeeringParameters"> Parameters supplied to the create or update virtual network peering operation. </param>
/// <param name="syncRemoteAddressSpace"> Parameter indicates the intention to sync the peering with the current address space on the remote vNet after it's updated. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="virtualNetworkPeeringName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="virtualNetworkPeeringName"/> or <paramref name="virtualNetworkPeeringParameters"/> is null. </exception>
public async virtual Task<VirtualNetworkPeeringCreateOrUpdateOperation> CreateOrUpdateAsync(bool waitForCompletion, string virtualNetworkPeeringName, VirtualNetworkPeeringData virtualNetworkPeeringParameters, SyncRemoteAddressSpace? syncRemoteAddressSpace = null, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(virtualNetworkPeeringName, nameof(virtualNetworkPeeringName));
if (virtualNetworkPeeringParameters == null)
{
throw new ArgumentNullException(nameof(virtualNetworkPeeringParameters));
}
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _virtualNetworkPeeringRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, virtualNetworkPeeringName, virtualNetworkPeeringParameters, syncRemoteAddressSpace, cancellationToken).ConfigureAwait(false);
var operation = new VirtualNetworkPeeringCreateOrUpdateOperation(Client, _virtualNetworkPeeringClientDiagnostics, Pipeline, _virtualNetworkPeeringRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, virtualNetworkPeeringName, virtualNetworkPeeringParameters, syncRemoteAddressSpace).Request, response);
if (waitForCompletion)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Creates or updates a peering in the specified virtual network. </summary>
/// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param>
/// <param name="virtualNetworkPeeringName"> The name of the peering. </param>
/// <param name="virtualNetworkPeeringParameters"> Parameters supplied to the create or update virtual network peering operation. </param>
/// <param name="syncRemoteAddressSpace"> Parameter indicates the intention to sync the peering with the current address space on the remote vNet after it's updated. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="virtualNetworkPeeringName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="virtualNetworkPeeringName"/> or <paramref name="virtualNetworkPeeringParameters"/> is null. </exception>
public virtual VirtualNetworkPeeringCreateOrUpdateOperation CreateOrUpdate(bool waitForCompletion, string virtualNetworkPeeringName, VirtualNetworkPeeringData virtualNetworkPeeringParameters, SyncRemoteAddressSpace? syncRemoteAddressSpace = null, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(virtualNetworkPeeringName, nameof(virtualNetworkPeeringName));
if (virtualNetworkPeeringParameters == null)
{
throw new ArgumentNullException(nameof(virtualNetworkPeeringParameters));
}
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _virtualNetworkPeeringRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, virtualNetworkPeeringName, virtualNetworkPeeringParameters, syncRemoteAddressSpace, cancellationToken);
var operation = new VirtualNetworkPeeringCreateOrUpdateOperation(Client, _virtualNetworkPeeringClientDiagnostics, Pipeline, _virtualNetworkPeeringRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, virtualNetworkPeeringName, virtualNetworkPeeringParameters, syncRemoteAddressSpace).Request, response);
if (waitForCompletion)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the specified virtual network peering. </summary>
/// <param name="virtualNetworkPeeringName"> The name of the virtual network peering. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="virtualNetworkPeeringName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="virtualNetworkPeeringName"/> is null. </exception>
public async virtual Task<Response<VirtualNetworkPeering>> GetAsync(string virtualNetworkPeeringName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(virtualNetworkPeeringName, nameof(virtualNetworkPeeringName));
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.Get");
scope.Start();
try
{
var response = await _virtualNetworkPeeringRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, virtualNetworkPeeringName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw await _virtualNetworkPeeringClientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false);
return Response.FromValue(new VirtualNetworkPeering(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets the specified virtual network peering. </summary>
/// <param name="virtualNetworkPeeringName"> The name of the virtual network peering. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="virtualNetworkPeeringName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="virtualNetworkPeeringName"/> is null. </exception>
public virtual Response<VirtualNetworkPeering> Get(string virtualNetworkPeeringName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(virtualNetworkPeeringName, nameof(virtualNetworkPeeringName));
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.Get");
scope.Start();
try
{
var response = _virtualNetworkPeeringRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, virtualNetworkPeeringName, cancellationToken);
if (response.Value == null)
throw _virtualNetworkPeeringClientDiagnostics.CreateRequestFailedException(response.GetRawResponse());
return Response.FromValue(new VirtualNetworkPeering(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Gets all virtual network peerings in a virtual network. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="VirtualNetworkPeering" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<VirtualNetworkPeering> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<VirtualNetworkPeering>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.GetAll");
scope.Start();
try
{
var response = await _virtualNetworkPeeringRestClient.ListAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new VirtualNetworkPeering(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<VirtualNetworkPeering>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.GetAll");
scope.Start();
try
{
var response = await _virtualNetworkPeeringRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new VirtualNetworkPeering(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Gets all virtual network peerings in a virtual network. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="VirtualNetworkPeering" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<VirtualNetworkPeering> GetAll(CancellationToken cancellationToken = default)
{
Page<VirtualNetworkPeering> FirstPageFunc(int? pageSizeHint)
{
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.GetAll");
scope.Start();
try
{
var response = _virtualNetworkPeeringRestClient.List(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new VirtualNetworkPeering(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<VirtualNetworkPeering> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.GetAll");
scope.Start();
try
{
var response = _virtualNetworkPeeringRestClient.ListNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new VirtualNetworkPeering(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary> Checks to see if the resource exists in azure. </summary>
/// <param name="virtualNetworkPeeringName"> The name of the virtual network peering. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="virtualNetworkPeeringName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="virtualNetworkPeeringName"/> is null. </exception>
public async virtual Task<Response<bool>> ExistsAsync(string virtualNetworkPeeringName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(virtualNetworkPeeringName, nameof(virtualNetworkPeeringName));
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(virtualNetworkPeeringName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Checks to see if the resource exists in azure. </summary>
/// <param name="virtualNetworkPeeringName"> The name of the virtual network peering. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="virtualNetworkPeeringName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="virtualNetworkPeeringName"/> is null. </exception>
public virtual Response<bool> Exists(string virtualNetworkPeeringName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(virtualNetworkPeeringName, nameof(virtualNetworkPeeringName));
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(virtualNetworkPeeringName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="virtualNetworkPeeringName"> The name of the virtual network peering. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="virtualNetworkPeeringName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="virtualNetworkPeeringName"/> is null. </exception>
public async virtual Task<Response<VirtualNetworkPeering>> GetIfExistsAsync(string virtualNetworkPeeringName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(virtualNetworkPeeringName, nameof(virtualNetworkPeeringName));
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.GetIfExists");
scope.Start();
try
{
var response = await _virtualNetworkPeeringRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, virtualNetworkPeeringName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<VirtualNetworkPeering>(null, response.GetRawResponse());
return Response.FromValue(new VirtualNetworkPeering(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary> Tries to get details for this resource from the service. </summary>
/// <param name="virtualNetworkPeeringName"> The name of the virtual network peering. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="virtualNetworkPeeringName"/> is empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="virtualNetworkPeeringName"/> is null. </exception>
public virtual Response<VirtualNetworkPeering> GetIfExists(string virtualNetworkPeeringName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(virtualNetworkPeeringName, nameof(virtualNetworkPeeringName));
using var scope = _virtualNetworkPeeringClientDiagnostics.CreateScope("VirtualNetworkPeeringCollection.GetIfExists");
scope.Start();
try
{
var response = _virtualNetworkPeeringRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, virtualNetworkPeeringName, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<VirtualNetworkPeering>(null, response.GetRawResponse());
return Response.FromValue(new VirtualNetworkPeering(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<VirtualNetworkPeering> IEnumerable<VirtualNetworkPeering>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<VirtualNetworkPeering> IAsyncEnumerable<VirtualNetworkPeering>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 60.893855 | 354 | 0.679266 | [
"MIT"
] | danielortega-msft/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/VirtualNetworkPeeringCollection.cs | 21,800 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using DG.Tweening;
using UnityEngine;
namespace Gamespace.UI
{
public enum CompositeMode
{
Join = 0,
Sequence
};
[Serializable]
public class CompositeAnimation : UIAnimation
{
[SerializeField] private bool _reverseOut;
[SerializeField] private CompositeMode _mode;
public override float Duration {
get
{
var duration = 0f;
for (int i = 0; i < _behaviours.Count; i++)
{
if (_mode == 0)
{
if (_behaviours[i].Function.Duration > duration)
duration = _behaviours[i].Function.Duration;
}
else
{
duration += _behaviours[i].Function.Duration;
}
}
return duration + _duration;
}
}
[TypeConstraint(typeof(IUIAnimation))]
[SerializeField]
private List<UIAnimationFacade> _behaviours = new List<UIAnimationFacade>();
public override void In(Sequence sequence)
{
for (int i = 0; i < _behaviours.Count; i++)
{
if (_mode == 0)
{
var behaviour = _behaviours[i];
sequence.AppendCallback(() => behaviour.Behaviour?.On());
}
else
{
var behaviour = _behaviours[i];
sequence.AppendCallback(() => behaviour.Behaviour?.On());
sequence.AppendInterval(behaviour.Behaviour.Duration);
}
}
}
public override async void Out(Sequence sequence)
{
if (_reverseOut)
{
for (int i = _behaviours.Count - 1; i >= 0; i--)
{
if (_mode == 0)
{
var behaviour = _behaviours[i];
sequence.AppendCallback(() => behaviour.Behaviour?.Off());
}
else
{
var behaviour = _behaviours[i];
sequence.AppendCallback(() => behaviour.Behaviour?.Off());
sequence.AppendInterval(behaviour.Behaviour.Duration);
}
}
return;
}
for (int i = 0; i < _behaviours.Count; i++)
{
if (_mode == 0)
{
var behaviour = _behaviours[i];
sequence.AppendCallback(() => behaviour.Behaviour?.Off());
}
else
{
var behaviour = _behaviours[i];
sequence.AppendCallback(() => behaviour.Behaviour?.Off());
sequence.AppendInterval(behaviour.Behaviour.Duration);
}
}
}
public override void Reset()
{
for (int i = 0; i < _behaviours.Count; i++)
_behaviours[i]?.Behaviour?.Reset();
}
}
} | 30.642857 | 84 | 0.421911 | [
"MIT"
] | MagicalMontra/Narrative | Assets/DOTweenUIAnimation/Script/CompositeAnimation.cs | 3,434 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using RoseByte.AdoSession.Interfaces;
using RoseByte.AdoSession.Internals;
namespace RoseByte.AdoSession
{
public class Session : ISession
{
private readonly string _connectionString;
private readonly IConnectionFactory _factory;
private IConnection _connection;
private IConnection Connection
{
get
{
if (_connection == null)
{
_connection = _factory.Create(_connectionString);
_connection.MessageReceived += OnMessageReceived;
_delegates.Add(OnMessageReceived);
}
return _connection;
}
}
private string _database;
private string _server;
/// <summary>
/// Messages sent by SQL server.
/// </summary>
public event Action<string> MessageReceived;
/// <summary>
/// Errors sent by SQL server.
/// </summary>
public event Action<string> ErrorReceived;
/// <summary>
/// Toggles between message and error sending. Set to false by every Close().
/// </summary>
public bool FireInfoMessageEventOnUserErrors
{
get => Connection.FireInfoMessageEventOnUserErrors;
set => Connection.FireInfoMessageEventOnUserErrors = value;
}
private void OnMessageReceived(object sender, SqlInfoMessageEventArgs args)
{
foreach (SqlError error in args.Errors)
{
if (error.Class > 10)
{
ErrorReceived?.Invoke(error.Message);
}
else
{
MessageReceived?.Invoke(args.Message);
}
}
}
private readonly List<EventHandler<SqlInfoMessageEventArgs>> _delegates;
/// <summary>
/// Returns session database's name
/// </summary>
public virtual string Database {
get
{
if (_database == null)
{
(_database, _server) = ParseConnectionString();
}
return _database;
}
}
/// <summary>
/// Returns session servers's name
/// </summary>
public virtual string Server {
get
{
if (_server == null)
{
(_database, _server) = ParseConnectionString();
}
return _server;
}
}
/// <summary>
/// Returns ValueSet for each row fetched by given SQL script
/// </summary>
/// <param name="sql">sql command fetching rows</param>
/// <param name="parameters">parameters for command</param>
/// <returns>IEnumerable interface of IValueSet</returns>
public IEnumerable<IValueSet> Select(string sql, ParameterSet parameters = null)
{
return Connection.Select(sql, parameters).ToList();
}
/// <summary>
/// Executes given SQL script
/// </summary>
/// <param name="sql">SQL script</param>
/// <param name="parameters">parameters for script</param>
/// <param name="timeout">command timeout in seconds and zero for infinity</param>
public void Execute(string sql, ParameterSet parameters = null, int timeout = 0)
{
Connection.Execute(sql, parameters, CommandType.Text, timeout);
}
/// <summary>
/// Executes given SQL script with multiple parameter sets as a batch
/// </summary>
/// <param name="sql">SQL script</param>
/// <param name="parameterSets">parameters for script</param>
public void ExecuteBatch(string sql, IEnumerable<ParameterSet> parameterSets)
{
Connection.ExecuteBatch(sql, parameterSets);
}
/// <summary>
/// Executes given SQL script on transaction. Transaction is created by first call
/// and disposed by either Commit() or Rollback() command.
/// </summary>
/// <param name="sql">SQL script</param>
/// <param name="parameters">parameters for script</param>
public void ExecuteOnTransaction(string sql, ParameterSet parameters = null)
{
Connection.ExecuteOnTransaction(sql, parameters);
}
/// <summary>
/// Executes given SQL script on transaction with multiple parameter sets as a batch. Transaction is created by first call
/// and disposed by either Commit() or Rollback() command.
/// </summary>
/// <param name="sql">SQL script</param>
/// <param name="parameterSets">parameters for script</param>
public void ExecuteBatchOnTransaction(string sql, IEnumerable<ParameterSet> parameterSets)
{
Connection.ExecuteBatchOnTransaction(sql, parameterSets);
}
/// <summary>
/// Returns scalar value fetched by given SQL script
/// </summary>
/// <param name="sql">SQL script</param>
/// <param name="parameters">parameters for script</param>
/// <returns>object</returns>
public object GetScalar(string sql, ParameterSet parameters = null)
{
return Connection.GetScalar(sql, parameters);
}
/// <summary>
/// Returns scalar value fetched by given SQL script
/// </summary>
/// <param name="sql">SQL script</param>
/// <param name="parameters">parameters for script</param>
/// <returns>promitive type of generic type given to the method</returns>
public T GetScalar<T>(string sql, ParameterSet parameters = null)
{
return (T)Convert.ChangeType(Connection.GetScalar(sql, parameters), typeof(T));
}
/// <summary>
/// Commits current transaction if any.
/// </summary>
public void Commit()
{
_connection?.Commit();
}
/// <summary>
/// Cancels current transaction if any.
/// </summary>
public void RollBack()
{
_connection?.RollBack();
}
/// <summary>
/// Closes current connection. Connection instance will be disposed and renewed with
/// first next call to database.
/// </summary>
public void CloseConnection()
{
foreach (var deleg in _delegates)
{
_connection.MessageReceived -= deleg;
}
_connection?.Dispose();
_connection = null;
}
/// <summary>
/// Returns content of embedded resource as a string.
/// </summary>
/// <param name="path">namespace of embedded resource (remember add folders' names)</param>
/// <returns>string</returns>
public string ReadEmbedded(string path)
{
using (var stm = Assembly.GetCallingAssembly().GetManifestResourceStream(path))
{
if (stm == null)
{
throw new ArgumentException($"Resource script '{path}' couldn't be found.");
}
return new StreamReader(stm).ReadToEnd();
}
}
/// <summary>
/// Returns content of resource item as a string.
/// </summary>
/// <param name="path">namespace of resource (remember add folders' names)</param>
/// <param name="key">key in resource</param>
/// <returns>string</returns>
public string ReadResource(string path, string key)
{
try
{
var rm = new ResourceManager(path, Assembly.GetCallingAssembly());
var item = rm.GetString(key);
if (item == null)
{
throw new ArgumentException($"Resource '{path}' file doesn't contain item '{key}'.");
}
return item;
}
catch (MissingManifestResourceException)
{
throw new ArgumentException($"Resource file '{path}' couldn't be found.");
}
}
/// <summary>
/// Returns content of file as a string.
/// </summary>
/// <param name="path">path to file</param>
/// <returns>string</returns>
public string ReadFile(string path)
{
if (!File.Exists(path))
{
throw new ArgumentException($"File '{path}' couldn't be found.");
}
return File.ReadAllText(path);
}
/// <summary>
/// Connection string in format "Data Source=..."
/// </summary>
/// <param name="connectionString"></param>
public Session(string connectionString) : this(new ConnectionFactory(), connectionString)
{ }
internal Session(IConnectionFactory factory, string connectionString)
{
_factory = factory;
_connectionString = connectionString;
_delegates = new List<EventHandler<SqlInfoMessageEventArgs>>();
}
public void Dispose()
{
CloseConnection();
}
protected virtual (string, string) ParseConnectionString()
{
var csb = new DbConnectionStringBuilder { ConnectionString = _connectionString };
return (csb["Initial Catalog"].ToString(), csb["Data Source"].ToString());
}
}
} | 33.37037 | 131 | 0.54495 | [
"MIT"
] | mezitrny/DbSession | AdoSession/AdoSession/Session.cs | 9,913 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using BuildXL.Cache.ContentStore.FileSystem;
using BuildXL.Cache.ContentStore.Interfaces.FileSystem;
using BuildXL.Cache.ContentStore.InterfacesTest.Time;
using ContentStoreTest.Test;
using BuildXL.Cache.MemoizationStore.Interfaces.Stores;
using BuildXL.Cache.MemoizationStore.InterfacesTest.Sessions;
using System;
using ContentStoreTest.Distributed.Redis;
using BuildXL.Cache.ContentStore.Distributed.Redis;
using BuildXL.Cache.ContentStore.Interfaces.Tracing;
using BuildXL.Cache.ContentStore.Interfaces.Logging;
using BuildXL.Cache.MemoizationStore.Distributed.Stores;
using Xunit;
using System.Threading.Tasks;
using System.Collections.Generic;
using Xunit.Abstractions;
namespace BuildXL.Cache.MemoizationStore.Test.Sessions
{
[Trait("Category", "LongRunningTest")]
[Collection("Redis-based tests")]
[Trait("Category", "WindowsOSOnly")] // 'redis-server' executable no longer exists
public class RedisMemoizationSessionTests : MemoizationSessionTests
{
private readonly MemoryClock _clock = new MemoryClock();
private readonly LocalRedisFixture _redis;
private readonly ILogger _logger;
private readonly TimeSpan _memoizationExpiryTime = TimeSpan.FromDays(1);
private readonly List<LocalRedisProcessDatabase> _databasesToDispose = new List<LocalRedisProcessDatabase>();
public RedisMemoizationSessionTests(LocalRedisFixture redis, ITestOutputHelper helper)
: base(() => new PassThroughFileSystem(TestGlobal.Logger), TestGlobal.Logger, helper)
{
_redis = redis;
_logger = TestGlobal.Logger;
}
protected override IMemoizationStore CreateStore(DisposableDirectory testDirectory)
{
var context = new Context(_logger);
var keySpace = Guid.NewGuid().ToString();
var primaryRedisInstance = LocalRedisProcessDatabase.CreateAndStartEmpty(_redis, _logger, _clock);
_databasesToDispose.Add(primaryRedisInstance);
var primaryFactory = RedisDatabaseFactory.CreateAsync(
context,
provider: new LiteralConnectionStringProvider(primaryRedisInstance.ConnectionString),
logSeverity: Severity.Info,
usePreventThreadTheft: false).GetAwaiter().GetResult();
var primaryRedisAdapter = new RedisDatabaseAdapter(primaryFactory, keySpace: keySpace);
var secondaryRedisInstance = LocalRedisProcessDatabase.CreateAndStartEmpty(_redis, _logger, _clock);
_databasesToDispose.Add(secondaryRedisInstance);
var secondaryFactory = RedisDatabaseFactory.CreateAsync(
context,
provider: new LiteralConnectionStringProvider(secondaryRedisInstance.ConnectionString),
logSeverity: Severity.Info,
usePreventThreadTheft: false).GetAwaiter().GetResult();
var secondaryRedisAdapter = new RedisDatabaseAdapter(secondaryFactory, keySpace: keySpace);
var memoizationDb = new RedisMemoizationDatabase(primaryRedisAdapter, secondaryRedisAdapter, new RedisMemoizationConfiguration()
{
ExpiryTime = _memoizationExpiryTime,
SlowOperationCancellationTimeout = null
});
return new RedisMemoizationStore(memoizationDb);
}
public override Task EnumerateStrongFingerprints(int strongFingerprintCount)
{
// Do nothing, since operation isn't supported in Redis.
return Task.FromResult(0);
}
public override Task EnumerateStrongFingerprintsEmpty()
{
// Do nothing, since operation isn't supported in Redis.
return Task.FromResult(0);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
foreach (var database in _databasesToDispose)
{
database.Dispose();
}
}
}
}
/// <summary>
/// Custom collection that uses <see cref="LocalRedisFixture"/>.
/// </summary>
[CollectionDefinition("Redis-based tests")]
public class LocalRedisCollection : ICollectionFixture<LocalRedisFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
}
| 42 | 141 | 0.671981 | [
"MIT"
] | Microsoft/BuildXL | Public/Src/Cache/MemoizationStore/DistributedTest/RedisMemoizationSessionTests.cs | 4,706 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SilupostWeb.Domain.ViewModel
{
public class SystemWebAdminModuleViewModel
{
public long? SystemWebAdminModuleId { get; set; }
public string SystemWebAdminModuleName { get; set; }
}
}
| 22.6 | 60 | 0.737463 | [
"Apache-2.0"
] | erwin-io/Silupost | SilupostWebApp/SilupostWeb.Domain/ViewModel/SystemWebAdminModuleViewModel.cs | 341 | C# |
#region License
// Copyright (c) 2009, ClearCanvas Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of ClearCanvas Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
#endregion
using System;
using ClearCanvas.Common;
using ClearCanvas.Common.Scripting;
using ClearCanvas.Common.Specifications;
using ClearCanvas.Dicom;
namespace ClearCanvas.ImageServer.Rules.Specifications
{
public class NoSuchDicomTagException : Exception
{
private readonly string _tagName;
public NoSuchDicomTagException(string tagName)
{
_tagName = tagName;
}
public string TagName
{
get { return _tagName; }
}
}
/// <summary>
/// Expression factory for evaluating expressions that reference attributes within a <see cref="DicomMessageBase"/>.
/// </summary>
[ExtensionOf(typeof (ExpressionFactoryExtensionPoint))]
[LanguageSupport("dicom")]
public class DicomExpressionFactory : IExpressionFactory
{
#region IExpressionFactory Members
public Expression CreateExpression(string text)
{
if (text.StartsWith("$"))
{
DicomTag tag = DicomTagDictionary.GetDicomTag(text.Substring(1));
if (tag == null)
throw new XmlSpecificationCompilerException("Invalid DICOM tag: " + text);
}
return new DicomExpression(text);
}
#endregion
}
/// <summary>
/// An expression handler for <see cref="DicomAttributeCollection"/> or
/// <see cref="DicomMessageBase"/> classes.
/// </summary>
/// <remarks>
/// <para>
/// This expression filter will evaluate input text with a leading $ as the name of a DICOM Tag.
/// It will lookup the name of the tag, and retrieve the value of the tag and return it. if there is no
/// leading $, the value will be passed through.
/// </para>
/// </remarks>
public class DicomExpression : Expression
{
public DicomExpression(string text)
: base(text)
{
}
/// <summary>
/// Evaluate
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public override object Evaluate(object arg)
{
if (string.IsNullOrEmpty(Text))
return null;
if (Text.StartsWith("$"))
{
DicomMessageBase msg = arg as DicomMessageBase;
DicomAttributeCollection collection = arg as DicomAttributeCollection;
if (collection == null && msg == null)
return null;
DicomTag tag = DicomTagDictionary.GetDicomTag(Text.Substring(1));
if (tag == null)
{
throw new NoSuchDicomTagException(Text.Substring(1));
}
if (msg != null)
{
if (msg.DataSet.Contains(tag))
collection = msg.DataSet;
else if (msg.MetaInfo.Contains(tag))
collection = msg.MetaInfo;
}
if (collection == null)
return null;
DicomAttribute attrib;
if (collection.TryGetAttribute(tag,out attrib))
{
if (attrib.IsEmpty || attrib.IsNull)
return null;
if (attrib.Tag.VR.Equals(DicomVr.SLvr))
return attrib.GetInt32(0, 0);
else if (attrib.Tag.VR.Equals(DicomVr.SSvr))
return attrib.GetInt16(0, 0);
else if (attrib.Tag.VR.Equals(DicomVr.ATvr) || attrib.Tag.VR.Equals(DicomVr.ULvr))
return attrib.GetUInt32(0, 0);
else if (attrib.Tag.VR.Equals(DicomVr.DSvr) || attrib.Tag.VR.Equals(DicomVr.FDvr))
return attrib.GetFloat64(0, 0f);
else if (attrib.Tag.VR.Equals(DicomVr.FLvr))
return attrib.GetFloat32(0, 0f);
else if (attrib.Tag.VR.Equals(DicomVr.ISvr))
return attrib.GetInt64(0, 0);
else if (attrib.Tag.VR.Equals(DicomVr.USvr))
return attrib.GetUInt16(0, 0);
else if (attrib.Tag.VR.Equals(DicomVr.SLvr))
return attrib.GetInt32(0, 0);
else if (attrib.Tag.VR.Equals(DicomVr.OBvr)
|| attrib.Tag.VR.Equals(DicomVr.OWvr)
|| attrib.Tag.VR.Equals(DicomVr.OFvr))
return attrib.StreamLength.ToString();
else
return attrib.ToString().Trim();
}
return null;
}
return Text;
}
}
} | 37 | 121 | 0.607043 | [
"Apache-2.0"
] | econmed/ImageServer20 | ImageServer/Rules/Specifications/DicomExpression.cs | 6,107 | C# |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace L2PNewsTicker.Droid
{
[Activity (Label = "L²P NewsTicker", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new L2PNewsTicker.App ());
}
}
}
| 26.08 | 162 | 0.731595 | [
"BSD-2-Clause"
] | auxua/L2PNewsTicker | L2PNewsTicker/L2PNewsTicker.Droid/MainActivity.cs | 655 | C# |
using DCL.Controllers;
using System.Collections;
using System.Collections.Generic;
using DCL;
using DCL.Builder;
using UnityEngine;
public class BuilderInWorldAudioHandler : MonoBehaviour
{
const float MUSIC_DELAY_TIME_ON_START = 4f;
const float MUSIC_FADE_OUT_TIME_ON_EXIT = 5f;
const float MUSIC_FADE_OUT_TIME_ON_TUTORIAL = 3f;
private IBIWCreatorController creatorController;
private IBIWEntityHandler entityHandler;
private IBIWModeController modeController;
[Header("Audio Events")]
[SerializeField]
AudioEvent eventAssetSpawn;
[SerializeField]
AudioEvent eventAssetPlace;
[SerializeField]
AudioEvent eventAssetSelect;
[SerializeField]
AudioEvent eventAssetDeselect;
[SerializeField]
AudioEvent eventBuilderOutOfBounds;
[SerializeField]
AudioEvent eventBuilderOutOfBoundsPlaced;
[SerializeField]
AudioEvent eventAssetDelete;
[SerializeField]
AudioEvent eventBuilderExit;
[SerializeField]
AudioEvent eventBuilderMusic;
private List<string> entitiesOutOfBounds = new List<string>();
private int entityCount;
bool playPlacementSoundOnDeselect;
private IBIWModeController.EditModeState state = IBIWModeController.EditModeState.Inactive;
private Coroutine fadeOutCoroutine;
private Coroutine startBuilderMusicCoroutine;
private IContext context;
private void Start() { playPlacementSoundOnDeselect = false; }
public void Initialize(IContext context)
{
this.context = context;
creatorController = context.editorContext.creatorController;
entityHandler = context.editorContext.entityHandler;
modeController = context.editorContext.modeController;
AddListeners();
}
private void AddListeners()
{
creatorController.OnCatalogItemPlaced += OnAssetSpawn;
entityHandler.OnDeleteSelectedEntities += OnAssetDelete;
modeController.OnChangedEditModeState += OnChangedEditModeState;
DCL.Environment.i.world.sceneBoundsChecker.OnEntityBoundsCheckerStatusChanged += OnEntityBoundsCheckerStatusChanged;
if (DCL.Tutorial.TutorialController.i != null)
{
DCL.Tutorial.TutorialController.i.OnTutorialEnabled += OnTutorialEnabled;
DCL.Tutorial.TutorialController.i.OnTutorialDisabled += OnTutorialDisabled;
}
entityHandler.OnEntityDeselected += OnAssetDeselect;
entityHandler.OnEntitySelected += OnAssetSelect;
}
public void EnterEditMode(IParcelScene scene)
{
UpdateEntityCount();
if (eventBuilderMusic.source.gameObject.activeSelf)
{
if (startBuilderMusicCoroutine != null)
CoroutineStarter.Stop(startBuilderMusicCoroutine);
startBuilderMusicCoroutine = CoroutineStarter.Start(StartBuilderMusic());
}
if ( context.editorContext.editorHUD != null)
context.editorContext.editorHUD.OnCatalogItemSelected += OnCatalogItemSelected;
gameObject.SetActive(true);
}
public void ExitEditMode()
{
eventBuilderExit.Play();
if (eventBuilderMusic.source.gameObject.activeSelf)
{
if (fadeOutCoroutine != null)
CoroutineStarter.Stop(fadeOutCoroutine);
fadeOutCoroutine = CoroutineStarter.Start(eventBuilderMusic.FadeOut(MUSIC_FADE_OUT_TIME_ON_EXIT));
}
if ( context.editorContext.editorHUD != null)
context.editorContext.editorHUD.OnCatalogItemSelected -= OnCatalogItemSelected;
gameObject.SetActive(false);
}
private void OnAssetSpawn() { eventAssetSpawn.Play(); }
private void OnAssetDelete(List<BIWEntity> entities)
{
foreach (BIWEntity deletedEntity in entities)
{
if (entitiesOutOfBounds.Contains(deletedEntity.rootEntity.entityId))
{
entitiesOutOfBounds.Remove(deletedEntity.rootEntity.entityId);
}
}
eventAssetDelete.Play();
}
private void OnAssetSelect() { eventAssetSelect.Play(); }
private void OnAssetDeselect(BIWEntity entity)
{
if (playPlacementSoundOnDeselect)
{
eventAssetPlace.Play();
playPlacementSoundOnDeselect = false;
}
else
eventAssetDeselect.Play();
UpdateEntityCount();
if (entitiesOutOfBounds.Contains(entity.rootEntity.entityId))
{
eventBuilderOutOfBoundsPlaced.Play();
}
}
private void OnCatalogItemSelected(CatalogItem catalogItem) { playPlacementSoundOnDeselect = true; }
private void OnTutorialEnabled()
{
if (gameObject.activeInHierarchy)
{
if (fadeOutCoroutine != null)
CoroutineStarter.Stop(fadeOutCoroutine);
fadeOutCoroutine = CoroutineStarter.Start(eventBuilderMusic.FadeOut(MUSIC_FADE_OUT_TIME_ON_TUTORIAL));
}
}
private void OnTutorialDisabled()
{
if (gameObject.activeInHierarchy)
{
if (startBuilderMusicCoroutine != null)
CoroutineStarter.Stop(startBuilderMusicCoroutine);
startBuilderMusicCoroutine = CoroutineStarter.Start(StartBuilderMusic());
}
}
private IEnumerator StartBuilderMusic()
{
yield return new WaitForSeconds(MUSIC_DELAY_TIME_ON_START);
if (gameObject != null && gameObject.activeInHierarchy)
eventBuilderMusic.Play();
}
private void OnChangedEditModeState(IBIWModeController.EditModeState previous, IBIWModeController.EditModeState current)
{
state = current;
if (previous != IBIWModeController.EditModeState.Inactive)
{
switch (current)
{
case IBIWModeController.EditModeState.FirstPerson:
AudioScriptableObjects.cameraFadeIn.Play();
break;
case IBIWModeController.EditModeState.GodMode:
AudioScriptableObjects.cameraFadeOut.Play();
break;
default:
break;
}
}
}
private void OnEntityBoundsCheckerStatusChanged(DCL.Models.IDCLEntity entity, bool isInsideBoundaries)
{
if (state == IBIWModeController.EditModeState.Inactive)
return;
if (!isInsideBoundaries)
{
if (!entitiesOutOfBounds.Contains(entity.entityId))
{
entitiesOutOfBounds.Add(entity.entityId);
eventBuilderOutOfBounds.Play();
}
}
else
{
if (entitiesOutOfBounds.Contains(entity.entityId))
{
entitiesOutOfBounds.Remove(entity.entityId);
}
}
}
private void UpdateEntityCount() { entityCount = entityHandler.GetCurrentSceneEntityCount(); }
private bool EntityHasBeenAddedSinceLastUpdate() { return (entityHandler.GetCurrentSceneEntityCount() > entityCount); }
private void OnDestroy() { Dispose(); }
public void Dispose()
{
if (startBuilderMusicCoroutine != null)
CoroutineStarter.Stop(startBuilderMusicCoroutine);
if (fadeOutCoroutine != null)
CoroutineStarter.Stop(fadeOutCoroutine);
startBuilderMusicCoroutine = null;
fadeOutCoroutine = null;
RemoveListeners();
}
private void RemoveListeners()
{
creatorController.OnCatalogItemPlaced -= OnAssetSpawn;
entityHandler.OnDeleteSelectedEntities -= OnAssetDelete;
modeController.OnChangedEditModeState -= OnChangedEditModeState;
DCL.Environment.i.world.sceneBoundsChecker.OnEntityBoundsCheckerStatusChanged -= OnEntityBoundsCheckerStatusChanged;
if (DCL.Tutorial.TutorialController.i != null)
{
DCL.Tutorial.TutorialController.i.OnTutorialEnabled -= OnTutorialEnabled;
DCL.Tutorial.TutorialController.i.OnTutorialDisabled -= OnTutorialDisabled;
}
entityHandler.OnEntityDeselected -= OnAssetDeselect;
entityHandler.OnEntitySelected -= OnAssetSelect;
}
} | 31.174905 | 124 | 0.671911 | [
"Apache-2.0"
] | JuanMartinSalice/unity-renderer | unity-renderer/Assets/DCLPlugins/BuilderInWorld/Scripts/BuilderInWorldAudioHandler.cs | 8,199 | C# |
using AmazonSpApiSDK.Api.Orders;
using AmazonSpApiSDK.Clients;
using AmazonSpApiSDK.Models;
using AmazonSpApiSDK.Models.Orders;
using FikaAmazonAPI.Parameter.Order;
using FikaAmazonAPI.Utils;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Text;
namespace FikaAmazonAPI.Services
{
public class OrderService : RequestService
{
public OrderService(AmazonCredential amazonCredential) : base(amazonCredential)
{
}
#region GetOrders
public List<CreateReportResult> GetOrders(ParameterOrderList serachOrderList)
{
var parameters = serachOrderList.getParameters();
return GetOrders(parameters);
}
public List<CreateReportResult> GetOrders(List<KeyValuePair<string, string>> queryParameters = null)
{
var orderList = new List<CreateReportResult>();
CreateAuthorizedRequest(OrdersApiUrls.Orders, RestSharp.Method.GET, queryParameters);
var response = ExecuteRequest<GetOrdersResponse>();
var nextToken = response.Payload.NextToken;
orderList = response.Payload.Orders;
while (!string.IsNullOrEmpty(nextToken))
{
var orderPayload = GetByNextToken(nextToken);
orderList.AddRange(orderPayload.Orders);
nextToken = orderPayload.NextToken;
}
return orderList;
}
private OrdersList GetByNextToken(string nextToken)
{
List<KeyValuePair<string, string>> queryParameters = new List<KeyValuePair<string, string>>();
queryParameters.Add(new KeyValuePair<string, string>("NextToken", nextToken));
CreateAuthorizedRequest(OrdersApiUrls.Orders, RestSharp.Method.GET, queryParameters);
var response = ExecuteRequest<GetOrdersResponse>();
return response.Payload;
}
#endregion
public CreateReportResult GetOrder(string orderId, List<KeyValuePair<string, string>> queryParameters = null)
{
CreateAuthorizedRequest(OrdersApiUrls.Order(orderId), RestSharp.Method.GET);
var response = ExecuteRequest<GetOrderResponse>();
return response.Payload;
}
public OrderItemList GetOrderItems(string orderId)
{
var orderItemList = new OrderItemList();
CreateAuthorizedRequest(OrdersApiUrls.OrderItems(orderId), RestSharp.Method.GET);
var response = ExecuteRequest<GetOrderItemsResponse>();
var nextToken = response.Payload.NextToken;
orderItemList.AddRange(response.Payload.OrderItems);
while (!string.IsNullOrEmpty(nextToken))
{
var orderItemPayload = GetOrderItemsNextToken(orderId,nextToken);
orderItemList.AddRange(orderItemPayload.OrderItems);
nextToken = orderItemPayload.NextToken;
}
return orderItemList;
}
public OrderItemsList GetOrderItemsNextToken(string orderId,string nextToken)
{
List<KeyValuePair<string, string>> queryParameters = new List<KeyValuePair<string, string>>();
queryParameters.Add(new KeyValuePair<string, string>("NextToken", nextToken));
CreateAuthorizedRequest(OrdersApiUrls.OrderItems(orderId), RestSharp.Method.GET, queryParameters);
var response = ExecuteRequest<GetOrderItemsResponse>();
return response.Payload;
}
public OrderBuyerInfo GetOrderBuyerInfo(string orderId, List<KeyValuePair<string, string>> queryParameters = null)
{
CreateAuthorizedRequest(OrdersApiUrls.OrderBuyerInfo(orderId), RestSharp.Method.GET, queryParameters);
var response = ExecuteRequest<GetOrderBuyerInfoResponse>();
return response.Payload;
}
public OrderItemsBuyerInfoList GetOrderItemsBuyerInfo(string orderId)
{
CreateAuthorizedRequest(OrdersApiUrls.OrderItemsBuyerInfo(orderId), RestSharp.Method.GET);
var response = ExecuteRequest<GetOrderItemsBuyerInfoResponse>();
return response.Payload;
}
public Address GetOrderAddress(string orderId)
{
CreateAuthorizedRequest(OrdersApiUrls.OrderShipmentInfo(orderId), RestSharp.Method.GET);
var response = ExecuteRequest<GetOrderAddressResponse>();
return response.Payload.ShippingAddress;
}
}
}
| 39.929825 | 122 | 0.66652 | [
"MIT"
] | KristopherMackowiak/Amazon-SP-API-CSharp | Source/FikaAmazonAPI/Services/OrderService.cs | 4,554 | C# |
namespace SharpVk.Glfw
{
/// <summary>
/// Events that may be raised from a monitor callback.
/// </summary>
public enum MonitorEvent
{
/// <summary>
/// The monitor was connected.
/// </summary>
Connected = 0x00040001,
/// <summary>
/// The monitor was disconnected.
/// </summary>
Disconnected = 0x00040002
}
}
| 22.388889 | 58 | 0.528536 | [
"MIT"
] | FacticiusVir/SharpVk | src/SharpVk.Glfw/MonitorEvent.cs | 405 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.MoveDeclarationNearReference;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.ReplaceDiscardDeclarationsWithAssignments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues
{
/// <summary>
/// Code fixer for unused expression value diagnostics reported by <see cref="AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer"/>.
/// We provide following code fixes:
/// 1. If the unused value assigned to a local/parameter has no side-effects,
/// we recommend removing the assignment. We consider an expression value to have no side effects
/// if one of the following is true:
/// 1. Value is a compile time constant.
/// 2. Value is a local or parameter reference.
/// 3. Value is a field reference with no or implicit this instance.
/// 2. Otherwise, if user preference is set to DiscardVariable, and project's
/// language version supports discard variable, we recommend assigning the value to discard.
/// 3. Otherwise, we recommend assigning the value to a new unused local variable which has no reads.
/// </summary>
internal abstract class AbstractRemoveUnusedValuesCodeFixProvider<TExpressionSyntax, TStatementSyntax, TBlockSyntax,
TExpressionStatementSyntax, TLocalDeclarationStatementSyntax, TVariableDeclaratorSyntax, TForEachStatementSyntax,
TSwitchCaseBlockSyntax, TSwitchCaseLabelOrClauseSyntax, TCatchStatementSyntax, TCatchBlockSyntax>
: SyntaxEditorBasedCodeFixProvider
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TBlockSyntax : TStatementSyntax
where TExpressionStatementSyntax : TStatementSyntax
where TLocalDeclarationStatementSyntax : TStatementSyntax
where TForEachStatementSyntax : TStatementSyntax
where TVariableDeclaratorSyntax : SyntaxNode
where TSwitchCaseBlockSyntax : SyntaxNode
where TSwitchCaseLabelOrClauseSyntax : SyntaxNode
{
private static readonly SyntaxAnnotation s_memberAnnotation = new();
private static readonly SyntaxAnnotation s_newLocalDeclarationStatementAnnotation = new();
private static readonly SyntaxAnnotation s_unusedLocalDeclarationAnnotation = new();
private static readonly SyntaxAnnotation s_existingLocalDeclarationWithoutInitializerAnnotation = new();
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.ExpressionValueIsUnusedDiagnosticId,
IDEDiagnosticIds.ValueAssignedIsUnusedDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality;
/// <summary>
/// Method to update the identifier token for the local/parameter declaration or reference
/// that was flagged as an unused value write by the analyzer.
/// Returns null if the provided node is not one of the handled node kinds.
/// Otherwise, returns the new node with updated identifier.
/// </summary>
/// <param name="node">Flaggged node containing the identifier token to be replaced.</param>
/// <param name="newName">New identifier token</param>
protected abstract SyntaxNode TryUpdateNameForFlaggedNode(SyntaxNode node, SyntaxToken newName);
/// <summary>
/// Gets the identifier token for the iteration variable of the given foreach statement node.
/// </summary>
protected abstract SyntaxToken GetForEachStatementIdentifier(TForEachStatementSyntax node);
/// <summary>
/// Wraps the given statements within a block statement.
/// Note this method is invoked when replacing a statement that is parented by a non-block statement syntax.
/// </summary>
protected abstract TBlockSyntax WrapWithBlockIfNecessary(IEnumerable<TStatementSyntax> statements);
/// <summary>
/// Inserts the given declaration statement at the start of the given switch case block.
/// </summary>
protected abstract void InsertAtStartOfSwitchCaseBlockForDeclarationInCaseLabelOrClause(TSwitchCaseBlockSyntax switchCaseBlock, SyntaxEditor editor, TLocalDeclarationStatementSyntax declarationStatement);
/// <summary>
/// Gets the replacement node for a compound assignment expression whose
/// assigned value is redundant.
/// For example, "x += MethodCall()", where assignment to 'x' is redundant
/// is replaced with "_ = MethodCall()" or "var unused = MethodCall()"
/// </summary>
protected abstract SyntaxNode GetReplacementNodeForCompoundAssignment(
SyntaxNode originalCompoundAssignment,
SyntaxNode newAssignmentTarget,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts);
/// <summary>
/// Rewrite the parent of a node which was rewritted by <see cref="TryUpdateNameForFlaggedNode"/>.
/// </summary>
/// <param name="parent">The original parent of the node rewritten by <see cref="TryUpdateNameForFlaggedNode"/>.</param>
/// <param name="newNameNode">The rewritten node produced by <see cref="TryUpdateNameForFlaggedNode"/>.</param>
/// <param name="editor">The syntax editor for the code fix.</param>
/// <param name="syntaxFacts">The syntax facts for the current language.</param>
/// <returns>The replacement node to use in the rewritten syntax tree; otherwise, <see langword="null"/> to only
/// rewrite the node originally rewritten by <see cref="TryUpdateNameForFlaggedNode"/>.</returns>
protected virtual SyntaxNode TryUpdateParentOfUpdatedNode(SyntaxNode parent, SyntaxNode newNameNode, SyntaxEditor editor, ISyntaxFacts syntaxFacts)
{
return null;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics[0];
if (!AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostic, out var preference))
{
return;
}
var isRemovableAssignment = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostic);
string title;
if (isRemovableAssignment)
{
// Recommend removing the redundant constant value assignment.
title = CodeFixesResources.Remove_redundant_assignment;
}
else
{
// Recommend using discard/unused local for redundant non-constant assignment.
switch (preference)
{
case UnusedValuePreference.DiscardVariable:
if (IsForEachIterationVariableDiagnostic(diagnostic, context.Document, context.CancellationToken))
{
// Do not offer a fix to replace unused foreach iteration variable with discard.
// User should probably replace it with a for loop based on the collection length.
return;
}
title = CodeFixesResources.Use_discard_underscore;
// Check if this is compound assignment which is not parented by an expression statement,
// for example "return x += M();" OR "=> x ??= new C();"
// If so, we will be replacing this compound assignment with the underlying binary operation.
// For the above examples, it will be "return x + M();" AND "=> x ?? new C();" respectively.
// For these cases, we want to show the title as "Remove redundant assignment" instead of "Use discard _".
var syntaxFacts = context.Document.GetLanguageService<ISyntaxFactsService>();
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span, getInnermostNodeForTie: true);
if (syntaxFacts.IsLeftSideOfCompoundAssignment(node) &&
!syntaxFacts.IsExpressionStatement(node.Parent))
{
title = CodeFixesResources.Remove_redundant_assignment;
}
break;
case UnusedValuePreference.UnusedLocalVariable:
title = CodeFixesResources.Use_discarded_local;
break;
default:
return;
}
}
context.RegisterCodeFix(
new MyCodeAction(
title,
c => FixAsync(context.Document, diagnostic, c),
equivalenceKey: GetEquivalenceKey(preference, isRemovableAssignment)),
diagnostic);
return;
}
private static bool IsForEachIterationVariableDiagnostic(Diagnostic diagnostic, Document document, CancellationToken cancellationToken)
{
// Do not offer a fix to replace unused foreach iteration variable with discard.
// User should probably replace it with a for loop based on the collection length.
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
return syntaxFacts.IsForEachStatement(diagnostic.Location.FindNode(cancellationToken));
}
private static string GetEquivalenceKey(UnusedValuePreference preference, bool isRemovableAssignment)
=> preference.ToString() + isRemovableAssignment;
private static string GetEquivalenceKey(Diagnostic diagnostic)
{
if (!AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostic, out var preference))
{
return string.Empty;
}
var isRemovableAssignment = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostic);
return GetEquivalenceKey(preference, isRemovableAssignment);
}
/// <summary>
/// Flag to indicate if the code fix can introduce local declaration statements
/// that need to be moved closer to the first reference of the declared variable.
/// This is currently only possible for the unused value assignment fix.
/// </summary>
private static bool NeedsToMoveNewLocalDeclarationsNearReference(string diagnosticId)
=> diagnosticId == IDEDiagnosticIds.ValueAssignedIsUnusedDiagnosticId;
protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic, Document document, string equivalenceKey, CancellationToken cancellationToken)
{
return equivalenceKey == GetEquivalenceKey(diagnostic) &&
!IsForEachIterationVariableDiagnostic(diagnostic, document, cancellationToken);
}
private static IEnumerable<IGrouping<SyntaxNode, Diagnostic>> GetDiagnosticsGroupedByMember(
ImmutableArray<Diagnostic> diagnostics,
ISyntaxFactsService syntaxFacts,
SyntaxNode root,
out string diagnosticId,
out UnusedValuePreference preference,
out bool removeAssignments)
{
diagnosticId = diagnostics[0].Id;
var success = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostics[0], out preference);
Debug.Assert(success);
removeAssignments = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostics[0]);
#if DEBUG
foreach (var diagnostic in diagnostics)
{
Debug.Assert(diagnosticId == diagnostic.Id);
Debug.Assert(AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.TryGetUnusedValuePreference(diagnostic, out var diagnosticPreference) &&
diagnosticPreference == preference);
Debug.Assert(removeAssignments == AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsRemovableAssignmentDiagnostic(diagnostic));
}
#endif
return GetDiagnosticsGroupedByMember(diagnostics, syntaxFacts, root);
}
private static IEnumerable<IGrouping<SyntaxNode, Diagnostic>> GetDiagnosticsGroupedByMember(
ImmutableArray<Diagnostic> diagnostics,
ISyntaxFactsService syntaxFacts,
SyntaxNode root)
=> diagnostics.GroupBy(d => syntaxFacts.GetContainingMemberDeclaration(root, d.Location.SourceSpan.Start));
private static async Task<Document> PreprocessDocumentAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
// Track all the member declaration nodes that have diagnostics.
// We will post process all these tracked nodes after applying the fix (see "PostProcessDocumentAsync" below in this source file).
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var memberDeclarations = GetDiagnosticsGroupedByMember(diagnostics, syntaxFacts, root).Select(g => g.Key);
root = root.ReplaceNodes(memberDeclarations, computeReplacementNode: (_, n) => n.WithAdditionalAnnotations(s_memberAnnotation));
return document.WithSyntaxRoot(root);
}
protected sealed override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
{
document = await PreprocessDocumentAsync(document, diagnostics, cancellationToken).ConfigureAwait(false);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticFacts = document.GetLanguageService<ISemanticFactsService>();
var originalEditor = editor;
editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
try
{
// We compute the code fix in two passes:
// 1. The first pass groups the diagnostics to fix by containing member declaration and
// computes and applies the core code fixes. Grouping is done to ensure we choose
// the most appropriate name for new unused local declarations, which can clash
// with existing local declarations in the method body.
// 2. Second pass (PostProcessDocumentAsync) performs additional syntax manipulations
// for the fixes produced from from first pass:
// a. Replace discard declarations, such as "var _ = M();" that conflict with newly added
// discard assignments, with discard assignments of the form "_ = M();"
// b. Move newly introduced local declaration statements closer to the local variable's
// first reference.
// Get diagnostics grouped by member.
var diagnosticsGroupedByMember = GetDiagnosticsGroupedByMember(diagnostics, syntaxFacts, root,
out var diagnosticId, out var preference, out var removeAssignments);
// First pass to compute and apply the core code fixes.
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnosticsToFix in diagnosticsGroupedByMember)
{
var containingMemberDeclaration = diagnosticsToFix.Key;
using var nameGenerator = new UniqueVariableNameGenerator(containingMemberDeclaration, semanticModel, semanticFacts, cancellationToken);
await FixAllAsync(diagnosticId, diagnosticsToFix.Select(d => d), document, semanticModel, root, containingMemberDeclaration, preference,
removeAssignments, nameGenerator, editor, syntaxFacts, cancellationToken).ConfigureAwait(false);
}
// Second pass to post process the document.
var currentRoot = editor.GetChangedRoot();
var newRoot = await PostProcessDocumentAsync(document, currentRoot,
diagnosticId, preference, cancellationToken).ConfigureAwait(false);
if (currentRoot != newRoot)
{
editor.ReplaceNode(root, newRoot);
}
}
finally
{
originalEditor.ReplaceNode(originalEditor.OriginalRoot, editor.GetChangedRoot());
}
}
private async Task FixAllAsync(
string diagnosticId,
IEnumerable<Diagnostic> diagnostics,
Document document,
SemanticModel semanticModel,
SyntaxNode root,
SyntaxNode containingMemberDeclaration,
UnusedValuePreference preference,
bool removeAssignments,
UniqueVariableNameGenerator nameGenerator,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
switch (diagnosticId)
{
case IDEDiagnosticIds.ExpressionValueIsUnusedDiagnosticId:
// Make sure the inner diagnostics are placed first
FixAllExpressionValueIsUnusedDiagnostics(diagnostics.OrderByDescending(d => d.Location.SourceSpan.Start), semanticModel, root,
preference, nameGenerator, editor, syntaxFacts);
break;
case IDEDiagnosticIds.ValueAssignedIsUnusedDiagnosticId:
// Make sure the diagnostics are placed in order.
// Example:
// int a = 0; int b = 1;
// After fix it would be int a; int b;
await FixAllValueAssignedIsUnusedDiagnosticsAsync(diagnostics.OrderBy(d => d.Location.SourceSpan.Start), document, semanticModel, root, containingMemberDeclaration,
preference, removeAssignments, nameGenerator, editor, syntaxFacts, cancellationToken).ConfigureAwait(false);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private static void FixAllExpressionValueIsUnusedDiagnostics(
IOrderedEnumerable<Diagnostic> diagnostics,
SemanticModel semanticModel,
SyntaxNode root,
UnusedValuePreference preference,
UniqueVariableNameGenerator nameGenerator,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts)
{
// This method applies the code fix for diagnostics reported for expression statement dropping values.
// We replace each flagged expression statement with an assignment to a discard variable or a new unused local,
// based on the user's preference.
// Note: The diagnostic order here should be inner first and outer second.
// Example: Foo1(() => { Foo2(); })
// Foo2() should be the first in this case.
foreach (var diagnostic in diagnostics)
{
var expressionStatement = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf<TExpressionStatementSyntax>();
if (expressionStatement == null)
{
continue;
}
switch (preference)
{
case UnusedValuePreference.DiscardVariable:
Debug.Assert(semanticModel.Language != LanguageNames.VisualBasic);
var expression = syntaxFacts.GetExpressionOfExpressionStatement(expressionStatement);
editor.ReplaceNode(expression, (node, generator) =>
{
var discardAssignmentExpression = (TExpressionSyntax)generator.AssignmentStatement(
left: generator.IdentifierName(AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.DiscardVariableName),
right: node.WithoutTrivia())
.WithTriviaFrom(node)
.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
return discardAssignmentExpression;
});
break;
case UnusedValuePreference.UnusedLocalVariable:
var name = nameGenerator.GenerateUniqueNameAtSpanStart(expressionStatement).ValueText;
editor.ReplaceNode(expressionStatement, (node, generator) =>
{
var expression = syntaxFacts.GetExpressionOfExpressionStatement(node);
// Add Simplifier annotation so that 'var'/explicit type is correctly added based on user options.
var localDecl = editor.Generator.LocalDeclarationStatement(
name: name,
initializer: expression.WithoutLeadingTrivia())
.WithTriviaFrom(node)
.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
return localDecl;
});
break;
}
}
}
private async Task FixAllValueAssignedIsUnusedDiagnosticsAsync(
IOrderedEnumerable<Diagnostic> diagnostics,
Document document,
SemanticModel semanticModel,
SyntaxNode root,
SyntaxNode containingMemberDeclaration,
UnusedValuePreference preference,
bool removeAssignments,
UniqueVariableNameGenerator nameGenerator,
SyntaxEditor editor,
ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken)
{
// This method applies the code fix for diagnostics reported for unused value assignments to local/parameter.
// The actual code fix depends on whether or not the right hand side of the assignment has side effects.
// For example, if the right hand side is a constant or a reference to a local/parameter, then it has no side effects.
// The lack of side effects is indicated by the "removeAssignments" parameter for this function.
// If the right hand side has no side effects, then we can replace the assignments with variable declarations that have no initializer
// or completely remove the statement.
// If the right hand side does have side effects, we replace the identifier token for unused value assignment with
// a new identifier token (either discard '_' or new unused local variable name).
// For both the above cases, if the original diagnostic was reported on a local declaration, i.e. redundant initialization
// at declaration, then we also add a new variable declaration statement without initializer for this local.
using var _1 = PooledDictionary<SyntaxNode, SyntaxNode>.GetInstance(out var nodeReplacementMap);
using var _2 = PooledHashSet<SyntaxNode>.GetInstance(out var nodesToRemove);
using var _3 = PooledHashSet<(TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode node)>.GetInstance(out var nodesToAdd);
// Indicates if the node's trivia was processed.
using var _4 = PooledHashSet<SyntaxNode>.GetInstance(out var processedNodes);
using var _5 = PooledHashSet<TLocalDeclarationStatementSyntax>.GetInstance(out var candidateDeclarationStatementsForRemoval);
var hasAnyUnusedLocalAssignment = false;
foreach (var (node, isUnusedLocalAssignment) in GetNodesToFix())
{
hasAnyUnusedLocalAssignment |= isUnusedLocalAssignment;
var declaredLocal = semanticModel.GetDeclaredSymbol(node, cancellationToken) as ILocalSymbol;
if (declaredLocal == null && node.Parent is TCatchStatementSyntax)
{
declaredLocal = semanticModel.GetDeclaredSymbol(node.Parent, cancellationToken) as ILocalSymbol;
}
string newLocalNameOpt = null;
if (removeAssignments)
{
// Removable assignment or initialization, such that right hand side has no side effects.
if (declaredLocal != null)
{
// Redundant initialization.
// For example, "int a = 0;"
var variableDeclarator = node.FirstAncestorOrSelf<TVariableDeclaratorSyntax>();
Debug.Assert(variableDeclarator != null);
nodesToRemove.Add(variableDeclarator);
// Local declaration statement containing the declarator might be a candidate for removal if all its variables get marked for removal.
var candidate = GetCandidateLocalDeclarationForRemoval(variableDeclarator);
if (candidate != null)
{
candidateDeclarationStatementsForRemoval.Add(candidate);
}
}
else
{
// Redundant assignment or increment/decrement.
if (syntaxFacts.IsOperandOfIncrementOrDecrementExpression(node))
{
// For example, C# increment operation "a++;"
Debug.Assert(node.Parent.Parent is TExpressionStatementSyntax);
nodesToRemove.Add(node.Parent.Parent);
}
else
{
Debug.Assert(syntaxFacts.IsLeftSideOfAnyAssignment(node));
if (node.Parent is TStatementSyntax)
{
// For example, VB simple assignment statement "a = 0"
nodesToRemove.Add(node.Parent);
}
else if (node.Parent is TExpressionSyntax && node.Parent.Parent is TExpressionStatementSyntax)
{
// For example, C# simple assignment statement "a = 0;"
nodesToRemove.Add(node.Parent.Parent);
}
else
{
// For example, C# nested assignment statement "a = b = 0;", where assignment to 'b' is redundant.
// We replace the node with "a = 0;"
nodeReplacementMap.Add(node.Parent, syntaxFacts.GetRightHandSideOfAssignment(node.Parent));
}
}
}
}
else
{
// Value initialization/assignment where the right hand side may have side effects,
// and hence needs to be preserved in fixed code.
// For example, "x = MethodCall();" is replaced with "_ = MethodCall();" or "var unused = MethodCall();"
// Replace the flagged variable's indentifier token with new named, based on user's preference.
var newNameToken = preference == UnusedValuePreference.DiscardVariable
? document.GetRequiredLanguageService<SyntaxGeneratorInternal>().Identifier(AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.DiscardVariableName)
: nameGenerator.GenerateUniqueNameAtSpanStart(node);
newLocalNameOpt = newNameToken.ValueText;
var newNameNode = TryUpdateNameForFlaggedNode(node, newNameToken);
if (newNameNode == null)
{
continue;
}
// Is this is compound assignment?
if (syntaxFacts.IsLeftSideOfAnyAssignment(node) && !syntaxFacts.IsLeftSideOfAssignment(node))
{
// Compound assignment is changed to simple assignment.
// For example, "x += MethodCall();", where assignment to 'x' is redundant
// is replaced with "_ = MethodCall();" or "var unused = MethodCall();"
nodeReplacementMap.Add(node.Parent, GetReplacementNodeForCompoundAssignment(node.Parent, newNameNode, editor, syntaxFacts));
}
else
{
var newParentNode = TryUpdateParentOfUpdatedNode(node.Parent, newNameNode, editor, syntaxFacts);
if (newParentNode is object)
{
nodeReplacementMap.Add(node.Parent, newParentNode);
}
else
{
nodeReplacementMap.Add(node, newNameNode);
}
}
}
if (declaredLocal != null)
{
// We have a dead initialization for a local declaration.
// Introduce a new local declaration statement without an initializer for this local.
var declarationStatement = CreateLocalDeclarationStatement(declaredLocal.Type, declaredLocal.Name);
if (isUnusedLocalAssignment)
{
declarationStatement = declarationStatement.WithAdditionalAnnotations(s_unusedLocalDeclarationAnnotation);
}
nodesToAdd.Add((declarationStatement, node));
}
else
{
// We have a dead assignment to a local/parameter, which is not at the declaration site.
// Create a new local declaration for the unused local if both following conditions are met:
// 1. User prefers unused local variables for unused value assignment AND
// 2. Assignment value has side effects and hence cannot be removed.
if (preference == UnusedValuePreference.UnusedLocalVariable && !removeAssignments)
{
var type = semanticModel.GetTypeInfo(node, cancellationToken).Type;
Debug.Assert(type != null);
Debug.Assert(newLocalNameOpt != null);
var declarationStatement = CreateLocalDeclarationStatement(type, newLocalNameOpt);
nodesToAdd.Add((declarationStatement, node));
}
}
}
// Process candidate declaration statements for removal.
foreach (var localDeclarationStatement in candidateDeclarationStatementsForRemoval)
{
// If all the variable declarators for the local declaration statement are being removed,
// we can remove the entire local declaration statement.
if (ShouldRemoveStatement(localDeclarationStatement, out var variables))
{
nodesToRemove.Add(localDeclarationStatement);
nodesToRemove.RemoveRange(variables);
}
}
foreach (var (declarationStatement, node) in nodesToAdd)
{
InsertLocalDeclarationStatement(declarationStatement, node);
}
if (hasAnyUnusedLocalAssignment)
{
// Local declaration statements with no initializer, but non-zero references are candidates for removal
// if the code fix removes all these references.
// We annotate such declaration statements with no initializer abd non-zero references here
// and remove them in post process document pass later, if the code fix did remove all these references.
foreach (var localDeclarationStatement in containingMemberDeclaration.DescendantNodes().OfType<TLocalDeclarationStatementSyntax>())
{
var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement);
if (variables.Count == 1 &&
syntaxFacts.GetInitializerOfVariableDeclarator(variables[0]) == null &&
!(await IsLocalDeclarationWithNoReferencesAsync(localDeclarationStatement, document, cancellationToken).ConfigureAwait(false)))
{
nodeReplacementMap.Add(localDeclarationStatement, localDeclarationStatement.WithAdditionalAnnotations(s_existingLocalDeclarationWithoutInitializerAnnotation));
}
}
}
foreach (var node in nodesToRemove)
{
var removeOptions = SyntaxGenerator.DefaultRemoveOptions;
// If the leading trivia was not added to a new node, process it now.
if (!processedNodes.Contains(node))
{
// Don't keep trivia if the node is part of a multiple declaration statement.
// e.g. int x = 0, y = 0, z = 0; any white space left behind can cause problems if the declaration gets split apart.
var containingDeclaration = node.GetAncestor<TLocalDeclarationStatementSyntax>();
if (containingDeclaration != null && candidateDeclarationStatementsForRemoval.Contains(containingDeclaration))
{
removeOptions = SyntaxRemoveOptions.KeepNoTrivia;
}
else
{
removeOptions |= SyntaxRemoveOptions.KeepLeadingTrivia;
}
}
editor.RemoveNode(node, removeOptions);
}
foreach (var kvp in nodeReplacementMap)
{
editor.ReplaceNode(kvp.Key, kvp.Value.WithAdditionalAnnotations(Formatter.Annotation));
}
return;
// Local functions.
IEnumerable<(SyntaxNode node, bool isUnusedLocalAssignment)> GetNodesToFix()
{
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);
var isUnusedLocalAssignment = AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer.GetIsUnusedLocalDiagnostic(diagnostic);
yield return (node, isUnusedLocalAssignment);
}
}
// Mark generated local declaration statement with:
// 1. "s_newLocalDeclarationAnnotation" for post processing in "MoveNewLocalDeclarationsNearReference" below.
// 2. Simplifier annotation so that 'var'/explicit type is correctly added based on user options.
TLocalDeclarationStatementSyntax CreateLocalDeclarationStatement(ITypeSymbol type, string name)
=> (TLocalDeclarationStatementSyntax)editor.Generator.LocalDeclarationStatement(type, name)
.WithLeadingTrivia(syntaxFacts.ElasticCarriageReturnLineFeed)
.WithAdditionalAnnotations(s_newLocalDeclarationStatementAnnotation, Simplifier.Annotation);
void InsertLocalDeclarationStatement(TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode node)
{
// Find the correct place to insert the given declaration statement based on the node's ancestors.
var insertionNode = node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>((n, syntaxFacts) => n.Parent is TSwitchCaseBlockSyntax ||
syntaxFacts.IsExecutableBlock(n.Parent) &&
!(n is TCatchStatementSyntax) &&
!(n is TCatchBlockSyntax),
syntaxFacts);
if (insertionNode is TSwitchCaseLabelOrClauseSyntax)
{
InsertAtStartOfSwitchCaseBlockForDeclarationInCaseLabelOrClause(insertionNode.GetAncestor<TSwitchCaseBlockSyntax>(), editor, declarationStatement);
}
else if (insertionNode is TStatementSyntax)
{
// If the insertion node is being removed, keep the leading trivia with the new declaration.
if (nodesToRemove.Contains(insertionNode) && !processedNodes.Contains(insertionNode))
{
declarationStatement = declarationStatement.WithLeadingTrivia(insertionNode.GetLeadingTrivia());
// Mark the node as processed so that the trivia only gets added once.
processedNodes.Add(insertionNode);
}
editor.InsertBefore(insertionNode, declarationStatement);
}
}
bool ShouldRemoveStatement(TLocalDeclarationStatementSyntax localDeclarationStatement, out SeparatedSyntaxList<SyntaxNode> variables)
{
Debug.Assert(removeAssignments);
Debug.Assert(localDeclarationStatement != null);
// We should remove the entire local declaration statement if all its variables are marked for removal.
variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement);
foreach (var variable in variables)
{
if (!nodesToRemove.Contains(variable))
{
return false;
}
}
return true;
}
}
protected abstract TLocalDeclarationStatementSyntax GetCandidateLocalDeclarationForRemoval(TVariableDeclaratorSyntax declarator);
private async Task<SyntaxNode> PostProcessDocumentAsync(
Document document,
SyntaxNode currentRoot,
string diagnosticId,
UnusedValuePreference preference,
CancellationToken cancellationToken)
{
// If we added discard assignments, replace all discard variable declarations in
// this method with discard assignments, i.e. "var _ = M();" is replaced with "_ = M();"
// This is done to prevent compiler errors where the existing method has a discard
// variable declaration at a line following the one we added a discard assignment in our fix.
if (preference == UnusedValuePreference.DiscardVariable)
{
currentRoot = await PostProcessDocumentCoreAsync(
ReplaceDiscardDeclarationsWithAssignmentsAsync, currentRoot, document, cancellationToken).ConfigureAwait(false);
}
// If we added new variable declaration statements, move these as close as possible to their
// first reference site.
if (NeedsToMoveNewLocalDeclarationsNearReference(diagnosticId))
{
currentRoot = await PostProcessDocumentCoreAsync(
AdjustLocalDeclarationsAsync, currentRoot, document, cancellationToken).ConfigureAwait(false);
}
return currentRoot;
}
private static async Task<SyntaxNode> PostProcessDocumentCoreAsync(
Func<SyntaxNode, Document, CancellationToken, Task<SyntaxNode>> processMemberDeclarationAsync,
SyntaxNode currentRoot,
Document document,
CancellationToken cancellationToken)
{
// Process each member declaration which had atleast one diagnostic reported in the original tree
// and hence was annotated with "s_memberAnnotation" for post processing.
var newDocument = document.WithSyntaxRoot(currentRoot);
var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
using var _1 = PooledDictionary<SyntaxNode, SyntaxNode>.GetInstance(out var memberDeclReplacementsMap);
foreach (var memberDecl in newRoot.DescendantNodes().Where(n => n.HasAnnotation(s_memberAnnotation)))
{
var newMemberDecl = await processMemberDeclarationAsync(memberDecl, newDocument, cancellationToken).ConfigureAwait(false);
memberDeclReplacementsMap.Add(memberDecl, newMemberDecl);
}
return newRoot.ReplaceNodes(memberDeclReplacementsMap.Keys,
computeReplacementNode: (node, _) => memberDeclReplacementsMap[node]);
}
/// <summary>
/// Returns an updated <paramref name="memberDeclaration"/> with all the
/// local declarations named '_' converted to simple assignments to discard.
/// For example, <code>int _ = Computation();</code> is converted to
/// <code>_ = Computation();</code>.
/// This is needed to prevent the code fix/FixAll from generating code with
/// multiple local variables named '_', which is a compiler error.
/// </summary>
private async Task<SyntaxNode> ReplaceDiscardDeclarationsWithAssignmentsAsync(SyntaxNode memberDeclaration, Document document, CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IReplaceDiscardDeclarationsWithAssignmentsService>();
if (service == null)
{
return memberDeclaration;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await service.ReplaceAsync(memberDeclaration, semanticModel, document.Project.Solution.Workspace, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns an updated <paramref name="memberDeclaration"/> with all the new
/// local declaration statements annotated with <see cref="s_newLocalDeclarationStatementAnnotation"/>
/// moved closer to first reference and all the existing
/// local declaration statements annotated with <see cref="s_existingLocalDeclarationWithoutInitializerAnnotation"/>
/// whose declared local is no longer used removed.
/// </summary>
private async Task<SyntaxNode> AdjustLocalDeclarationsAsync(
SyntaxNode memberDeclaration,
Document document,
CancellationToken cancellationToken)
{
var service = document.GetLanguageService<IMoveDeclarationNearReferenceService>();
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var originalDocument = document;
var originalDeclStatementsToMoveOrRemove = memberDeclaration.DescendantNodes()
.Where(n => n.HasAnnotation(s_newLocalDeclarationStatementAnnotation) ||
n.HasAnnotation(s_existingLocalDeclarationWithoutInitializerAnnotation))
.ToImmutableArray();
if (originalDeclStatementsToMoveOrRemove.IsEmpty)
{
return memberDeclaration;
}
// Moving declarations closer to a reference can lead to conflicting edits.
// So, we track all the declaration statements to be moved upfront, and update
// the root, document, editor and memberDeclaration for every edit.
// Finally, we apply replace the memberDeclaration in the originalEditor as a single edit.
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var rootWithTrackedNodes = root.TrackNodes(originalDeclStatementsToMoveOrRemove);
// Run formatter prior to invoking IMoveDeclarationNearReferenceService.
rootWithTrackedNodes = Formatter.Format(rootWithTrackedNodes, originalDeclStatementsToMoveOrRemove.Select(s => s.Span), document.Project.Solution.Workspace, cancellationToken: cancellationToken);
document = document.WithSyntaxRoot(rootWithTrackedNodes);
await OnDocumentUpdatedAsync().ConfigureAwait(false);
foreach (TLocalDeclarationStatementSyntax originalDeclStatement in originalDeclStatementsToMoveOrRemove)
{
// Get the current declaration statement.
var declStatement = memberDeclaration.GetCurrentNode(originalDeclStatement);
var documentUpdated = false;
// Check if the variable declaration is unused after all the fixes, and hence can be removed.
if (await TryRemoveUnusedLocalAsync(declStatement, originalDeclStatement).ConfigureAwait(false))
{
documentUpdated = true;
}
else if (declStatement.HasAnnotation(s_newLocalDeclarationStatementAnnotation))
{
// Otherwise, move the declaration closer to the first reference if possible.
if (await service.CanMoveDeclarationNearReferenceAsync(document, declStatement, cancellationToken).ConfigureAwait(false))
{
document = await service.MoveDeclarationNearReferenceAsync(document, declStatement, cancellationToken).ConfigureAwait(false);
documentUpdated = true;
}
}
if (documentUpdated)
{
await OnDocumentUpdatedAsync().ConfigureAwait(false);
}
}
return memberDeclaration;
// Local functions.
async Task OnDocumentUpdatedAsync()
{
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
memberDeclaration = syntaxFacts.GetContainingMemberDeclaration(root, memberDeclaration.SpanStart);
}
async Task<bool> TryRemoveUnusedLocalAsync(TLocalDeclarationStatementSyntax newDecl, TLocalDeclarationStatementSyntax originalDecl)
{
// If we introduced this new local declaration statement while computing the code fix,
// but all it's existing references were removed as part of FixAll, then we
// can remove the unncessary local declaration statement.
// Additionally, if this is an existing local declaration without an initializer,
// such that the local has no references anymore, we can remove it.
if (newDecl.HasAnnotation(s_unusedLocalDeclarationAnnotation) ||
newDecl.HasAnnotation(s_existingLocalDeclarationWithoutInitializerAnnotation))
{
// Check if we have no references to local in fixed code.
if (await IsLocalDeclarationWithNoReferencesAsync(newDecl, document, cancellationToken).ConfigureAwait(false))
{
document = document.WithSyntaxRoot(
root.RemoveNode(newDecl, SyntaxGenerator.DefaultRemoveOptions | SyntaxRemoveOptions.KeepLeadingTrivia));
return true;
}
}
return false;
}
}
private static async Task<bool> IsLocalDeclarationWithNoReferencesAsync(
TLocalDeclarationStatementSyntax declStatement,
Document document,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var localDeclarationOperation = (IVariableDeclarationGroupOperation)semanticModel.GetOperation(declStatement, cancellationToken);
var local = localDeclarationOperation.GetDeclaredVariables().Single();
// Check if the declared variable has no references in fixed code.
var referencedSymbols = await SymbolFinder.FindReferencesAsync(local, document.Project.Solution, cancellationToken).ConfigureAwait(false);
return referencedSymbols.Count() == 1 &&
referencedSymbols.Single().Locations.IsEmpty();
}
private sealed class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey)
: base(title, createChangedDocument, equivalenceKey)
{
}
}
protected sealed class UniqueVariableNameGenerator : IDisposable
{
private readonly SyntaxNode _memberDeclaration;
private readonly SemanticModel _semanticModel;
private readonly ISemanticFactsService _semanticFacts;
private readonly CancellationToken _cancellationToken;
private readonly PooledHashSet<string> _usedNames;
public UniqueVariableNameGenerator(
SyntaxNode memberDeclaration,
SemanticModel semanticModel,
ISemanticFactsService semanticFacts,
CancellationToken cancellationToken)
{
_memberDeclaration = memberDeclaration;
_semanticModel = semanticModel;
_semanticFacts = semanticFacts;
_cancellationToken = cancellationToken;
_usedNames = PooledHashSet<string>.GetInstance();
}
public SyntaxToken GenerateUniqueNameAtSpanStart(SyntaxNode node)
{
var nameToken = _semanticFacts.GenerateUniqueName(_semanticModel, node, _memberDeclaration, "unused", _usedNames, _cancellationToken);
_usedNames.Add(nameToken.ValueText);
return nameToken;
}
public void Dispose() => _usedNames.Free();
}
}
}
| 56.647691 | 212 | 0.621988 | [
"MIT"
] | BrianFreemanAtlanta/roslyn | src/Analyzers/Core/CodeFixes/RemoveUnusedParametersAndValues/AbstractRemoveUnusedValuesCodeFixProvider.cs | 52,741 | C# |
using System.Collections.Generic;
namespace LiteDB
{
internal static class DictionaryExtensions
{
public static ushort NextIndex<T>(this Dictionary<ushort, T> dict)
{
ushort next = 0;
while (dict.ContainsKey(next))
{
next++;
}
return next;
}
public static T GetOrDefault<K, T>(this IDictionary<K, T> dict, K key, T defaultValue = default(T))
{
T result;
if (dict.TryGetValue(key, out result))
{
return result;
}
return defaultValue;
}
}
} | 21.193548 | 107 | 0.493151 | [
"MIT"
] | negue/LiteDB | LiteDB/Utils/DictionaryExtensions.cs | 659 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Apollo.Data
{
public interface ITableModel
{
int id { get; set; }
}
public abstract class BaseDataService
{
protected readonly IConnectionFactory connectionFactory;
protected BaseDataService(IConnectionFactory connectionFactory)
{
this.connectionFactory = connectionFactory;
}
protected async Task<IReadOnlyList<TResultType>> QueryAsync<TResultType>(string query)
{
try
{
using (var conn = await connectionFactory.GetConnection())
{
return (await conn.QueryAsync<TResultType>(query)).ToList();
}
}
catch (Exception exception)
{
Logger.Error(exception.Message, new { query });
throw new DatabaseException(exception.Message);
}
}
protected async Task<TModel> Upsert<TModel>(
string insertQuery,
string updateQuery,
string selectQuery,
TModel parameters,
Action<int> insertCallback = null,
Action<int> updateCallback = null) where TModel : ITableModel
{
int id = parameters.id;
if (id == default(int))
{
id = await InsertAndReturnId(insertQuery, parameters);
insertCallback?.Invoke(id);
}
else
{
await Execute(updateQuery, parameters);
updateCallback?.Invoke(id);
}
return (await QueryAsync<TModel>(selectQuery, new {id})).Single();
}
protected async Task<int> InsertAndReturnId(string query, object parameters)
{
try
{
using (var conn = await connectionFactory.GetConnection())
{
return (await conn.QueryAsync<IdResult>(query, parameters)).Single().id;
}
}
catch (Exception exception)
{
Logger.Error(exception.Message, new { query, parameters });
throw new DatabaseException(exception.Message);
}
}
protected async Task<IReadOnlyList<TResultType>> QueryAsync<TResultType>(string query, object parameters)
{
try
{
using (var conn = await connectionFactory.GetConnection())
{
return (await conn.QueryAsync<TResultType>(query, parameters)).ToList();
}
}
catch (Exception exception)
{
Logger.Error(exception.Message, new { query, parameters });
throw new DatabaseException(exception.Message);
}
}
protected async Task<int> Execute(string query, object parameters)
{
try
{
using (var conn = await connectionFactory.GetConnection())
{
return conn.Execute(query, parameters);
}
}
catch (Exception exception)
{
Logger.Error(exception.Message, new { query, parameters });
throw new DatabaseException(exception.Message);
}
}
}
}
| 31.363636 | 113 | 0.523478 | [
"MIT"
] | charlesj/Apollo | server/Apollo/Data/BaseDataService.cs | 3,452 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Application.Dtos;
namespace EasyAbp.EShop.Orders.Orders.Dtos
{
[Serializable]
public class GetOrderListDto : PagedAndSortedResultRequestDto
{
public Guid? StoreId { get; set; }
public Guid? CustomerUserId { get; set; }
[Range(1, 100)]
public override int MaxResultCount { get; set; } = DefaultMaxResultCount;
}
} | 26.235294 | 81 | 0.679372 | [
"MIT"
] | EasyAbp/EShop | modules/EasyAbp.EShop.Orders/src/EasyAbp.EShop.Orders.Application.Contracts/EasyAbp/EShop/Orders/Orders/Dtos/GetOrderListDto.cs | 448 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Assignment9")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Assignment9")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9dd6c1e0-02de-42f8-a4a1-a2b730b821c9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.567568 | 84 | 0.747482 | [
"MIT"
] | anhminh10a2hoa/Window-programming | Assignment9/Assignment9/Properties/AssemblyInfo.cs | 1,393 | C# |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Content.Server.NodeContainer.NodeGroups;
using Content.Server.NodeContainer.Nodes;
using Content.Shared.Examine;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.NodeContainer
{
/// <summary>
/// Creates and maintains a set of <see cref="Node"/>s.
/// </summary>
[RegisterComponent]
#pragma warning disable 618
public class NodeContainerComponent : Component, IExamine
#pragma warning restore 618
{
//HACK: THIS BEING readOnly IS A FILTHY HACK AND I HATE IT --moony
[DataField("nodes", readOnly: true)] [ViewVariables] public Dictionary<string, Node> Nodes { get; } = new();
[DataField("examinable")] private bool _examinable = false;
public T GetNode<T>(string identifier) where T : Node
{
return (T) Nodes[identifier];
}
public bool TryGetNode<T>(string identifier, [NotNullWhen(true)] out T? node) where T : Node
{
if (Nodes.TryGetValue(identifier, out var n) && n is T t)
{
node = t;
return true;
}
node = null;
return false;
}
public void Examine(FormattedMessage message, bool inDetailsRange)
{
if (!_examinable || !inDetailsRange) return;
foreach (var node in Nodes.Values)
{
if (node == null) continue;
switch (node.NodeGroupID)
{
case NodeGroupID.HVPower:
message.AddMarkup(
Loc.GetString("node-container-component-on-examine-details-hvpower") + "\n");
break;
case NodeGroupID.MVPower:
message.AddMarkup(
Loc.GetString("node-container-component-on-examine-details-mvpower") + "\n");
break;
case NodeGroupID.Apc:
message.AddMarkup(
Loc.GetString("node-container-component-on-examine-details-apc") + "\n");
break;
}
}
}
}
}
| 34.428571 | 116 | 0.560996 | [
"MIT"
] | AzzyIsNotHere/space-station-14 | Content.Server/NodeContainer/NodeContainerComponent.cs | 2,410 | C# |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using DotSpatial.Data;
using NetTopologySuite.Geometries;
using NUnit.Framework;
namespace DotSpatial.Symbology.Tests
{
/// <summary>
/// Tests for IndexSelection.
/// </summary>
[TestFixture]
internal class IndexSelectionTests
{
/// <summary>
/// Checks that only the attributes of the given field names get returned.
/// </summary>
[Test]
public void GetAttributesWithFieldNames()
{
var fs = new FeatureSet(FeatureType.Point);
fs.DataTable.Columns.Add("Column1");
fs.DataTable.Columns.Add("Column2");
fs.AddFeature(new Point(0, 0));
var fl = new PointLayer(fs);
var target = new IndexSelection(fl);
var attributesTable = target.GetAttributes(0, 1, new[] { "Column1" });
Assert.AreEqual(1, attributesTable.Columns.Count);
Assert.AreEqual("Column1", attributesTable.Columns[0].ColumnName);
}
}
}
| 33.027778 | 106 | 0.608915 | [
"MIT"
] | AlexanderSemenyak/DotSpatial | Source/DotSpatial.Symbology.Tests/IndexSelectionTests.cs | 1,191 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using AutoMapper.QueryableExtensions;
using FilterLists.Data;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
namespace FilterLists.Services.Seed
{
[UsedImplicitly]
public class SeedService : Service
{
public SeedService(FilterListsDbContext dbContext) : base(dbContext)
{
DbContext = dbContext;
}
public async Task<IEnumerable<TSeedDto>> GetAllAsync<TEntity, TSeedDto>() where TEntity : class =>
await DbContext.Set<TEntity>().AsNoTracking().ProjectTo<TSeedDto>().ToArrayAsync();
public async Task<IEnumerable<TSeedDto>> GetAllAsync<TEntity, TSeedDto>(PropertyInfo primarySort)
where TEntity : class
{
return await DbContext.Set<TEntity>()
.OrderBy(x => primarySort.GetValue(x, null))
.AsNoTracking()
.ProjectTo<TSeedDto>()
.ToArrayAsync();
}
public async Task<IEnumerable<TSeedDto>> GetAllAsync<TEntity, TSeedDto>(PropertyInfo primarySort,
PropertyInfo secondarySort) where TEntity : class
{
return await DbContext.Set<TEntity>()
.OrderBy(x => primarySort.GetValue(x, null))
.ThenBy(x => secondarySort.GetValue(x, null))
.AsNoTracking()
.ProjectTo<TSeedDto>()
.ToArrayAsync();
}
}
} | 38.386364 | 106 | 0.568384 | [
"MIT"
] | DandelionSprout/FilterLists | src/FilterLists.Services/Seed/SeedService.cs | 1,691 | C# |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace haxe.lang
{
public class HaxeException : global::System.Exception
{
public HaxeException(object obj) : base()
{
unchecked
{
#line 34 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Exceptions.hx"
if (( obj is global::haxe.lang.HaxeException ))
{
#line 36 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Exceptions.hx"
global::haxe.lang.HaxeException _obj = ((global::haxe.lang.HaxeException) (obj) );
obj = _obj.getObject();
}
#line 39 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Exceptions.hx"
this.obj = obj;
}
#line default
}
public static global::System.Exception wrap(object obj)
{
unchecked
{
#line 54 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Exceptions.hx"
if (( obj is global::System.Exception ))
{
#line 54 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Exceptions.hx"
return ((global::System.Exception) (obj) );
}
#line 56 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Exceptions.hx"
return new global::haxe.lang.HaxeException(((object) (obj) ));
}
#line default
}
public object obj;
public virtual object getObject()
{
unchecked
{
#line 44 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Exceptions.hx"
return this.obj;
}
#line default
}
public virtual string toString()
{
unchecked
{
#line 49 "C:\\HaxeToolkit\\haxe\\std/cs/internal/Exceptions.hx"
return global::haxe.lang.Runtime.concat("Haxe Exception: ", global::Std.@string(this.obj));
}
#line default
}
public override string ToString()
{
return this.toString();
}
}
}
| 21.74359 | 95 | 0.622052 | [
"MIT"
] | AxGord/TicTacToe | unity3d/bin/Assets/src/cs/internal/Exceptions.cs | 1,696 | C# |
using Xamarin.Forms;
namespace XamarinFormsSample.Views
{
/// <summary>
/// This class is a ViewCell that will be displayed for each employee.
/// </summary>
class EmployeeCell : ViewCell
{
public EmployeeCell()
{
StackLayout nameLayout = CreateNameLayout();
Image image = CreateEmployeeImageLayout;
StackLayout viewLayout = new StackLayout
{
Orientation = StackOrientation.Horizontal,
Children = { image, nameLayout }
};
View = viewLayout;
}
/// <summary>
/// Create a Xamarin.Forms image and bind it to the ImageUri property.
/// </summary>
/// <value>The create employee image layout.</value>
static Image CreateEmployeeImageLayout
{
get
{
Image image = new Image
{
HorizontalOptions = LayoutOptions.Start
};
image.SetBinding(Image.SourceProperty, new Binding("ImageUri"));
image.WidthRequest = image.HeightRequest = 40;
return image;
}
}
/// <summary>
/// Create a layout to hold the name & twitter handle of the user.
/// </summary>
/// <returns>The name layout.</returns>
static StackLayout CreateNameLayout()
{
#region Create a Label for name
Label nameLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand
};
nameLabel.SetBinding(Label.TextProperty, "DisplayName");
#endregion
#region Create a label for the Twitter handler.
Label twitterLabel = new Label
{
HorizontalOptions = LayoutOptions.FillAndExpand,
FontFamily = Fonts.Twitter.FontFamily,
FontSize = Fonts.Twitter.FontSize,
FontAttributes = Fonts.Twitter.FontAttributes
};
twitterLabel.SetBinding(Label.TextProperty, "Twitter");
#endregion
StackLayout nameLayout = new StackLayout
{
HorizontalOptions = LayoutOptions.StartAndExpand,
Orientation = StackOrientation.Vertical,
Children = { nameLabel, twitterLabel }
};
return nameLayout;
}
}
}
| 36.894737 | 90 | 0.473252 | [
"Apache-2.0"
] | 4qu3l3c4r4/xamarin-forms-samples | GettingStarted/CSSample/CSSample/XamarinFormsSample/Views/EmployeeCell.cs | 2,806 | C# |
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Duration
{
public uint Value;
}
| 16 | 38 | 0.78125 | [
"MIT"
] | Qibbi/BinaryAssetBuilder | source/BinaryAssetBuilder.Utility/Duration.cs | 130 | C# |
using System;
using Newtonsoft.Json;
namespace InventorConfig
{
public class ConfigLoader : ConfigEngine
{
public ConfigLoader(string path)
{
ConfigFileReadOnly configFile = new ConfigFileReadOnly(path);
Config = DeserializeConfiguration(configFile.Contents);
DecideIfWeShouldCloseInventorAfterCompletion();
App = GetInventorInstance();
Config.LoadConfigurationIntoInventor(App);
CloseInventorIfRequired();
}
private Configuration DeserializeConfiguration(string content)
{
try
{
return JsonConvert.DeserializeObject<Configuration>(content);
}
catch (Exception e)
{
throw new SystemException("The configuration was invalid, please verify json file syntax. Process was aborted, press any key to continue...", e);
}
}
}
}
| 30.967742 | 162 | 0.611458 | [
"MIT"
] | jordanrobot/InventorConf | src/InventorConfig/ConfigLoader.cs | 962 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OpenSleigh.Core;
using OpenSleigh.Core.Messaging;
namespace OpenSleigh.Samples.Sample3.Worker.Sagas
{
public class ChildSagaState : SagaState
{
public ChildSagaState(Guid id) : base(id) { }
}
public record StartChildSaga(Guid Id, Guid CorrelationId) : ICommand { }
public record ProcessChildSaga(Guid Id, Guid CorrelationId) : ICommand { }
public record ChildSagaCompleted(Guid Id, Guid CorrelationId) : IEvent { }
public class ChildSaga :
Saga<ChildSagaState>,
IStartedBy<StartChildSaga>,
IHandleMessage<ProcessChildSaga>
{
private readonly ILogger<ChildSaga> _logger;
private readonly Random _random = new Random();
public ChildSaga(ILogger<ChildSaga> logger, ChildSagaState state) : base(state)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task HandleAsync(IMessageContext<StartChildSaga> context, CancellationToken cancellationToken = default)
{
_logger.LogInformation($"starting child saga '{context.Message.CorrelationId}'...");
await Task.Delay(TimeSpan.FromSeconds(_random.Next(1, 5)), cancellationToken);
var message = new ProcessChildSaga(Guid.NewGuid(), context.Message.CorrelationId);
Publish(message);
}
public async Task HandleAsync(IMessageContext<ProcessChildSaga> context,
CancellationToken cancellationToken = default)
{
_logger.LogInformation($"processing child saga '{context.Message.CorrelationId}'...");
await Task.Delay(TimeSpan.FromSeconds(_random.Next(1, 5)), cancellationToken);
_logger.LogInformation($"child saga '{context.Message.CorrelationId}' completed!");
var completedEvent = new ChildSagaCompleted(Guid.NewGuid(), context.Message.CorrelationId);
Publish(completedEvent);
}
}
}
| 35.016949 | 125 | 0.684898 | [
"Apache-2.0"
] | PhilboLaggins/OpenSleigh | samples/Sample3/OpenSleigh.Samples.Sample3.Worker/Sagas/ChildSaga.cs | 2,066 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using NUnit.Framework;
using SkbKontur.Cassandra.Primitives.EventLog.Sharding;
namespace CassandraPrimitives.Tests.Tests.EventLog.Sharding
{
[TestFixture]
public class KeyDistributorTests
{
[Test]
public void TestGuidDistribution()
{
const int shardsCount = 10;
var keyDistributor = KeyDistributor.Create(shardsCount);
var array = new int[shardsCount];
const int guidsCount = 10000;
var sw = Stopwatch.StartNew();
for (var i = 0; i < guidsCount; i++)
{
var idx = keyDistributor.Distribute(Guid.NewGuid().ToString());
if (idx < 0 || idx >= shardsCount)
Assert.That(false);
array[idx]++;
}
Console.WriteLine("Time=" + sw.Elapsed);
var diff = array.Max() - array.Min();
Console.WriteLine("Diff = " + diff);
Assert.That(diff < guidsCount / 50);
}
[Test]
public void TestRandomStringDistribution()
{
const int shardsCount = 10;
var keyDistributor = KeyDistributor.Create(shardsCount);
var array = new int[shardsCount];
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Tests/EventLog/Sharding/Files/dict.txt");
var words = File.ReadAllText(path).Split('\n', '\r').Where(s => !string.IsNullOrEmpty(s)).ToArray();
var sw = Stopwatch.StartNew();
for (var i = 0; i < words.Length; i++)
{
var idx = keyDistributor.Distribute(words[i]);
if (idx < 0 || idx >= shardsCount)
Assert.That(false);
array[idx]++;
}
Console.WriteLine("Time=" + sw.Elapsed);
var diff = array.Max() - array.Min();
Console.WriteLine("Diff = " + diff);
Assert.That(diff < words.Length / 100);
}
}
} | 35.655172 | 117 | 0.544487 | [
"MIT"
] | skbkontur/cassandra-primitives | CassandraPrimitives.Tests/Tests/EventLog/Sharding/KeyDistributorTests.cs | 2,068 | C# |
using System.Web;
using System.Web.Optimization;
namespace Aurora
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
}
} | 49.418605 | 112 | 0.554824 | [
"MIT"
] | nkanish2002/Aurora | Aurora/App_Start/BundleConfig.cs | 2,127 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Problem03
{
public class StartUp
{
public static void Main()
{
string encoded = Console.ReadLine();
string placeholders = Console.ReadLine();
var separators = FindSeparators(encoded);
var holders = ParsePlaceholders(placeholders);
string result = encoded;
for (int i = 0; i < separators.Count; i++)
{
result = Regex.Replace(result, $"{separators[i]}(.+){separators[i]}",
$"{separators[i]}{holders[i]}{separators[i]}");
}
Console.WriteLine(result);
}
static List<string> FindSeparators(string encoded)
{
List<string> separatorsList = new List<string>();
StringBuilder searchBuilder = new StringBuilder();
string lastHit = null;
for (var i = 0; i < encoded.Length; i++)
{
char c = encoded[i];
string rest = encoded.Substring(i);
if (!Char.IsLetter(c))
{
if (!string.IsNullOrEmpty(lastHit))
{
i += rest.LastIndexOf(lastHit) + lastHit.Length;
separatorsList.Add(lastHit);
lastHit = null;
searchBuilder.Clear();
}
continue;
}
searchBuilder.Append(c);
if (rest.Contains(searchBuilder.ToString()))
{
lastHit = searchBuilder.ToString();
}
else
{
if (!string.IsNullOrEmpty(lastHit))
{
i += rest.LastIndexOf(lastHit) + lastHit.Length;
separatorsList.Add(lastHit);
lastHit = null;
searchBuilder.Clear();
}
}
}
return separatorsList;
}
static List<string> ParsePlaceholders(string placeholders)
{
Regex r = new Regex(@"\{(?<grp>.+?)\}");
List<string> matchesList = new List<string>();
foreach (var match in r.Matches(placeholders).Cast<Match>())
{
matchesList.Add(match.Groups["grp"].Value);
}
return matchesList;
}
}
}
| 30.552941 | 85 | 0.461687 | [
"MIT"
] | KonstantinRupchanski/softUni-homeworks | 30.PRACTICAL EXAM/Problem03/StartUp.cs | 2,599 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace helloworldapi
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| 23.192308 | 61 | 0.66335 | [
"MIT"
] | shailensukul/Kubernetes-Introduction | code/helloworldapi/Program.cs | 605 | C# |
using NullReferencesDemo.Presentation.Interfaces;
namespace NullReferencesDemo.Presentation.PurchaseReports
{
public class FailedPurchase: IPurchaseReport
{
private static FailedPurchase instance;
private FailedPurchase()
{
}
public static FailedPurchase Instance
{
get
{
if (instance == null)
instance = new FailedPurchase();
return instance;
}
}
}
}
| 20.88 | 57 | 0.545977 | [
"CC0-1.0"
] | rajeeshckr/managing-responsibility | tactical-design-patterns-dot-net-control-flow/7-exercise-files/02 DynamicViewsDemo Before/NullReferencesDemo/Presentation/PurchaseReports/FailedPurchase.cs | 524 | C# |
using Newtonsoft.Json;
using System;
namespace DevOpsLittleHelper
{
public class WebhookRequestEntity
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("subscriptionId")]
public string SubscriptionId { get; set; }
[JsonProperty("notificationId")]
public int NotificationId { get; set; }
[JsonProperty("createdDate")]
public DateTime CreatedDate { get; set; }
[JsonProperty("resource")]
public WebhookResource Resource { get; set; }
[JsonProperty("resourceContainers")]
public WebhookResourceContainer ResourceContainers { get; set; }
public class WebhookResourceContainer
{
[JsonProperty("collection")]
public WebhookIdRef Collection { get; set; }
[JsonProperty("account")]
public WebhookIdRef Account { get; set; }
[JsonProperty("project")]
public WebhookIdRef Project { get; set; }
}
public class WebhookResource
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("buildNumber")]
public string BuildNumber { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("uri")]
public string Uri { get; set; }
}
public class WebhookIdRef
{
[JsonProperty("id")]
public string Id { get; set; }
}
}
}
| 26.6 | 73 | 0.536967 | [
"MIT"
] | vijayraavi/DevOpsLittleHelper | DevOpsLittleHelper/Common/WebhookRequestEntity.cs | 1,598 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.