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 |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace StoreApp.Models
{
public class DbContextClass : DbContext
{
public DbContextClass()
{ }
public DbContextClass(DbContextOptions<DbContextClass> options)
: base(options)
{ }
public DbSet<Customer> Customers { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductOrder> ProductOrders { get; set; }
public DbSet<Inventory> Inventories { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (!options.IsConfigured)
options.UseSqlite("Data Source = StoreApp.db");
}
}
}
| 28.8125
| 78
| 0.642082
|
[
"MIT"
] |
042020-dotnet-uta/isaiahTaala-repo0
|
StoreApp/StoreApp/Models/DbContextClass.cs
| 924
|
C#
|
using System;
using System.IO;
using System.Net;
using System.Text;
namespace GodletRouter
{
public abstract class AbstractHttpHandler : IHttpHandler
{
private const string METHOD_DELETE = "DELETE";
private const string METHOD_HEAD = "HEAD";
private const string METHOD_GET = "GET";
private const string METHOD_OPTIONS = "OPTIONS";
private const string METHOD_POST = "POST";
private const string METHOD_PUT = "PUT";
private const string METHOD_TRACE = "TRACE";
public virtual void Service(HttpListenerRequest req, HttpListenerResponse resp)
{
string method = req.HttpMethod.ToUpper();
if (method.Equals(METHOD_GET))
{
doGet(req, resp);
}
else if (method.Equals(METHOD_HEAD))
{
doHead(req, resp);
}
else if (method.Equals(METHOD_POST))
{
doPost(req, resp);
}
else if (method.Equals(METHOD_PUT))
{
doPut(req, resp);
}
else if (method.Equals(METHOD_DELETE))
{
doDelete(req, resp);
}
else if (method.Equals(METHOD_OPTIONS))
{
doOptions(req, resp);
}
else if (method.Equals(METHOD_TRACE))
{
doTrace(req, resp);
}
else
{
throw new Exception("Not supported http method!");
}
}
protected virtual void doHead(HttpListenerRequest req, HttpListenerResponse resp)
{
}
protected virtual void doGet(HttpListenerRequest req, HttpListenerResponse resp)
{
}
protected virtual void doPost(HttpListenerRequest req, HttpListenerResponse resp)
{
}
protected virtual void doPut(HttpListenerRequest req, HttpListenerResponse resp)
{
}
protected virtual void doDelete(HttpListenerRequest req, HttpListenerResponse resp)
{
}
protected virtual void doOptions(HttpListenerRequest req, HttpListenerResponse resp)
{
}
protected virtual void doTrace(HttpListenerRequest req, HttpListenerResponse resp)
{
}
protected virtual void WriteString(HttpListenerResponse resp,string responseString)
{
if (resp.ContentLength64 != 0) return;
resp.ContentLength64 = Encoding.UTF8.GetByteCount(responseString);
resp.ContentType = "text/html; charset=UTF-8";
Stream output = resp.OutputStream;
StreamWriter writer = new StreamWriter(output);
writer.Write(responseString);
writer.Close();
}
}
}
| 29.843137
| 93
| 0.529238
|
[
"Apache-2.0"
] |
godlet-cn/GodletRouter
|
GodletRouter/AbstractHttpHandler.cs
| 3,046
|
C#
|
// Copyright 2017-2018 Dirk Lemstra (https://github.com/dlemstra/line-bot-sdk-dotnet)
//
// Dirk Lemstra licenses this file to you 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.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Line.Tests
{
public partial class EnumConverterTests
{
[TestClass]
public class UnixDateTimeConverterTests
{
[TestMethod]
public void ShouldThrowException()
{
UnixDateTimeConverter converter = new UnixDateTimeConverter();
ExceptionAssert.Throws<NotSupportedException>(() =>
{
converter.WriteJson(null, null, null);
});
}
}
}
}
| 33.078947
| 86
| 0.660302
|
[
"Apache-2.0"
] |
Ben67366/line-bot-sdk-dotnet
|
tests/LineBot.Tests/Converters/UnixDateTimeConverterTests/TheWriteJsonMethod.cs
| 1,259
|
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.Auth0.Outputs
{
[OutputType]
public sealed class TenantGuardianMfaPage
{
/// <summary>
/// Boolean. Indicates whether or not to use the custom Guardian page.
/// </summary>
public readonly bool Enabled;
/// <summary>
/// String, HTML format with supported Liquid syntax. Customized content of the Guardian page.
/// </summary>
public readonly string Html;
[OutputConstructor]
private TenantGuardianMfaPage(
bool enabled,
string html)
{
Enabled = enabled;
Html = html;
}
}
}
| 26.916667
| 102
| 0.625387
|
[
"ECL-2.0",
"Apache-2.0"
] |
kevinschoonover/pulumi-auth0
|
sdk/dotnet/Outputs/TenantGuardianMfaPage.cs
| 969
|
C#
|
using System.Collections.Generic;
namespace MyCompany.Authentication.External
{
public interface IExternalAuthConfiguration
{
List<ExternalLoginProviderInfo> Providers { get; }
}
}
| 20.3
| 58
| 0.743842
|
[
"MIT"
] |
StefanKoenen/aspnetboilerplate-5844
|
aspnet-core/src/MyCompany.Web.Core/Authentication/External/IExternalAuthConfiguration.cs
| 205
|
C#
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.ContentEditing;
using Umbraco.Core.Serialization;
using Umbraco.Web.Routing;
namespace Umbraco.Web.Models.ContentEditing
{
/// <summary>
/// A model representing a content item to be displayed in the back office
/// </summary>
[DataContract(Name = "content", Namespace = "")]
public class ContentItemDisplay : INotificationModel, IErrorModel //ListViewAwareContentItemDisplayBase<ContentPropertyDisplay, IContent>
{
public ContentItemDisplay()
{
AllowPreview = true;
Notifications = new List<Notification>();
Errors = new Dictionary<string, object>();
Variants = new List<ContentVariantDisplay>();
ContentApps = new List<ContentApp>();
}
[DataMember(Name = "id", IsRequired = true)]
[Required]
public int Id { get; set; }
[DataMember(Name = "udi")]
[ReadOnly(true)]
[JsonConverter(typeof(UdiJsonConverter))]
public Udi Udi { get; set; }
[DataMember(Name = "icon")]
public string Icon { get; set; }
[DataMember(Name = "trashed")]
[ReadOnly(true)]
public bool Trashed { get; set; }
/// <summary>
/// This is the unique Id stored in the database - but could also be the unique id for a custom membership provider
/// </summary>
[DataMember(Name = "key")]
public Guid Key { get; set; }
[DataMember(Name = "parentId", IsRequired = true)]
[Required]
public int ParentId { get; set; }
/// <summary>
/// The path of the entity
/// </summary>
[DataMember(Name = "path")]
public string Path { get; set; }
/// <summary>
/// A collection of content variants
/// </summary>
/// <remarks>
/// If a content item is invariant, this collection will only contain one item, else it will contain all culture variants
/// </remarks>
[DataMember(Name = "variants")]
public IEnumerable<ContentVariantDisplay> Variants { get; set; }
[DataMember(Name = "owner")]
public UserProfile Owner { get; set; }
[DataMember(Name = "updater")]
public UserProfile Updater { get; set; }
/// <summary>
/// The name of the content type
/// </summary>
[DataMember(Name = "contentTypeName")]
public string ContentTypeName { get; set; }
/// <summary>
/// Indicates if the content is configured as a list view container
/// </summary>
[DataMember(Name = "isContainer")]
public bool IsContainer { get; set; }
/// <summary>
/// Property indicating if this item is part of a list view parent
/// </summary>
[DataMember(Name = "isChildOfListView")]
public bool IsChildOfListView { get; set; }
/// <summary>
/// Property for the entity's individual tree node URL
/// </summary>
/// <remarks>
/// This is required if the item is a child of a list view since the tree won't actually be loaded,
/// so the app will need to go fetch the individual tree node in order to be able to load it's action list (menu)
/// </remarks>
[DataMember(Name = "treeNodeUrl")]
public string TreeNodeUrl { get; set; }
[DataMember(Name = "contentTypeAlias", IsRequired = true)]
[Required(AllowEmptyStrings = false)]
public string ContentTypeAlias { get; set; }
[DataMember(Name = "sortOrder")]
public int SortOrder { get; set; }
/// <summary>
/// This is the last updated date for the entire content object regardless of variants
/// </summary>
/// <remarks>
/// Each variant has it's own update date assigned as well
/// </remarks>
[DataMember(Name = "updateDate")]
public DateTime UpdateDate { get; set; }
[DataMember(Name = "template")]
public string TemplateAlias { get; set; }
[DataMember(Name = "templateId")]
public int TemplateId { get; set; }
[DataMember(Name = "allowedTemplates")]
public IDictionary<string, string> AllowedTemplates { get; set; }
[DataMember(Name = "documentType")]
public ContentTypeBasic DocumentType { get; set; }
[DataMember(Name = "urls")]
public UrlInfo[] Urls { get; set; }
/// <summary>
/// Determines whether previewing is allowed for this node
/// </summary>
/// <remarks>
/// By default this is true but by using events developers can toggle this off for certain documents if there is nothing to preview
/// </remarks>
[DataMember( Name = "allowPreview" )]
public bool AllowPreview { get; set; }
/// <summary>
/// The allowed 'actions' based on the user's permissions - Create, Update, Publish, Send to publish
/// </summary>
/// <remarks>
/// Each char represents a button which we can then map on the front-end to the correct actions
/// </remarks>
[DataMember(Name = "allowedActions")]
public IEnumerable<string> AllowedActions { get; set; }
[DataMember(Name = "isBlueprint")]
public bool IsBlueprint { get; set; }
[DataMember(Name = "apps")]
public IEnumerable<ContentApp> ContentApps { get; set; }
/// <summary>
/// The real persisted content object - used during inbound model binding
/// </summary>
/// <remarks>
/// This is not used for outgoing model information.
/// </remarks>
[IgnoreDataMember]
internal IContent PersistedContent { get; set; }
/// <summary>
/// The DTO object used to gather all required content data including data type information etc... for use with validation - used during inbound model binding
/// </summary>
/// <remarks>
/// We basically use this object to hydrate all required data from the database into one object so we can validate everything we need
/// instead of having to look up all the data individually.
/// This is not used for outgoing model information.
/// </remarks>
[IgnoreDataMember]
internal ContentPropertyCollectionDto ContentDto { get; set; }
/// <summary>
/// This is used to add custom localized messages/strings to the response for the app to use for localized UI purposes.
/// </summary>
[DataMember(Name = "notifications")]
[ReadOnly(true)]
public List<Notification> Notifications { get; private set; }
/// <summary>
/// This is used for validation of a content item.
/// </summary>
/// <remarks>
/// A content item can be invalid but still be saved. This occurs when there's property validation errors, we will
/// still save the item but it cannot be published. So we need a way of returning validation errors as well as the
/// updated model.
///
/// NOTE: The ProperCase is important because when we return ModeState normally it will always be proper case.
/// </remarks>
[DataMember(Name = "ModelState")]
[ReadOnly(true)]
public IDictionary<string, object> Errors { get; set; }
/// <summary>
/// A collection of extra data that is available for this specific entity/entity type
/// </summary>
[DataMember(Name = "metaData")]
[ReadOnly(true)]
public IDictionary<string, object> AdditionalData { get; private set; }
}
}
| 37.976077
| 166
| 0.603881
|
[
"MIT"
] |
lars-erik/Umbraco-CMS
|
src/Umbraco.Web/Models/ContentEditing/ContentItemDisplay.cs
| 7,939
|
C#
|
using Cdy.Spider.DevelopCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Cdy.Spider.CalculateDriver.Develop
{
public class ScriptExpressConfigModel : ViewModelBase, IRegistorConfigModel
{
private ICommand mExpressionEditCommand;
private ICommand mClearCommand;
private string mExpresstion = "";
/// <summary>
///
/// </summary>
public Action<string> UpdateRegistorCallBack { get; set; }
/// <summary>
///
/// </summary>
public IDeviceDevelopService Service { get; set; }
/// <summary>
///
/// </summary>
public string Expresstion
{
get
{
return mExpresstion;
}
set
{
if (mExpresstion != value)
{
mExpresstion = value;
OnPropertyChanged("Expresstion");
}
}
}
/// <summary>
///
/// </summary>
public ICommand ExpressionEditCommand
{
get
{
if(mExpressionEditCommand==null)
{
mExpressionEditCommand = new RelayCommand(() => {
ExpressionEditViewModel mm = new ExpressionEditViewModel();
mm.Expresse = this.Expresstion;
if(mm.ShowDialog().Value)
{
Expresstion = mm.GetExpressResult();
UpdateRegistor();
}
});
}
return mExpressionEditCommand;
}
}
/// <summary>
///
/// </summary>
public ICommand ClearCommand
{
get
{
if(mClearCommand==null)
{
mClearCommand = new RelayCommand(() => {
Expresstion = "";
UpdateRegistor();
});
}
return mClearCommand;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerable<string> Config()
{
return new List<string>();
}
public void FreshRegistor(string registor)
{
Expresstion = registor;
}
public void OnDisActived()
{
UpdateRegistor();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private void UpdateRegistor()
{
UpdateRegistorCallBack?.Invoke(Expresstion);
}
/// <summary>
///
/// </summary>
public override void Dispose()
{
UpdateRegistorCallBack = null;
base.Dispose();
}
}
}
| 24.712
| 83
| 0.432179
|
[
"Apache-2.0"
] |
bingwang12/Spider
|
Develop/Drivers/Cdy.Spider.CalculateDriver.Develop/ScriptExpressConfigModel.cs
| 3,091
|
C#
|
using System;
namespace ModernMoleculeViewer.Model
{
/// <summary>
/// <see cref="Atom" /> subclass for atoms that are not waters and are not standard protein chain atoms.
/// </summary>
/// <remarks>
/// Adds functionality to toggle visibility based on the <see cref="Molecule.ShowHetAtoms" /> property.
/// </remarks>
internal class HetAtom : Atom
{
/// <summary>
/// Attaches an event handedler to <see cref="Molecule.ShowHetAtomsChanged" />.
/// </summary>
internal override void Initialize()
{
base.Initialize();
Molecule.ShowHetAtomsChanged += MoleculeShowHetAtomsChanged;
}
/* /// <summary>
/// Override to check <see cref="Molecule.ShowHetAtoms" /> when the atom's selection state
/// is changed.
/// </summary>
protected override void UpdateSelectionView()
{
base.UpdateSelectionView();
RenderAtomModel(Molecule.ShowHetAtoms || ShowAsSelected);
}*/
/// <summary>
/// Toggles visibility based on the <see cref="Molecule.ShowHetAtoms" /> property.
/// </summary>
/// <param name="sender">The molecule.</param>
/// <param name="e">Empty event args.</param>
private void MoleculeShowHetAtomsChanged(object sender, EventArgs e)
{
/*
RenderAtomModel(Molecule.ShowHetAtoms || ShowAsSelected);
*/
}
}
}
| 31.978261
| 108
| 0.594154
|
[
"MIT"
] |
kobush/ModernMoleculeViewer
|
win10/src/ModernMoleculeViewer/Model/HetAtom.cs
| 1,471
|
C#
|
// Copyright 2013-2017 Serilog Contributors
//
// 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;
using System.ComponentModel;
using System.Text;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Display;
using Serilog.Formatting.Json;
using Serilog.Sinks.File;
// ReSharper disable RedundantArgumentDefaultValue, MethodOverloadWithOptionalParameter
namespace Serilog
{
/// <summary>Extends <see cref="LoggerConfiguration"/> with methods to add file sinks.</summary>
public static class FileLoggerConfigurationExtensions
{
const int DefaultRetainedFileCountLimit = 31; // A long month of logs
const long DefaultFileSizeLimitBytes = 1L * 1024 * 1024 * 1024;
const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}";
/// <summary>
/// Write log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <param name="outputTemplate">A message template describing the format used to write to the sink.
/// the default is "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}".</param>
/// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow.
/// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit
/// will be written in full even if it exceeds the limit.</param>
/// <param name="buffered">Indicates if flushing to the output file can be buffered or not. The default
/// is false.</param>
/// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param>
/// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <remarks>The file will be written using the UTF-8 character set.</remarks>
[Obsolete("New code should not be compiled against this obsolete overload"), EditorBrowsable(EditorBrowsableState.Never)]
public static LoggerConfiguration File(
this LoggerSinkConfiguration sinkConfiguration,
string path,
LogEventLevel restrictedToMinimumLevel,
string outputTemplate,
IFormatProvider formatProvider,
long? fileSizeLimitBytes,
LoggingLevelSwitch levelSwitch,
bool buffered,
bool shared,
TimeSpan? flushToDiskInterval)
{
return File(sinkConfiguration, path, restrictedToMinimumLevel, outputTemplate, formatProvider, fileSizeLimitBytes,
levelSwitch, buffered, shared, flushToDiskInterval, RollingInterval.Infinite, false, null, null, null);
}
/// <summary>
/// Write log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="formatter">A formatter, such as <see cref="JsonFormatter"/>, to convert the log events into
/// text for the file. If control of regular text formatting is required, use the other
/// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?)"/>
/// and specify the outputTemplate parameter instead.
/// </param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow.
/// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit
/// will be written in full even if it exceeds the limit.</param>
/// <param name="buffered">Indicates if flushing to the output file can be buffered or not. The default
/// is false.</param>
/// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param>
/// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <remarks>The file will be written using the UTF-8 character set.</remarks>
[Obsolete("New code should not be compiled against this obsolete overload"), EditorBrowsable(EditorBrowsableState.Never)]
public static LoggerConfiguration File(
this LoggerSinkConfiguration sinkConfiguration,
ITextFormatter formatter,
string path,
LogEventLevel restrictedToMinimumLevel,
long? fileSizeLimitBytes,
LoggingLevelSwitch levelSwitch,
bool buffered,
bool shared,
TimeSpan? flushToDiskInterval)
{
return File(sinkConfiguration, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch,
buffered, shared, flushToDiskInterval, RollingInterval.Infinite, false, null, null, null);
}
/// <summary>
/// Write log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <param name="outputTemplate">A message template describing the format used to write to the sink.
/// the default is "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}".</param>
/// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow.
/// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit
/// will be written in full even if it exceeds the limit.</param>
/// <param name="buffered">Indicates if flushing to the output file can be buffered or not. The default
/// is false.</param>
/// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param>
/// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param>
/// <param name="rollingInterval">The interval at which logging will roll over to a new file.</param>
/// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames
/// will have a number appended in the format <code>_NNN</code>, with the first filename given no number.</param>
/// <param name="retainedFileCountLimit">The maximum number of log files that will be retained,
/// including the current log file. For unlimited retention, pass null. The default is 31.</param>
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param>
/// <returns>Configuration object allowing method chaining.</returns>
[Obsolete("New code should not be compiled against this obsolete overload"), EditorBrowsable(EditorBrowsableState.Never)]
public static LoggerConfiguration File(
this LoggerSinkConfiguration sinkConfiguration,
string path,
LogEventLevel restrictedToMinimumLevel,
string outputTemplate,
IFormatProvider formatProvider,
long? fileSizeLimitBytes,
LoggingLevelSwitch levelSwitch,
bool buffered,
bool shared,
TimeSpan? flushToDiskInterval,
RollingInterval rollingInterval,
bool rollOnFileSizeLimit,
int? retainedFileCountLimit,
Encoding encoding)
{
return File(sinkConfiguration, path, restrictedToMinimumLevel, outputTemplate, formatProvider, fileSizeLimitBytes, levelSwitch, buffered,
shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding, null);
}
/// <summary>
/// Write log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="formatter">A formatter, such as <see cref="JsonFormatter"/>, to convert the log events into
/// text for the file. If control of regular text formatting is required, use the other
/// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?, RollingInterval, bool, int?, Encoding, FileLifecycleHooks)"/>
/// and specify the outputTemplate parameter instead.
/// </param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow.
/// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit
/// will be written in full even if it exceeds the limit.</param>
/// <param name="buffered">Indicates if flushing to the output file can be buffered or not. The default
/// is false.</param>
/// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param>
/// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param>
/// <param name="rollingInterval">The interval at which logging will roll over to a new file.</param>
/// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames
/// will have a number appended in the format <code>_NNN</code>, with the first filename given no number.</param>
/// <param name="retainedFileCountLimit">The maximum number of log files that will be retained,
/// including the current log file. For unlimited retention, pass null. The default is 31.</param>
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param>
/// <returns>Configuration object allowing method chaining.</returns>
[Obsolete("New code should not be compiled against this obsolete overload"), EditorBrowsable(EditorBrowsableState.Never)]
public static LoggerConfiguration File(
this LoggerSinkConfiguration sinkConfiguration,
ITextFormatter formatter,
string path,
LogEventLevel restrictedToMinimumLevel,
long? fileSizeLimitBytes,
LoggingLevelSwitch levelSwitch,
bool buffered,
bool shared,
TimeSpan? flushToDiskInterval,
RollingInterval rollingInterval,
bool rollOnFileSizeLimit,
int? retainedFileCountLimit,
Encoding encoding)
{
return File(sinkConfiguration, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch, buffered,
shared, flushToDiskInterval, rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding, null);
}
/// <summary>
/// Write log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <param name="outputTemplate">A message template describing the format used to write to the sink.
/// the default is "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}".</param>
/// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow.
/// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit
/// will be written in full even if it exceeds the limit.</param>
/// <param name="buffered">Indicates if flushing to the output file can be buffered or not. The default
/// is false.</param>
/// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param>
/// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param>
/// <param name="rollingInterval">The interval at which logging will roll over to a new file.</param>
/// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames
/// will have a number appended in the format <code>_NNN</code>, with the first filename given no number.</param>
/// <param name="retainedFileCountLimit">The maximum number of log files that will be retained,
/// including the current log file. For unlimited retention, pass null. The default is 31.</param>
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param>
/// <param name="hooks">Optionally enables hooking into log file lifecycle events.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration File(
this LoggerSinkConfiguration sinkConfiguration,
string path,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
string outputTemplate = DefaultOutputTemplate,
IFormatProvider formatProvider = null,
long? fileSizeLimitBytes = DefaultFileSizeLimitBytes,
LoggingLevelSwitch levelSwitch = null,
bool buffered = false,
bool shared = false,
TimeSpan? flushToDiskInterval = null,
RollingInterval rollingInterval = RollingInterval.Infinite,
bool rollOnFileSizeLimit = false,
int? retainedFileCountLimit = DefaultRetainedFileCountLimit,
Encoding encoding = null,
FileLifecycleHooks hooks = null)
{
if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration));
if (path == null) throw new ArgumentNullException(nameof(path));
if (outputTemplate == null) throw new ArgumentNullException(nameof(outputTemplate));
var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
return File(sinkConfiguration, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes,
levelSwitch, buffered, shared, flushToDiskInterval,
rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding, hooks);
}
/// <summary>
/// Write log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="formatter">A formatter, such as <see cref="JsonFormatter"/>, to convert the log events into
/// text for the file. If control of regular text formatting is required, use the other
/// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?, RollingInterval, bool, int?, Encoding, FileLifecycleHooks)"/>
/// and specify the outputTemplate parameter instead.
/// </param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <param name="fileSizeLimitBytes">The approximate maximum size, in bytes, to which a log file will be allowed to grow.
/// For unrestricted growth, pass null. The default is 1 GB. To avoid writing partial events, the last event within the limit
/// will be written in full even if it exceeds the limit.</param>
/// <param name="buffered">Indicates if flushing to the output file can be buffered or not. The default
/// is false.</param>
/// <param name="shared">Allow the log file to be shared by multiple processes. The default is false.</param>
/// <param name="flushToDiskInterval">If provided, a full disk flush will be performed periodically at the specified interval.</param>
/// <param name="rollingInterval">The interval at which logging will roll over to a new file.</param>
/// <param name="rollOnFileSizeLimit">If <code>true</code>, a new file will be created when the file size limit is reached. Filenames
/// will have a number appended in the format <code>_NNN</code>, with the first filename given no number.</param>
/// <param name="retainedFileCountLimit">The maximum number of log files that will be retained,
/// including the current log file. For unlimited retention, pass null. The default is 31.</param>
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param>
/// <param name="hooks">Optionally enables hooking into log file lifecycle events.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration File(
this LoggerSinkConfiguration sinkConfiguration,
ITextFormatter formatter,
string path,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
long? fileSizeLimitBytes = DefaultFileSizeLimitBytes,
LoggingLevelSwitch levelSwitch = null,
bool buffered = false,
bool shared = false,
TimeSpan? flushToDiskInterval = null,
RollingInterval rollingInterval = RollingInterval.Infinite,
bool rollOnFileSizeLimit = false,
int? retainedFileCountLimit = DefaultRetainedFileCountLimit,
Encoding encoding = null,
FileLifecycleHooks hooks = null)
{
if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration));
if (formatter == null) throw new ArgumentNullException(nameof(formatter));
if (path == null) throw new ArgumentNullException(nameof(path));
return ConfigureFile(sinkConfiguration.Sink, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch,
buffered, false, shared, flushToDiskInterval, encoding, rollingInterval, rollOnFileSizeLimit,
retainedFileCountLimit, hooks);
}
/// <summary>
/// Write log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <param name="outputTemplate">A message template describing the format used to write to the sink.
/// the default is "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}".</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <remarks>The file will be written using the UTF-8 character set.</remarks>
[Obsolete("New code should not be compiled against this obsolete overload"), EditorBrowsable(EditorBrowsableState.Never)]
public static LoggerConfiguration File(
this LoggerAuditSinkConfiguration sinkConfiguration,
string path,
LogEventLevel restrictedToMinimumLevel,
string outputTemplate,
IFormatProvider formatProvider,
LoggingLevelSwitch levelSwitch)
{
return File(sinkConfiguration, path, restrictedToMinimumLevel, outputTemplate, formatProvider, levelSwitch, null, null);
}
/// <summary>
/// Write log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="formatter">A formatter, such as <see cref="JsonFormatter"/>, to convert the log events into
/// text for the file. If control of regular text formatting is required, use the other
/// overload of <see cref="File(LoggerAuditSinkConfiguration, string, LogEventLevel, string, IFormatProvider, LoggingLevelSwitch)"/>
/// and specify the outputTemplate parameter instead.
/// </param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <remarks>The file will be written using the UTF-8 character set.</remarks>
[Obsolete("New code should not be compiled against this obsolete overload"), EditorBrowsable(EditorBrowsableState.Never)]
public static LoggerConfiguration File(
this LoggerAuditSinkConfiguration sinkConfiguration,
ITextFormatter formatter,
string path,
LogEventLevel restrictedToMinimumLevel,
LoggingLevelSwitch levelSwitch)
{
return File(sinkConfiguration, formatter, path, restrictedToMinimumLevel, levelSwitch, null, null);
}
/// <summary>
/// Write audit log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <param name="outputTemplate">A message template describing the format used to write to the sink.
/// the default is "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}".</param>
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param>
/// <param name="hooks">Optionally enables hooking into log file lifecycle events.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration File(
this LoggerAuditSinkConfiguration sinkConfiguration,
string path,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
string outputTemplate = DefaultOutputTemplate,
IFormatProvider formatProvider = null,
LoggingLevelSwitch levelSwitch = null,
Encoding encoding = null,
FileLifecycleHooks hooks = null)
{
if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration));
if (path == null) throw new ArgumentNullException(nameof(path));
if (outputTemplate == null) throw new ArgumentNullException(nameof(outputTemplate));
var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
return File(sinkConfiguration, formatter, path, restrictedToMinimumLevel, levelSwitch, encoding, hooks);
}
/// <summary>
/// Write audit log events to the specified file.
/// </summary>
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="formatter">A formatter, such as <see cref="JsonFormatter"/>, to convert the log events into
/// text for the file. If control of regular text formatting is required, use the other
/// overload of <see cref="File(LoggerAuditSinkConfiguration, string, LogEventLevel, string, IFormatProvider, LoggingLevelSwitch, Encoding, FileLifecycleHooks)"/>
/// and specify the outputTemplate parameter instead.
/// </param>
/// <param name="path">Path to the file.</param>
/// <param name="restrictedToMinimumLevel">The minimum level for
/// events passed through the sink. Ignored when <paramref name="levelSwitch"/> is specified.</param>
/// <param name="levelSwitch">A switch allowing the pass-through minimum level
/// to be changed at runtime.</param>
/// <param name="encoding">Character encoding used to write the text file. The default is UTF-8 without BOM.</param>
/// <param name="hooks">Optionally enables hooking into log file lifecycle events.</param>
/// <returns>Configuration object allowing method chaining.</returns>
public static LoggerConfiguration File(
this LoggerAuditSinkConfiguration sinkConfiguration,
ITextFormatter formatter,
string path,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
LoggingLevelSwitch levelSwitch = null,
Encoding encoding = null,
FileLifecycleHooks hooks = null)
{
if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration));
if (formatter == null) throw new ArgumentNullException(nameof(formatter));
if (path == null) throw new ArgumentNullException(nameof(path));
return ConfigureFile(sinkConfiguration.Sink, formatter, path, restrictedToMinimumLevel, null, levelSwitch, false, true,
false, null, encoding, RollingInterval.Infinite, false, null, hooks);
}
static LoggerConfiguration ConfigureFile(
this Func<ILogEventSink, LogEventLevel, LoggingLevelSwitch, LoggerConfiguration> addSink,
ITextFormatter formatter,
string path,
LogEventLevel restrictedToMinimumLevel,
long? fileSizeLimitBytes,
LoggingLevelSwitch levelSwitch,
bool buffered,
bool propagateExceptions,
bool shared,
TimeSpan? flushToDiskInterval,
Encoding encoding,
RollingInterval rollingInterval,
bool rollOnFileSizeLimit,
int? retainedFileCountLimit,
FileLifecycleHooks hooks)
{
if (addSink == null) throw new ArgumentNullException(nameof(addSink));
if (formatter == null) throw new ArgumentNullException(nameof(formatter));
if (path == null) throw new ArgumentNullException(nameof(path));
if (fileSizeLimitBytes.HasValue && fileSizeLimitBytes < 0) throw new ArgumentException("Negative value provided; file size limit must be non-negative.", nameof(fileSizeLimitBytes));
if (retainedFileCountLimit.HasValue && retainedFileCountLimit < 1) throw new ArgumentException("At least one file must be retained.", nameof(retainedFileCountLimit));
if (shared && buffered) throw new ArgumentException("Buffered writes are not available when file sharing is enabled.", nameof(buffered));
if (shared && hooks != null) throw new ArgumentException("File lifecycle hooks are not currently supported for shared log files.", nameof(hooks));
ILogEventSink sink;
if (rollOnFileSizeLimit || rollingInterval != RollingInterval.Infinite)
{
sink = new RollingFileSink(path, formatter, fileSizeLimitBytes, retainedFileCountLimit, encoding, buffered, shared, rollingInterval, rollOnFileSizeLimit, hooks);
}
else
{
try
{
if (shared)
{
#pragma warning disable 618
sink = new SharedFileSink(path, formatter, fileSizeLimitBytes, encoding);
#pragma warning restore 618
}
else
{
sink = new FileSink(path, formatter, fileSizeLimitBytes, encoding, buffered, hooks);
}
}
catch (Exception ex)
{
SelfLog.WriteLine("Unable to open file sink for {0}: {1}", path, ex);
if (propagateExceptions)
throw;
return addSink(new NullSink(), LevelAlias.Maximum, null);
}
}
if (flushToDiskInterval.HasValue)
{
#pragma warning disable 618
sink = new PeriodicFlushToDiskSink(sink, flushToDiskInterval.Value);
#pragma warning restore 618
}
return addSink(sink, restrictedToMinimumLevel, levelSwitch);
}
}
}
| 64.426877
| 224
| 0.669325
|
[
"Apache-2.0"
] |
chennssol/serilog-sinks-file
|
src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs
| 32,602
|
C#
|
/*
Copyright 2019 James Craig
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 Enlighten.NameFinder.Interfaces;
using Enlighten.Tokenizer;
using System.Collections.Generic;
using System.Linq;
namespace Enlighten.NameFinder
{
/// <summary>
/// Default name finder
/// </summary>
/// <seealso cref="IEntityFinder"/>
public class DefaultEntityFinder : IEntityFinder
{
/// <summary>
/// Initializes a new instance of the <see cref="DefaultEntityFinder"/> class.
/// </summary>
/// <param name="finders">The finders.</param>
public DefaultEntityFinder(IEnumerable<IFinder> finders)
{
Finders = finders.Where(x => x.GetType().Assembly != typeof(DefaultEntityFinder).Assembly).ToDictionary(x => x.Name);
foreach (var Finder in finders.Where(x => x.GetType().Assembly == typeof(DefaultEntityFinder).Assembly
&& !Finders.ContainsKey(x.Name)))
{
Finders.Add(Finder.Name, Finder);
}
}
/// <summary>
/// Gets the finders.
/// </summary>
/// <value>The finders.</value>
private Dictionary<string, IFinder> Finders { get; }
/// <summary>
/// Finds the entities in the specified document.
/// </summary>
/// <param name="tokens">The tokens.</param>
/// <param name="entityFinder">The entity finder.</param>
/// <returns>The document after it is processed.</returns>
public Token[] Find(Token[] tokens, string entityFinder)
{
if (!Finders.TryGetValue(entityFinder, out var Finder))
return tokens;
return Finder.Find(tokens);
}
}
}
| 35.238095
| 129
| 0.635586
|
[
"Apache-2.0"
] |
JaCraig/Enlighten
|
Enlighten/EntityFinder/DefaultEntityFinder.cs
| 2,222
|
C#
|
/*
* Copyright 2018 James Courtney
*
* 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.
*/
namespace FlatSharp.Attributes
{
using System;
using System.ComponentModel;
/// <summary>
/// Defines a member of a FlatBuffer struct or table.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FlatBufferItemAttribute : Attribute
{
/// <summary>
/// Initializes a new FlatBufferItemAttribute.
/// </summary>
/// <param name="index">The field index within the struct or table.</param>
public FlatBufferItemAttribute(ushort index)
{
this.Index = index;
}
/// <summary>
/// The index within the struct or table.
/// </summary>
public ushort Index { get; }
/// <summary>
/// For tables, indicates if this field is deprecated. Deprecated fields are not written or read.
/// </summary>
public bool Deprecated { get; set; }
/// <summary>
/// Indicates that the given vector property is to be serialized sorted by the key property of the vector type.
/// </summary>
public bool SortedVector { get; set; }
/// <summary>
/// Indicates that this field is the key for the table. Keys are used when sorting inside a vector. Only valid on a table.
/// </summary>
public bool Key { get; set; }
/// <summary>
/// For table items, gets or sets the default value. The type of the object must match the
/// type of the property.
/// </summary>
public object? DefaultValue { get; set; }
/// <summary>
/// When set, indicates that this item should always be written to tables,
/// even if it matches the default value. An exception is raised if this
/// is set in a context where Force-Writing is not allowed.
/// </summary>
public bool ForceWrite { get; set; }
/// <summary>
/// When set, indicates that this property is write-through to the underlying vector.
/// Only supported on scalars, structs, and enums in addition to vectors of those types.
/// </summary>
public bool WriteThrough { get; set; }
/// <summary>
/// When set, indicates that the field is required. Only applies to non-scalar fields on tables.
/// </summary>
public bool Required { get; set; }
/// <summary>
/// A C# expression that gets the value of the current property from the enclosing object.
/// This is a very advanced feature and is only intended to be used by the FlatSharp compiler.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The custom getter property is obsolete. Please use FlatBufferMetadataAttribute instead")]
public string? CustomGetter { get; set; }
}
}
| 38.6
| 130
| 0.631261
|
[
"Apache-2.0"
] |
StirlingLabs/FlatSharp
|
src/FlatSharp.Runtime/Attributes/FlatBufferItemAttribute.cs
| 3,476
|
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.Globalization;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.AspNetCore.Components.WebAssembly.Services;
namespace TestServer
{
public class PrerenderedStartup
{
public PrerenderedStartup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddServerSideBlazor();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddScoped<LazyAssemblyLoader>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var enUs = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = enUs;
CultureInfo.DefaultThreadCurrentUICulture = enUs;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Map("/prerendered", app =>
{
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapFallbackToPage("/PrerenderedHost");
endpoints.MapBlazorHub();
});
});
}
}
}
| 33.293103
| 106
| 0.616261
|
[
"Apache-2.0"
] |
a14907/AspNetCore
|
src/Components/test/testassets/TestServer/PrerenderedStartup.cs
| 1,931
|
C#
|
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you 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.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NJetty.Util.Util.Ajax
{
/// <summary>
/// TODO: Class/Interface Information here
/// </summary>
/// <author>
/// <a href="mailto:leopoldo.agdeppa@gmail.com">Leopoldo Lee Agdeppa III</a>
/// </author>
/// <date>
/// November 2008
/// </date>
public class ContinuationSupport
{
}
}
| 31.853659
| 85
| 0.68683
|
[
"Apache-2.0"
] |
chris2001jm/njetty
|
NJetty.Util/Util/Ajax/ContinuationSupport.cs
| 1,308
|
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.AzureNative.Network.V20200401
{
/// <summary>
/// ExpressRouteConnection resource.
/// </summary>
[AzureNativeResourceType("azure-native:network/v20200401:ExpressRouteConnection")]
public partial class ExpressRouteConnection : Pulumi.CustomResource
{
/// <summary>
/// Authorization key to establish the connection.
/// </summary>
[Output("authorizationKey")]
public Output<string?> AuthorizationKey { get; private set; } = null!;
/// <summary>
/// Enable internet security.
/// </summary>
[Output("enableInternetSecurity")]
public Output<bool?> EnableInternetSecurity { get; private set; } = null!;
/// <summary>
/// The ExpressRoute circuit peering.
/// </summary>
[Output("expressRouteCircuitPeering")]
public Output<Outputs.ExpressRouteCircuitPeeringIdResponse> ExpressRouteCircuitPeering { get; private set; } = null!;
/// <summary>
/// The name of the resource.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state of the express route connection resource.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// The Routing Configuration indicating the associated and propagated route tables on this connection.
/// </summary>
[Output("routingConfiguration")]
public Output<Outputs.RoutingConfigurationResponse?> RoutingConfiguration { get; private set; } = null!;
/// <summary>
/// The routing weight associated to the connection.
/// </summary>
[Output("routingWeight")]
public Output<int?> RoutingWeight { get; private set; } = null!;
/// <summary>
/// Create a ExpressRouteConnection resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ExpressRouteConnection(string name, ExpressRouteConnectionArgs args, CustomResourceOptions? options = null)
: base("azure-native:network/v20200401:ExpressRouteConnection", name, args ?? new ExpressRouteConnectionArgs(), MakeResourceOptions(options, ""))
{
}
private ExpressRouteConnection(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:network/v20200401:ExpressRouteConnection", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/latest:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/latest:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20180801:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20181001:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20181101:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20181201:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190201:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190401:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190601:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190701:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190801:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20190901:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20191101:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20191201:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200301:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200501:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200601:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200701:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-native:network/v20200801:ExpressRouteConnection"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:ExpressRouteConnection"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ExpressRouteConnection resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ExpressRouteConnection Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ExpressRouteConnection(name, id, options);
}
}
public sealed class ExpressRouteConnectionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Authorization key to establish the connection.
/// </summary>
[Input("authorizationKey")]
public Input<string>? AuthorizationKey { get; set; }
/// <summary>
/// The name of the connection subresource.
/// </summary>
[Input("connectionName")]
public Input<string>? ConnectionName { get; set; }
/// <summary>
/// Enable internet security.
/// </summary>
[Input("enableInternetSecurity")]
public Input<bool>? EnableInternetSecurity { get; set; }
/// <summary>
/// The ExpressRoute circuit peering.
/// </summary>
[Input("expressRouteCircuitPeering", required: true)]
public Input<Inputs.ExpressRouteCircuitPeeringIdArgs> ExpressRouteCircuitPeering { get; set; } = null!;
/// <summary>
/// The name of the ExpressRoute gateway.
/// </summary>
[Input("expressRouteGatewayName", required: true)]
public Input<string> ExpressRouteGatewayName { get; set; } = null!;
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// The name of the resource.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The Routing Configuration indicating the associated and propagated route tables on this connection.
/// </summary>
[Input("routingConfiguration")]
public Input<Inputs.RoutingConfigurationArgs>? RoutingConfiguration { get; set; }
/// <summary>
/// The routing weight associated to the connection.
/// </summary>
[Input("routingWeight")]
public Input<int>? RoutingWeight { get; set; }
public ExpressRouteConnectionArgs()
{
}
}
}
| 50.849057
| 157
| 0.623377
|
[
"Apache-2.0"
] |
pulumi-bot/pulumi-azure-native
|
sdk/dotnet/Network/V20200401/ExpressRouteConnection.cs
| 10,780
|
C#
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* 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 the OpenSimulator Project 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 DEVELOPERS ``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 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.ClientStack.LindenUDP;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.OptionalModules.UDP.Linden
{
/// <summary>
/// A module that just holds commands for inspecting the current state of the Linden UDP stack.
/// </summary>
/// <remarks>
/// All actual client stack functionality remains in OpenSim.Region.ClientStack.LindenUDP
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LindenUDPInfoModule")]
public class LindenUDPInfoModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
public string Name { get { return "Linden UDP Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource source)
{
// m_log.DebugFormat("[LINDEN UDP INFO MODULE]: INITIALIZED MODULE");
}
public void PostInitialise()
{
// m_log.DebugFormat("[LINDEN UDP INFO MODULE]: POST INITIALIZED MODULE");
}
public void Close()
{
// m_log.DebugFormat("[LINDEN UDP INFO MODULE]: CLOSED MODULE");
}
public void AddRegion(Scene scene)
{
// m_log.DebugFormat("[LINDEN UDP INFO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName);
lock (m_scenes)
m_scenes[scene.RegionInfo.RegionID] = scene;
scene.AddCommand(
"Comms", this, "show pqueues",
"show pqueues [full]",
"Show priority queue data for each client",
"Without the 'full' option, only root agents are shown."
+ " With the 'full' option child agents are also shown.",
(mod, cmd) => MainConsole.Instance.Output(GetPQueuesReport(cmd)));
scene.AddCommand(
"Comms", this, "show queues",
"show queues [full]",
"Show queue data for each client",
"Without the 'full' option, only root agents are shown.\n"
+ "With the 'full' option child agents are also shown.\n\n"
+ "Type - Rt is a root (avatar) client whilst cd is a child (neighbour interacting) client.\n"
+ "Since Last In - Time in milliseconds since last packet received.\n"
+ "Pkts In - Number of packets processed from the client.\n"
+ "Pkts Out - Number of packets sent to the client.\n"
+ "Pkts Resent - Number of packets resent to the client.\n"
+ "Bytes Unacked - Number of bytes transferred to the client that are awaiting acknowledgement.\n"
+ "Q Pkts * - Number of packets of various types (land, wind, etc.) to be sent to the client that are waiting for available bandwidth.\n",
(mod, cmd) => MainConsole.Instance.Output(GetQueuesReport(cmd)));
scene.AddCommand(
"Comms", this, "show image queues",
"show image queues <first-name> <last-name>",
"Show the image queues (textures downloaded via UDP) for a particular client.",
(mod, cmd) => MainConsole.Instance.Output(GetImageQueuesReport(cmd)));
scene.AddCommand(
"Comms", this, "clear image queues",
"clear image queues <first-name> <last-name>",
"Clear the image queues (textures downloaded via UDP) for a particular client.",
(mod, cmd) => MainConsole.Instance.Output(HandleImageQueuesClear(cmd)));
scene.AddCommand(
"Comms", this, "show throttles",
"show throttles [full]",
"Show throttle settings for each client and for the server overall",
"Without the 'full' option, only root agents are shown."
+ " With the 'full' option child agents are also shown.",
(mod, cmd) => MainConsole.Instance.Output(GetThrottlesReport(cmd)));
}
public void RemoveRegion(Scene scene)
{
// m_log.DebugFormat("[LINDEN UDP INFO MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
lock (m_scenes)
m_scenes.Remove(scene.RegionInfo.RegionID);
}
public void RegionLoaded(Scene scene)
{
// m_log.DebugFormat("[LINDEN UDP INFO MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName);
}
protected string HandleImageQueuesClear(string[] cmd)
{
if (cmd.Length != 5)
return "Usage: image queues clear <first-name> <last-name>";
string firstName = cmd[3];
string lastName = cmd[4];
List<ScenePresence> foundAgents = new List<ScenePresence>();
lock (m_scenes)
{
foreach (Scene scene in m_scenes.Values)
{
ScenePresence sp = scene.GetScenePresence(firstName, lastName);
if (sp != null)
foundAgents.Add(sp);
}
}
if (foundAgents.Count == 0)
return string.Format("No agents found for {0} {1}", firstName, lastName);
StringBuilder report = new StringBuilder();
foreach (ScenePresence agent in foundAgents)
{
LLClientView client = agent.ControllingClient as LLClientView;
if (client == null)
return "This command is only supported for LLClientView";
int requestsDeleted = client.ImageManager.ClearImageQueue();
report.AppendFormat(
"In region {0} ({1} agent) cleared {2} requests\n",
agent.Scene.RegionInfo.RegionName, agent.IsChildAgent ? "child" : "root", requestsDeleted);
}
return report.ToString();
}
protected string GetColumnEntry(string entry, int maxLength, int columnPadding)
{
return string.Format(
"{0,-" + maxLength + "}{1,-" + columnPadding + "}",
entry.Length > maxLength ? entry.Substring(0, maxLength) : entry,
"");
}
/// <summary>
/// Generate UDP Queue data report for each client
/// </summary>
/// <param name="showParams"></param>
/// <returns></returns>
protected string GetPQueuesReport(string[] showParams)
{
bool showChildren = false;
string pname = "";
if (showParams.Length > 2 && showParams[2] == "full")
showChildren = true;
else if (showParams.Length > 3)
pname = showParams[2] + " " + showParams[3];
StringBuilder report = new StringBuilder();
int columnPadding = 2;
int maxNameLength = 18;
int maxRegionNameLength = 14;
int maxTypeLength = 4;
// int totalInfoFieldsLength = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding;
report.Append(GetColumnEntry("User", maxNameLength, columnPadding));
report.Append(GetColumnEntry("Region", maxRegionNameLength, columnPadding));
report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding));
report.AppendFormat(
"{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7} {10,7} {11,7}\n",
"Pri 0",
"Pri 1",
"Pri 2",
"Pri 3",
"Pri 4",
"Pri 5",
"Pri 6",
"Pri 7",
"Pri 8",
"Pri 9",
"Pri 10",
"Pri 11");
lock (m_scenes)
{
foreach (Scene scene in m_scenes.Values)
{
scene.ForEachClient(
delegate(IClientAPI client)
{
if (client is LLClientView)
{
bool isChild = client.SceneAgent.IsChildAgent;
if (isChild && !showChildren)
return;
string name = client.Name;
if (pname != "" && name != pname)
return;
string regionName = scene.RegionInfo.RegionName;
report.Append(GetColumnEntry(name, maxNameLength, columnPadding));
report.Append(GetColumnEntry(regionName, maxRegionNameLength, columnPadding));
report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding));
report.AppendLine(((LLClientView)client).EntityUpdateQueue.ToString());
}
});
}
}
return report.ToString();
}
/// <summary>
/// Generate an image queue report
/// </summary>
/// <param name="showParams"></param>
/// <returns></returns>
private string GetImageQueuesReport(string[] showParams)
{
if (showParams.Length < 5 || showParams.Length > 6)
return "Usage: show image queues <first-name> <last-name> [full]";
string firstName = showParams[3];
string lastName = showParams[4];
bool showChildAgents = showParams.Length == 6;
List<ScenePresence> foundAgents = new List<ScenePresence>();
lock (m_scenes)
{
foreach (Scene scene in m_scenes.Values)
{
ScenePresence sp = scene.GetScenePresence(firstName, lastName);
if (sp != null && (showChildAgents || !sp.IsChildAgent))
foundAgents.Add(sp);
}
}
if (foundAgents.Count == 0)
return string.Format("No agents found for {0} {1}", firstName, lastName);
StringBuilder report = new StringBuilder();
foreach (ScenePresence agent in foundAgents)
{
LLClientView client = agent.ControllingClient as LLClientView;
if (client == null)
return "This command is only supported for LLClientView";
J2KImage[] images = client.ImageManager.GetImages();
report.AppendFormat(
"In region {0} ({1} agent)\n",
agent.Scene.RegionInfo.RegionName, agent.IsChildAgent ? "child" : "root");
report.AppendFormat("Images in queue: {0}\n", images.Length);
if (images.Length > 0)
{
report.AppendFormat(
"{0,-36} {1,-8} {2,-10} {3,-9} {4,-9} {5,-7}\n",
"Texture ID",
"Last Seq",
"Priority",
"Start Pkt",
"Has Asset",
"Decoded");
foreach (J2KImage image in images)
report.AppendFormat(
"{0,36} {1,8} {2,10} {3,10} {4,9} {5,7}\n",
image.TextureID, image.LastSequence, image.Priority, image.StartPacket, image.HasAsset, image.IsDecoded);
}
}
return report.ToString();
}
/// <summary>
/// Generate UDP Queue data report for each client
/// </summary>
/// <param name="showParams"></param>
/// <returns></returns>
protected string GetQueuesReport(string[] showParams)
{
bool showChildren = false;
string pname = "";
if (showParams.Length > 2 && showParams[2] == "full")
showChildren = true;
else if (showParams.Length > 3)
pname = showParams[2] + " " + showParams[3];
StringBuilder report = new StringBuilder();
int columnPadding = 2;
int maxNameLength = 18;
int maxRegionNameLength = 14;
int maxTypeLength = 4;
int totalInfoFieldsLength
= maxNameLength + columnPadding
+ maxRegionNameLength + columnPadding
+ maxTypeLength + columnPadding;
report.Append(GetColumnEntry("User", maxNameLength, columnPadding));
report.Append(GetColumnEntry("Region", maxRegionNameLength, columnPadding));
report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding));
report.AppendFormat(
"{0,7} {1,7} {2,7} {3,7} {4,9} {5,7} {6,7} {7,7} {8,7} {9,7} {10,8} {11,7}\n",
"Since",
"Pkts",
"Pkts",
"Pkts",
"Bytes",
"Q Pkts",
"Q Pkts",
"Q Pkts",
"Q Pkts",
"Q Pkts",
"Q Pkts",
"Q Pkts");
report.AppendFormat("{0,-" + totalInfoFieldsLength + "}", "");
report.AppendFormat(
"{0,7} {1,7} {2,7} {3,7} {4,9} {5,7} {6,7} {7,7} {8,7} {9,7} {10,8} {11,7}\n",
"Last In",
"In",
"Out",
"Resent",
"Unacked",
"Resend",
"Land",
"Wind",
"Cloud",
"Task",
"Texture",
"Asset");
lock (m_scenes)
{
foreach (Scene scene in m_scenes.Values)
{
scene.ForEachClient(
delegate(IClientAPI client)
{
if (client is IStatsCollector)
{
bool isChild = client.SceneAgent.IsChildAgent;
if (isChild && !showChildren)
return;
string name = client.Name;
if (pname != "" && name != pname)
return;
string regionName = scene.RegionInfo.RegionName;
report.Append(GetColumnEntry(name, maxNameLength, columnPadding));
report.Append(GetColumnEntry(regionName, maxRegionNameLength, columnPadding));
report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding));
IStatsCollector stats = (IStatsCollector)client;
report.AppendLine(stats.Report());
}
});
}
}
return report.ToString();
}
/// <summary>
/// Show throttle data
/// </summary>
/// <param name="showParams"></param>
/// <returns></returns>
protected string GetThrottlesReport(string[] showParams)
{
bool showChildren = false;
string pname = "";
if (showParams.Length > 2 && showParams[2] == "full")
showChildren = true;
else if (showParams.Length > 3)
pname = showParams[2] + " " + showParams[3];
StringBuilder report = new StringBuilder();
int columnPadding = 2;
int maxNameLength = 18;
int maxRegionNameLength = 14;
int maxTypeLength = 4;
int totalInfoFieldsLength = maxNameLength + columnPadding + maxRegionNameLength + columnPadding + maxTypeLength + columnPadding;
report.Append(GetColumnEntry("User", maxNameLength, columnPadding));
report.Append(GetColumnEntry("Region", maxRegionNameLength, columnPadding));
report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding));
report.AppendFormat(
"{0,8} {1,8} {2,7} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7}\n",
"Max",
"Target",
"Actual",
"Resend",
"Land",
"Wind",
"Cloud",
"Task",
"Texture",
"Asset");
report.AppendFormat("{0,-" + totalInfoFieldsLength + "}", "");
report.AppendFormat(
"{0,8} {1,8} {2,7} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7}\n",
"kb/s",
"kb/s",
"kb/s",
"kb/s",
"kb/s",
"kb/s",
"kb/s",
"kb/s",
"kb/s",
"kb/s");
report.AppendLine();
lock (m_scenes)
{
foreach (Scene scene in m_scenes.Values)
{
scene.ForEachClient(
delegate(IClientAPI client)
{
if (client is LLClientView)
{
LLClientView llClient = client as LLClientView;
bool isChild = client.SceneAgent.IsChildAgent;
if (isChild && !showChildren)
return;
string name = client.Name;
if (pname != "" && name != pname)
return;
string regionName = scene.RegionInfo.RegionName;
LLUDPClient llUdpClient = llClient.UDPClient;
ClientInfo ci = llUdpClient.GetClientInfo();
report.Append(GetColumnEntry(name, maxNameLength, columnPadding));
report.Append(GetColumnEntry(regionName, maxRegionNameLength, columnPadding));
report.Append(GetColumnEntry(isChild ? "Cd" : "Rt", maxTypeLength, columnPadding));
report.AppendFormat(
"{0,8} {1,8} {2,7} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7}\n",
ci.maxThrottle > 0 ? ((ci.maxThrottle * 8) / 1000).ToString() : "-",
llUdpClient.FlowThrottle.AdaptiveEnabled
? ((ci.targetThrottle * 8) / 1000).ToString()
: (llUdpClient.FlowThrottle.TotalDripRequest * 8 / 1000).ToString(),
(ci.totalThrottle * 8) / 1000,
(ci.resendThrottle * 8) / 1000,
(ci.landThrottle * 8) / 1000,
(ci.windThrottle * 8) / 1000,
(ci.cloudThrottle * 8) / 1000,
(ci.taskThrottle * 8) / 1000,
(ci.textureThrottle * 8) / 1000,
(ci.assetThrottle * 8) / 1000);
}
});
}
}
return report.ToString();
}
private void PrintRequests(string type, Dictionary<string, int> sortedDict, int sum)
{
m_log.InfoFormat("[INFO]:");
m_log.InfoFormat("[INFO]: {0,25}", type);
foreach (KeyValuePair<string, int> kvp in sortedDict.Take(12))
m_log.InfoFormat("[INFO]: {0,25} {1,-6}", kvp.Key, kvp.Value);
m_log.InfoFormat("[INFO]: {0,25}", "...");
m_log.InfoFormat("[INFO]: {0,25} {1,-6}", "Total", sum);
}
}
}
| 40.930275
| 163
| 0.499574
|
[
"BSD-3-Clause"
] |
AI-Grid/AI-Grid-2.0
|
OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs
| 22,307
|
C#
|
using System;
using System.Collections.Immutable;
using Newtonsoft.Json;
namespace Microsoft.DotNet.Maestro.Client.Models
{
public partial class ApiError
{
public ApiError()
{
}
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("errors")]
public IImmutableList<string> Errors { get; set; }
}
}
| 19.55
| 58
| 0.624041
|
[
"MIT"
] |
AlitzelMendez/arcade-services
|
src/Maestro/Client/src/Generated/Models/ApiError.cs
| 391
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AllReady.Areas.Admin.Models
{
public class TenantSummaryModel
{
public int Id { get; set; }
public string Name { get; set; }
public string LogoUrl { get; set; }
public string WebUrl { get; set; }
}
}
| 21.764706
| 44
| 0.621622
|
[
"MIT"
] |
JesseLiberty/allReady
|
AllReadyApp/Web-App/AllReady/Areas/Admin/Models/TenantSummaryModel.cs
| 372
|
C#
|
// Copyright 2018 by JCoder58. See License.txt for license
// Auto-generated --- Do not modify.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UE4.Core;
using UE4.CoreUObject;
using UE4.CoreUObject.Native;
using UE4.InputCore;
using UE4.Native;
namespace UE4.MovieSceneTools.Native {
[StructLayout( LayoutKind.Explicit, Size=232 )]
internal unsafe struct K2Node_GetSequenceBindings_fields {
[FieldOffset(208)] public NativeArray BindingGuids;
[FieldOffset(224)] public IntPtr Sequence;
}
internal unsafe struct K2Node_GetSequenceBindings_methods {
}
internal unsafe struct K2Node_GetSequenceBindings_events {
}
}
| 29.458333
| 63
| 0.759547
|
[
"MIT"
] |
UE4DotNet/Plugin
|
DotNet/DotNet/UE4/Generated/MovieSceneTools/Native/K2Node_GetSequenceBindings.cs
| 707
|
C#
|
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Machinelearning.V1
{
/// <summary>
/// The SELinux context to be applied to the container. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
/// </summary>
public class SeldonDeploymentSpecPredictorsComponentSpecsSpecEphemeralContainersSecurityContextSeLinuxOptionsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Level is SELinux level label that applies to the container.
/// </summary>
[Input("level")]
public Input<string>? Level { get; set; }
/// <summary>
/// Role is a SELinux role label that applies to the container.
/// </summary>
[Input("role")]
public Input<string>? Role { get; set; }
/// <summary>
/// Type is a SELinux type label that applies to the container.
/// </summary>
[Input("type")]
public Input<string>? Type { get; set; }
/// <summary>
/// User is a SELinux user label that applies to the container.
/// </summary>
[Input("user")]
public Input<string>? User { get; set; }
public SeldonDeploymentSpecPredictorsComponentSpecsSpecEphemeralContainersSecurityContextSeLinuxOptionsArgs()
{
}
}
}
| 37.297872
| 309
| 0.662864
|
[
"Apache-2.0"
] |
pulumi/pulumi-kubernetes-crds
|
operators/seldon-operator/dotnet/Kubernetes/Crds/Operators/SeldonOperator/Machinelearning/V1/Inputs/SeldonDeploymentSpecPredictorsComponentSpecsSpecEphemeralContainersSecurityContextSeLinuxOptionsArgs.cs
| 1,753
|
C#
|
using System;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Movies.Service
{
public partial class ApiResponse
{
[JsonProperty("resultCount")]
public long ResultCount { get; set; }
[JsonProperty("results")]
public MovieResult[] Results { get; set; }
public static ApiResponse FromJson(string json) => JsonConvert.DeserializeObject<ApiResponse>(json, Converter.Settings);
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
}
};
}
}
}
| 30.09375
| 128
| 0.628245
|
[
"MIT"
] |
AlejandroRuiz/MonkeyFestGdl2018
|
Completed/Movies.Service/ApiResponse.cs
| 965
|
C#
|
using Unity.Extension;
using Unity.Lifetime;
using Unity.Microsoft.DependencyInjection.Policy;
using Unity.Policy;
namespace Unity.Microsoft.DependencyInjection
{
internal class MdiExtension : UnityContainerExtension
{
protected override void Initialize()
{
Context.Policies.SetDefault<IConstructorSelectorPolicy>(new ConstructorSelectorPolicy());
}
public ILifetimeContainer Lifetime => Context.Lifetime;
}
}
| 26.055556
| 101
| 0.733475
|
[
"Apache-2.0"
] |
pksorensen/microsoft-dependency-injection
|
src/MDIExtension.cs
| 471
|
C#
|
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
namespace EasyTranslate
{
public class EasyTranslate
{
public static string env = null;
public static string loc = null;
private static bool hasInit = false;
private static Dictionary<string,string> locales = null;
private static string assDir = null;
private static Dictionary<string,string> current_translation = new Dictionary<string, string>();
static EasyTranslate()
{
assDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}
public bool Init(string environement, string locale = "EN_en")
{
env = environement;
loc = locale;
if(env != null && loc != null)
{
if (!Directory.Exists(assDir + "/" + env + "/"))
{
Directory.CreateDirectory(assDir + "/" + env + "/");
}
if (File.Exists(assDir + "/" + env + "/" + loc + "/translation.txt"))
{
current_translation = translationToDicitionary(File.ReadAllText(assDir + "/" + env + "/" + loc + "/translation.txt"));
}
hasInit = true;
}
return hasInit;
}
public bool setLocales(Dictionary<string,string> dict)
{
locales = dict;
if (locales != null) return true;
return false;
}
public bool SetupKeys(Dictionary<string, string> dict)
{
if (!hasInit || locales == null) return false;
foreach(var dict_locale in locales)
{
if (!Directory.Exists(assDir + "/" + env + "/" + dict_locale.Key + "_" + dict_locale.Value + "/"))
{
Directory.CreateDirectory(assDir + "/" + env + "/" + dict_locale.Key + "_" + dict_locale.Value + "/");
}
Dictionary<string,string> locale_translation = new Dictionary<string, string>();
if (File.Exists(assDir + "/" + env + "/" + dict_locale.Key + "_" + dict_locale.Value + "/translation.txt"))
{
locale_translation = translationToDicitionary(File.ReadAllText(assDir + "/" + env + "/" + dict_locale.Key + "_" + dict_locale.Value + "/translation.txt"));
}
foreach (var translation in dict)
{
if (locale_translation.ContainsKey(translation.Key)) continue;
locale_translation.Add(translation.Key,translation.Value);
}
File.WriteAllText(assDir + "/" + env + "/" + dict_locale.Key + "_" + dict_locale.Value + "/translation.txt", DictionaryToTranslation(locale_translation));
}
Init(env,loc);
return true;
}
public String getTranslation(string key, string defaultVal = "")
{
string out_val = defaultVal;
if (current_translation.TryGetValue(key, out out_val)) return out_val;
//todo get translation
return defaultVal;
}
private Dictionary<string, string> translationToDicitionary(string text)
{
Dictionary<string, string> temp_translation = new Dictionary<string, string>();
foreach (var val in text.Split(new string[] { Environment.NewLine + "=NL=" + Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
{
var pairs = val.Split(new string[] { "=/=" }, StringSplitOptions.None);
if(pairs[0] != null && pairs[1] != null) temp_translation.Add(pairs[0], pairs[1].Trim());
}
return temp_translation;
}
private string DictionaryToTranslation(Dictionary<string, string> dict)
{
string temp_translation = "";
foreach (var translation in dict)
{
temp_translation += (translation.Key + "=/=" + translation.Value + Environment.NewLine + "=NL=" + Environment.NewLine);
}
return temp_translation;
}
}
}
| 40.839623
| 176
| 0.529453
|
[
"Apache-2.0"
] |
MLIMG/Easy-Translate
|
EasyTranslate.cs
| 4,331
|
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.PatternMatching;
namespace ICSharpCode.NRefactory.CSharp {
public class QueryExpressionExpansionResult {
public AstNode AstNode { get; private set; }
/// <summary>
/// Maps original range variables to some node in the new tree that represents them.
/// </summary>
public IDictionary<Identifier, AstNode> RangeVariables { get; private set; }
/// <summary>
/// Maps clauses to method calls. The keys will always be either a <see cref="QueryClause"/> or a <see cref="QueryOrdering"/>
/// </summary>
public IDictionary<AstNode, Expression> Expressions { get; private set; }
public QueryExpressionExpansionResult(AstNode astNode, IDictionary<Identifier, AstNode> rangeVariables, IDictionary<AstNode, Expression> expressions) {
AstNode = astNode;
RangeVariables = rangeVariables;
Expressions = expressions;
}
}
public class QueryExpressionExpander {
class Visitor : DepthFirstAstVisitor<AstNode> {
int currentTransparentParameter;
const string TransparentParameterNameTemplate = "<>x{0}";
protected override AstNode VisitChildren(AstNode node) {
List<AstNode> newChildren = null;
int i = 0;
foreach (var child in node.Children) {
var newChild = child.AcceptVisitor(this);
if (newChild != null) {
newChildren = newChildren ?? Enumerable.Repeat((AstNode)null, i).ToList();
newChildren.Add(newChild);
}
else if (newChildren != null) {
newChildren.Add(null);
}
i++;
}
if (newChildren == null)
return null;
var result = node.Clone();
i = 0;
foreach (var children in result.Children) {
if (newChildren[i] != null)
children.ReplaceWith(newChildren[i]);
i++;
}
return result;
}
Expression MakeNestedMemberAccess(Expression target, IEnumerable<string> members) {
return members.Aggregate(target, (current, m) => current.Member(m));
}
Expression VisitNested(Expression node, ParameterDeclaration transparentParameter) {
var oldRangeVariableSubstitutions = activeRangeVariableSubstitutions;
try {
if (transparentParameter != null && currentTransparentType.Count > 1) {
activeRangeVariableSubstitutions = new Dictionary<string, Expression>(activeRangeVariableSubstitutions);
foreach (var t in currentTransparentType)
activeRangeVariableSubstitutions[t.Item1.Name] = MakeNestedMemberAccess(new IdentifierExpression(transparentParameter.Name), t.Item2);
}
var result = node.AcceptVisitor(this);
return (Expression)(result ?? node.Clone());
}
finally {
activeRangeVariableSubstitutions = oldRangeVariableSubstitutions;
}
}
QueryClause GetNextQueryClause(QueryClause clause) {
for (AstNode node = clause.NextSibling; node != null; node = node.NextSibling) {
if (node.Role == QueryExpression.ClauseRole)
return (QueryClause)node;
}
return null;
}
public IDictionary<Identifier, AstNode> rangeVariables = new Dictionary<Identifier, AstNode>();
public IDictionary<AstNode, Expression> expressions = new Dictionary<AstNode, Expression>();
Dictionary<string, Expression> activeRangeVariableSubstitutions = new Dictionary<string, Expression>();
List<Tuple<Identifier, List<string>>> currentTransparentType = new List<Tuple<Identifier, List<string>>>();
Expression currentResult;
bool eatSelect;
void MapExpression(AstNode orig, Expression newExpr) {
Debug.Assert(orig is QueryClause || orig is QueryOrdering);
expressions[orig] = newExpr;
}
ParameterDeclaration CreateParameterForCurrentRangeVariable() {
var param = new ParameterDeclaration();
if (currentTransparentType.Count == 1) {
var clonedRangeVariable = (Identifier)currentTransparentType[0].Item1.Clone();
if (!rangeVariables.ContainsKey(currentTransparentType[0].Item1))
rangeVariables[currentTransparentType[0].Item1] = param;
param.AddChild(clonedRangeVariable, Roles.Identifier);
}
else {
param.AddChild(Identifier.Create(string.Format(CultureInfo.InvariantCulture, TransparentParameterNameTemplate, currentTransparentParameter++)), Roles.Identifier);
}
return param;
}
LambdaExpression CreateLambda(IList<ParameterDeclaration> parameters, Expression body) {
var result = new LambdaExpression();
if (parameters.Count > 1)
result.AddChild(new CSharpTokenNode(TextLocation.Empty), Roles.LPar);
result.AddChild(parameters[0], Roles.Parameter);
for (int i = 1; i < parameters.Count; i++) {
result.AddChild(new CSharpTokenNode(TextLocation.Empty), Roles.Comma);
result.AddChild(parameters[i], Roles.Parameter);
}
if (parameters.Count > 1)
result.AddChild(new CSharpTokenNode(TextLocation.Empty), Roles.RPar);
result.AddChild(body, LambdaExpression.BodyRole);
return result;
}
ParameterDeclaration CreateParameter(Identifier identifier) {
var result = new ParameterDeclaration();
result.AddChild(identifier, Roles.Identifier);
return result;
}
Expression AddMemberToCurrentTransparentType(ParameterDeclaration param, Identifier name, Expression value, bool namedExpression) {
Expression newAssignment = VisitNested(value, param);
if (namedExpression) {
newAssignment = new NamedExpression(name.Name, VisitNested(value, param));
if (!rangeVariables.ContainsKey(name) )
rangeVariables[name] = ((NamedExpression)newAssignment).NameToken;
}
foreach (var t in currentTransparentType)
t.Item2.Insert(0, param.Name);
currentTransparentType.Add(Tuple.Create(name, new List<string> { name.Name }));
return new AnonymousTypeCreateExpression(new[] { new IdentifierExpression(param.Name), newAssignment });
}
void AddFirstMemberToCurrentTransparentType(Identifier identifier) {
Debug.Assert(currentTransparentType.Count == 0);
currentTransparentType.Add(Tuple.Create(identifier, new List<string>()));
}
public override AstNode VisitQueryExpression(QueryExpression queryExpression) {
var oldTransparentType = currentTransparentType;
var oldResult = currentResult;
var oldEatSelect = eatSelect;
try {
currentTransparentType = new List<Tuple<Identifier, List<string>>>();
currentResult = null;
eatSelect = false;
foreach (var clause in queryExpression.Clauses) {
var result = (Expression)clause.AcceptVisitor(this);
MapExpression(clause, result ?? currentResult);
currentResult = result;
}
return currentResult;
}
finally {
currentTransparentType = oldTransparentType;
currentResult = oldResult;
eatSelect = oldEatSelect;
}
}
public override AstNode VisitQueryContinuationClause(QueryContinuationClause queryContinuationClause) {
var prev = VisitNested(queryContinuationClause.PrecedingQuery, null);
AddFirstMemberToCurrentTransparentType(queryContinuationClause.IdentifierToken);
return prev;
}
public override AstNode VisitQueryFromClause(QueryFromClause queryFromClause) {
if (currentResult == null) {
AddFirstMemberToCurrentTransparentType(queryFromClause.IdentifierToken);
if (queryFromClause.Type.IsNull) {
return VisitNested(queryFromClause.Expression, null);
}
else {
return VisitNested(queryFromClause.Expression, null).Invoke("Cast", new[] { queryFromClause.Type.Clone() }, new Expression[0]);
}
}
else {
var innerSelectorParam = CreateParameterForCurrentRangeVariable();
var innerSelector = CreateLambda(new[] { innerSelectorParam }, VisitNested(queryFromClause.Expression, innerSelectorParam));
var clonedIdentifier = (Identifier)queryFromClause.IdentifierToken.Clone();
var resultParam = CreateParameterForCurrentRangeVariable();
Expression body;
// Second from clause - SelectMany
var select = GetNextQueryClause(queryFromClause) as QuerySelectClause;
if (select != null) {
body = VisitNested(select.Expression, resultParam);
eatSelect = true;
}
else {
body = AddMemberToCurrentTransparentType(resultParam, queryFromClause.IdentifierToken, new IdentifierExpression(queryFromClause.Identifier), false);
}
var resultSelectorParam2 = CreateParameter(clonedIdentifier);
var resultSelector = CreateLambda(new[] { resultParam, resultSelectorParam2 }, body);
rangeVariables[queryFromClause.IdentifierToken] = resultSelectorParam2;
return currentResult.Invoke("SelectMany", innerSelector, resultSelector);
}
}
public override AstNode VisitQueryLetClause(QueryLetClause queryLetClause) {
var param = CreateParameterForCurrentRangeVariable();
var body = AddMemberToCurrentTransparentType(param, queryLetClause.IdentifierToken, queryLetClause.Expression, true);
var lambda = CreateLambda(new[] { param }, body);
return currentResult.Invoke("Select", lambda);
}
public override AstNode VisitQueryWhereClause(QueryWhereClause queryWhereClause) {
var param = CreateParameterForCurrentRangeVariable();
return currentResult.Invoke("Where", CreateLambda(new[] { param }, VisitNested(queryWhereClause.Condition, param)));
}
public override AstNode VisitQueryJoinClause(QueryJoinClause queryJoinClause) {
Expression resultSelectorBody = null;
var inExpression = VisitNested(queryJoinClause.InExpression, null);
var key1SelectorFirstParam = CreateParameterForCurrentRangeVariable();
var key1Selector = CreateLambda(new[] { key1SelectorFirstParam }, VisitNested(queryJoinClause.OnExpression, key1SelectorFirstParam));
var key2Param = CreateParameter(Identifier.Create(queryJoinClause.JoinIdentifier));
var key2Selector = CreateLambda(new[] { key2Param }, VisitNested(queryJoinClause.EqualsExpression, null));
var resultSelectorFirstParam = CreateParameterForCurrentRangeVariable();
var select = GetNextQueryClause(queryJoinClause) as QuerySelectClause;
if (select != null) {
resultSelectorBody = VisitNested(select.Expression, resultSelectorFirstParam);
eatSelect = true;
}
if (queryJoinClause.IntoKeyword.IsNull) {
// Normal join
if (resultSelectorBody == null)
resultSelectorBody = AddMemberToCurrentTransparentType(resultSelectorFirstParam, queryJoinClause.JoinIdentifierToken, new IdentifierExpression(queryJoinClause.JoinIdentifier), false);
var resultSelector = CreateLambda(new[] { resultSelectorFirstParam, CreateParameter(Identifier.Create(queryJoinClause.JoinIdentifier)) }, resultSelectorBody);
rangeVariables[queryJoinClause.JoinIdentifierToken] = key2Param;
return currentResult.Invoke("Join", inExpression, key1Selector, key2Selector, resultSelector);
}
else {
// Group join
if (resultSelectorBody == null)
resultSelectorBody = AddMemberToCurrentTransparentType(resultSelectorFirstParam, queryJoinClause.IntoIdentifierToken, new IdentifierExpression(queryJoinClause.IntoIdentifier), false);
var intoParam = CreateParameter(Identifier.Create(queryJoinClause.IntoIdentifier));
var resultSelector = CreateLambda(new[] { resultSelectorFirstParam, intoParam }, resultSelectorBody);
rangeVariables[queryJoinClause.IntoIdentifierToken] = intoParam;
return currentResult.Invoke("GroupJoin", inExpression, key1Selector, key2Selector, resultSelector);
}
}
public override AstNode VisitQueryOrderClause(QueryOrderClause queryOrderClause) {
var current = currentResult;
bool first = true;
foreach (var o in queryOrderClause.Orderings) {
string methodName = first ? (o.Direction == QueryOrderingDirection.Descending ? "OrderByDescending" : "OrderBy")
: (o.Direction == QueryOrderingDirection.Descending ? "ThenByDescending" : "ThenBy");
var param = CreateParameterForCurrentRangeVariable();
current = current.Invoke(methodName, CreateLambda(new[] { param }, VisitNested(o.Expression, param)));
MapExpression(o, current);
first = false;
}
return current;
}
bool IsSingleRangeVariable(Expression expr) {
if (currentTransparentType.Count > 1)
return false;
var unpacked = ParenthesizedExpression.UnpackParenthesizedExpression(expr);
return unpacked is IdentifierExpression && ((IdentifierExpression)unpacked).Identifier == currentTransparentType[0].Item1.Name;
}
public override AstNode VisitQuerySelectClause(QuerySelectClause querySelectClause) {
if (eatSelect) {
eatSelect = false;
return currentResult;
}
else if (((QueryExpression)querySelectClause.Parent).Clauses.Count > 2 && IsSingleRangeVariable(querySelectClause.Expression)) {
// A simple query that ends with a trivial select should be removed.
return currentResult;
}
var param = CreateParameterForCurrentRangeVariable();
var lambda = CreateLambda(new[] { param }, VisitNested(querySelectClause.Expression, param));
return currentResult.Invoke("Select", lambda);
}
public override AstNode VisitQueryGroupClause(QueryGroupClause queryGroupClause) {
var param = CreateParameterForCurrentRangeVariable();
var keyLambda = CreateLambda(new[] { param }, VisitNested(queryGroupClause.Key, param));
if (IsSingleRangeVariable(queryGroupClause.Projection)) {
// We are grouping by the single active range variable, so we can use the single argument form of GroupBy
return currentResult.Invoke("GroupBy", keyLambda);
}
else {
var projectionParam = CreateParameterForCurrentRangeVariable();
var projectionLambda = CreateLambda(new[] { projectionParam }, VisitNested(queryGroupClause.Projection, projectionParam));
return currentResult.Invoke("GroupBy", keyLambda, projectionLambda);
}
}
public override AstNode VisitIdentifierExpression(IdentifierExpression identifierExpression) {
Expression subst;
activeRangeVariableSubstitutions.TryGetValue(identifierExpression.Identifier, out subst);
return subst != null ? subst.Clone() : null;
}
}
/// <summary>
/// Expands all occurances of query patterns in the specified node. Returns a clone of the node with all query patterns expanded, or null if there was no query pattern to expand.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public QueryExpressionExpansionResult ExpandQueryExpressions(AstNode node) {
var visitor = new Visitor();
var astNode = node.AcceptVisitor(visitor);
if (astNode != null) {
astNode.Freeze();
return new QueryExpressionExpansionResult(astNode, visitor.rangeVariables, visitor.expressions);
}
else {
return null;
}
}
}
}
| 42.396648
| 190
| 0.722361
|
[
"MIT"
] |
GreenDamTan/simple-assembly-exploror
|
ILSpy/NRefactory/ICSharpCode.NRefactory.CSharp/QueryExpressionExpander.cs
| 15,180
|
C#
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NUnit.Framework;
using UnityEngine.TestTools;
namespace UnityEngine.XR.Interaction.Toolkit.Tests
{
[TestFixture]
class InteractionManagerTests
{
[TearDown]
public void TearDown()
{
TestUtilities.DestroyAllSceneObjects();
}
[Test]
public void InteractorRegisteredOnEnable()
{
var manager = TestUtilities.CreateInteractionManager();
XRBaseInteractor registeredInteractor = null;
manager.interactorRegistered += args => registeredInteractor = args.interactor;
var interactor = TestUtilities.CreateDirectInteractor();
var interactors = new List<XRBaseInteractor>();
manager.GetRegisteredInteractors(interactors);
Assert.That(interactors, Is.EqualTo(new[] { interactor }));
Assert.That(registeredInteractor, Is.SameAs(interactor));
Assert.That(manager.IsRegistered(interactor), Is.True);
}
[Test]
public void InteractorUnregisteredOnDisable()
{
var manager = TestUtilities.CreateInteractionManager();
XRBaseInteractor unregisteredInteractor = null;
manager.interactorUnregistered += args => unregisteredInteractor = args.interactor;
var interactor = TestUtilities.CreateDirectInteractor();
interactor.enabled = false;
var interactors = new List<XRBaseInteractor>();
manager.GetRegisteredInteractors(interactors);
Assert.That(interactors, Is.Empty);
Assert.That(unregisteredInteractor, Is.SameAs(interactor));
Assert.That(manager.IsRegistered(interactor), Is.False);
}
[Test]
public void InteractorRegistrationEventsInvoked()
{
var manager = TestUtilities.CreateInteractionManager();
var interactor = TestUtilities.CreateDirectInteractor();
XRBaseInteractor registeredInteractor = null;
XRBaseInteractor unregisteredInteractor = null;
interactor.registered += args => registeredInteractor = args.interactor;
interactor.unregistered += args => unregisteredInteractor = args.interactor;
interactor.enabled = false;
var interactors = new List<XRBaseInteractor>();
manager.GetRegisteredInteractors(interactors);
Assert.That(interactors, Is.Empty);
Assert.That(unregisteredInteractor, Is.SameAs(interactor));
interactor.enabled = true;
manager.GetRegisteredInteractors(interactors);
Assert.That(interactors, Is.EqualTo(new[] { interactor }));
Assert.That(registeredInteractor, Is.SameAs(interactor));
}
[Test]
public void InteractableRegisteredOnEnable()
{
var manager = TestUtilities.CreateInteractionManager();
XRBaseInteractable registeredInteractable = null;
manager.interactableRegistered += args => registeredInteractable = args.interactable;
var interactable = TestUtilities.CreateGrabInteractable();
var interactables = new List<XRBaseInteractable>();
manager.GetRegisteredInteractables(interactables);
Assert.That(interactables, Is.EqualTo(new[] { interactable }));
Assert.That(registeredInteractable, Is.SameAs(interactable));
Assert.That(manager.IsRegistered(interactable), Is.True);
}
[Test]
public void InteractableUnregisteredOnDisable()
{
var manager = TestUtilities.CreateInteractionManager();
XRBaseInteractable unregisteredInteractable = null;
manager.interactableUnregistered += args => unregisteredInteractable = args.interactable;
var interactable = TestUtilities.CreateGrabInteractable();
interactable.enabled = false;
var interactables = new List<XRBaseInteractable>();
manager.GetRegisteredInteractables(interactables);
Assert.That(interactables, Is.Empty);
Assert.That(unregisteredInteractable, Is.SameAs(interactable));
Assert.That(manager.IsRegistered(interactable), Is.False);
}
[Test]
public void InteractableRegistrationEventsInvoked()
{
var manager = TestUtilities.CreateInteractionManager();
var interactable = TestUtilities.CreateGrabInteractable();
XRBaseInteractable registeredInteractable = null;
XRBaseInteractable unregisteredInteractable = null;
interactable.registered += args => registeredInteractable = args.interactable;
interactable.unregistered += args => unregisteredInteractable = args.interactable;
interactable.enabled = false;
var interactables = new List<XRBaseInteractable>();
manager.GetRegisteredInteractables(interactables);
Assert.That(interactables, Is.Empty);
Assert.That(unregisteredInteractable, Is.SameAs(interactable));
interactable.enabled = true;
manager.GetRegisteredInteractables(interactables);
Assert.That(interactables, Is.EqualTo(new[] { interactable }));
Assert.That(registeredInteractable, Is.SameAs(interactable));
}
[Test]
public void InteractableRegisteredOnEnableWithColliders()
{
var manager = TestUtilities.CreateInteractionManager();
var interactable = TestUtilities.CreateGrabInteractable();
var interactables = new List<XRBaseInteractable>();
manager.GetRegisteredInteractables(interactables);
Assert.That(interactables, Is.EqualTo(new[] { interactable }));
Assert.That(interactable.colliders, Has.Count.EqualTo(1));
Assert.That(manager.GetInteractableForCollider(interactable.colliders.First()), Is.EqualTo(interactable));
}
[Test]
public void InteractableUnregistersAssociatedColliders()
{
var manager = TestUtilities.CreateInteractionManager();
var firstInteractable = TestUtilities.CreateGrabInteractable();
var secondInteractable = TestUtilities.CreateGrabInteractable();
manager.UnregisterInteractable(firstInteractable);
manager.UnregisterInteractable(secondInteractable);
// Setup so the first Interactable has both colliders, and the second Interactable has a conflicting reference
secondInteractable.transform.SetParent(firstInteractable.transform);
firstInteractable.colliders.Clear();
firstInteractable.colliders.AddRange(firstInteractable.GetComponentsInChildren<Collider>());
secondInteractable.colliders.Clear();
secondInteractable.colliders.AddRange(secondInteractable.GetComponentsInChildren<Collider>());
Assert.That(firstInteractable.colliders, Has.Count.EqualTo(2));
Assert.That(secondInteractable.colliders, Has.Count.EqualTo(1));
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[0]), Is.Null);
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[1]), Is.Null);
manager.RegisterInteractable(firstInteractable);
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[0]), Is.SameAs(firstInteractable));
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[1]), Is.SameAs(firstInteractable));
LogAssert.Expect(LogType.Warning, new Regex("A Collider used by an Interactable object is already registered with another Interactable object*"));
manager.RegisterInteractable(secondInteractable);
// Interactables registered afterward do not replace the existing Collider association
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[0]), Is.SameAs(firstInteractable));
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[1]), Is.SameAs(firstInteractable));
manager.UnregisterInteractable(secondInteractable);
// Interactables registered afterward should not cause the registered Collider association to be removed
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[0]), Is.SameAs(firstInteractable));
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[1]), Is.SameAs(firstInteractable));
manager.UnregisterInteractable(firstInteractable);
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[0]), Is.Null);
Assert.That(manager.GetInteractableForCollider(firstInteractable.colliders[1]), Is.Null);
}
// Tests that Interactors and Interactables can register or unregister
// while the Interaction Manager is iterating over the list of Interactors to process events in Update.
[UnityTest]
public IEnumerator ObjectsCanRegisterDuringEvents()
{
var manager = TestUtilities.CreateInteractionManager();
var interactor = TestUtilities.CreateRayInteractor();
var interactable = TestUtilities.CreateSimpleInteractable();
interactable.transform.position = interactor.transform.position + interactor.transform.forward * 5f;
var otherInteractor = TestUtilities.CreateDirectInteractor();
var otherInteractable = TestUtilities.CreateSimpleInteractable();
otherInteractor.enabled = false;
otherInteractable.enabled = false;
// Don't let them get in the way, both are only used to test registration
otherInteractor.interactionLayerMask = 0;
otherInteractable.interactionLayerMask = 0;
// Upon Select, enable the other Interactor to have it register with the Interaction Manager during the update loop.
// Upon Deselect, disable the other Interactor to have it unregister from the Interaction Manager during the update loop.
interactor.selectEntered.AddListener(args =>
{
otherInteractor.enabled = true;
otherInteractable.enabled = true;
});
interactor.selectExited.AddListener(args =>
{
otherInteractor.enabled = false;
otherInteractable.enabled = false;
});
// Prepare controller state which will be used to cause a Select during the Interaction Manager update loop
var controller = interactor.GetComponent<XRBaseController>();
var controllerState = new XRControllerState(0f, Vector3.zero, Quaternion.identity, false, false, false);
controller.SetControllerState(controllerState);
var interactors = new List<XRBaseInteractor>();
var interactables = new List<XRBaseInteractable>();
manager.GetRegisteredInteractors(interactors);
manager.GetRegisteredInteractables(interactables);
Assert.That(interactors, Is.EqualTo(new[] { interactor }));
Assert.That(interactables, Is.EqualTo(new[] { interactable }));
// Wait for Physics update to ensure the Interactable can be detected by the Interactor
yield return new WaitForFixedUpdate();
yield return null;
Assert.That(interactable.isHovered, Is.True);
Assert.That(interactable.isSelected, Is.False);
// Press Grip
controllerState.selectInteractionState = new InteractionState { active = true, activatedThisFrame = true };
yield return null;
Assert.That(interactable.isHovered, Is.True);
Assert.That(interactable.isSelected, Is.True);
manager.GetRegisteredInteractors(interactors);
manager.GetRegisteredInteractables(interactables);
Assert.That(interactors, Is.EqualTo(new XRBaseInteractor[] { interactor, otherInteractor }));
Assert.That(interactables, Is.EqualTo(new XRBaseInteractable[] { interactable, otherInteractable }));
// Release Grip
controllerState.selectInteractionState = new InteractionState { active = false, deactivatedThisFrame = true };
yield return null;
Assert.That(interactable.isHovered, Is.True);
Assert.That(interactable.isSelected, Is.False);
manager.GetRegisteredInteractors(interactors);
manager.GetRegisteredInteractables(interactables);
Assert.That(interactors, Is.EqualTo(new[] { interactor }));
Assert.That(interactables, Is.EqualTo(new[] { interactable }));
}
// Tests that Interactors and Interactables can register or unregister
// while the Interaction Manager is iterating over the list of Interactors to process in ProcessInteractors.
[UnityTest]
public IEnumerator ObjectsCanRegisterDuringProcessInteractors()
{
var manager = TestUtilities.CreateInteractionManager();
var interactor = EnablerInteractor.CreateInteractor();
var otherInteractor = TestUtilities.CreateDirectInteractor();
var otherInteractable = TestUtilities.CreateSimpleInteractable();
otherInteractor.enabled = false;
otherInteractable.enabled = false;
// Don't let them get in the way, both are only used to test registration
otherInteractor.interactionLayerMask = 0;
otherInteractable.interactionLayerMask = 0;
interactor.interactor = otherInteractor;
interactor.interactable = otherInteractable;
yield return null;
var interactors = new List<XRBaseInteractor>();
var interactables = new List<XRBaseInteractable>();
manager.GetRegisteredInteractors(interactors);
manager.GetRegisteredInteractables(interactables);
Assert.That(interactors, Is.EqualTo(new[] { interactor }));
Assert.That(interactables, Is.Empty);
interactor.enableBehaviors = true;
yield return null;
manager.GetRegisteredInteractors(interactors);
manager.GetRegisteredInteractables(interactables);
Assert.That(interactors, Is.EqualTo(new XRBaseInteractor[] { interactor, otherInteractor }));
Assert.That(interactables, Is.EqualTo(new XRBaseInteractable[] { otherInteractable }));
interactor.enableBehaviors = false;
yield return null;
manager.GetRegisteredInteractors(interactors);
manager.GetRegisteredInteractables(interactables);
Assert.That(interactors, Is.EqualTo(new[] { interactor }));
Assert.That(interactables, Is.Empty);
}
// Tests that Interactors and Interactables can register or unregister
// while the Interaction Manager is iterating over the list of Interactables to process in ProcessInteractables.
[UnityTest]
public IEnumerator ObjectsCanRegisterDuringProcessInteractables()
{
var manager = TestUtilities.CreateInteractionManager();
var interactable = EnablerInteractable.CreateInteractable();
var otherInteractor = TestUtilities.CreateDirectInteractor();
var otherInteractable = TestUtilities.CreateSimpleInteractable();
otherInteractor.enabled = false;
otherInteractable.enabled = false;
// Don't let them get in the way, both are only used to test registration
otherInteractor.interactionLayerMask = 0;
otherInteractable.interactionLayerMask = 0;
interactable.interactor = otherInteractor;
interactable.interactable = otherInteractable;
yield return null;
var interactors = new List<XRBaseInteractor>();
var interactables = new List<XRBaseInteractable>();
manager.GetRegisteredInteractors(interactors);
manager.GetRegisteredInteractables(interactables);
Assert.That(interactors, Is.Empty);
Assert.That(interactables, Is.EqualTo(new[] { interactable }));
interactable.enableBehaviors = true;
yield return null;
manager.GetRegisteredInteractors(interactors);
manager.GetRegisteredInteractables(interactables);
Assert.That(interactors, Is.EqualTo(new XRBaseInteractor[] { otherInteractor }));
Assert.That(interactables, Is.EqualTo(new XRBaseInteractable[] { interactable, otherInteractable }));
interactable.enableBehaviors = false;
yield return null;
manager.GetRegisteredInteractors(interactors);
manager.GetRegisteredInteractables(interactables);
Assert.That(interactors, Is.Empty);
Assert.That(interactables, Is.EqualTo(new[] { interactable }));
}
[UnityTest]
public IEnumerator InteractorRegistrationEventsOccurSameFrame()
{
TestUtilities.CreateInteractionManager();
var interactor = TestUtilities.CreateDirectInteractor();
interactor.enabled = false;
var numRegistered = 0;
var numUnregistered = 0;
interactor.registered += args =>
{
++numRegistered;
};
interactor.unregistered += args =>
{
++numUnregistered;
};
interactor.enabled = true;
Assert.That(numRegistered, Is.EqualTo(1));
Assert.That(numUnregistered, Is.EqualTo(0));
interactor.enabled = false;
Assert.That(numRegistered, Is.EqualTo(1));
Assert.That(numUnregistered, Is.EqualTo(1));
interactor.enabled = true;
Assert.That(numRegistered, Is.EqualTo(2));
Assert.That(numUnregistered, Is.EqualTo(1));
yield return null;
Assert.That(numRegistered, Is.EqualTo(2));
Assert.That(numUnregistered, Is.EqualTo(1));
}
[UnityTest]
public IEnumerator InteractableRegistrationEventsOccurSameFrame()
{
TestUtilities.CreateInteractionManager();
var interactable = TestUtilities.CreateSimpleInteractable();
interactable.enabled = false;
var numRegistered = 0;
var numUnregistered = 0;
interactable.registered += args =>
{
++numRegistered;
};
interactable.unregistered += args =>
{
++numUnregistered;
};
interactable.enabled = true;
Assert.That(numRegistered, Is.EqualTo(1));
Assert.That(numUnregistered, Is.EqualTo(0));
interactable.enabled = false;
Assert.That(numRegistered, Is.EqualTo(1));
Assert.That(numUnregistered, Is.EqualTo(1));
interactable.enabled = true;
Assert.That(numRegistered, Is.EqualTo(2));
Assert.That(numUnregistered, Is.EqualTo(1));
yield return null;
Assert.That(numRegistered, Is.EqualTo(2));
Assert.That(numUnregistered, Is.EqualTo(1));
}
[UnityTest]
public IEnumerator InteractorCanDestroy()
{
var manager = TestUtilities.CreateInteractionManager();
var interactor = TestUtilities.CreateDirectInteractor();
Object.Destroy(interactor);
yield return null;
var interactors = new List<XRBaseInteractor>();
manager.GetRegisteredInteractors(interactors);
Assert.That(interactors, Is.Empty);
Assert.That(manager.IsRegistered(interactor), Is.False);
}
[UnityTest]
public IEnumerator InteractableCanDestroy()
{
var manager = TestUtilities.CreateInteractionManager();
var interactable = TestUtilities.CreateGrabInteractable();
Object.Destroy(interactable);
yield return null;
var interactables = new List<XRBaseInteractable>();
manager.GetRegisteredInteractables(interactables);
Assert.That(interactables, Is.Empty);
Assert.That(manager.IsRegistered(interactable), Is.False);
}
[UnityTest]
public IEnumerator InteractionManagersInteractWithCorrectObjects()
{
var managerA = TestUtilities.CreateInteractionManager();
var interactorA = TestUtilities.CreateDirectInteractor();
interactorA.interactionManager = managerA;
var interactableA = TestUtilities.CreateGrabInteractable();
interactableA.interactionManager = managerA;
var managerB = TestUtilities.CreateInteractionManager();
var interactorB = TestUtilities.CreateDirectInteractor();
interactorB.interactionManager = managerB;
var interactableB = TestUtilities.CreateGrabInteractable();
interactableB.interactionManager = managerB;
yield return new WaitForSeconds(0.1f);
var validTargets = new List<XRBaseInteractable>();
managerA.GetValidTargets(interactorA, validTargets);
Assert.That(validTargets, Has.Exactly(1).EqualTo(interactableA));
managerB.GetValidTargets(interactorA, validTargets);
Assert.That(validTargets, Is.Empty);
var hoverTargetList = new List<XRBaseInteractable>();
interactorA.GetHoverTargets(hoverTargetList);
Assert.That(hoverTargetList, Has.Exactly(1).EqualTo(interactableA));
interactorB.GetHoverTargets(hoverTargetList);
Assert.That(hoverTargetList, Has.Exactly(1).EqualTo(interactableB));
}
[Test]
public void RegistrationListRegisterReturnsStatusChange()
{
var registrationList = new XRInteractionManager.RegistrationList<string>();
Assert.That(registrationList.Register("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.True);
Assert.That(registrationList.Register("A"), Is.False);
Assert.That(registrationList.IsRegistered("A"), Is.True);
Assert.That(registrationList.Unregister("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.False);
Assert.That(registrationList.Register("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.True);
registrationList.Flush();
Assert.That(registrationList.Unregister("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.False);
Assert.That(registrationList.Register("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.True);
registrationList.Flush();
Assert.That(registrationList.Register("A"), Is.False);
Assert.That(registrationList.IsRegistered("A"), Is.True);
}
[Test]
public void RegistrationListUnregisterReturnsStatusChange()
{
var registrationList = new XRInteractionManager.RegistrationList<string>();
Assert.That(registrationList.Unregister("A"), Is.False);
Assert.That(registrationList.IsRegistered("A"), Is.False);
Assert.That(registrationList.Register("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.True);
Assert.That(registrationList.Unregister("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.False);
registrationList.Flush();
Assert.That(registrationList.IsRegistered("A"), Is.False);
Assert.That(registrationList.Unregister("A"), Is.False);
Assert.That(registrationList.Register("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.True);
registrationList.Flush();
Assert.That(registrationList.IsRegistered("A"), Is.True);
Assert.That(registrationList.Unregister("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.False);
Assert.That(registrationList.Register("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.True);
Assert.That(registrationList.Unregister("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.False);
registrationList.Flush();
Assert.That(registrationList.IsRegistered("A"), Is.False);
}
[Test]
public void RegistrationListSnapshotUnaffectedUntilFlush()
{
var registrationList = new XRInteractionManager.RegistrationList<string>();
Assert.That(registrationList.Register("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.True);
Assert.That(registrationList.registeredSnapshot, Is.Empty);
registrationList.Flush();
Assert.That(registrationList.IsRegistered("A"), Is.True);
Assert.That(registrationList.registeredSnapshot, Is.EqualTo(new[] { "A" }));
Assert.That(registrationList.Unregister("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.False);
Assert.That(registrationList.Register("B"), Is.True);
Assert.That(registrationList.IsRegistered("B"), Is.True);
Assert.That(registrationList.registeredSnapshot, Is.EqualTo(new[] { "A" }));
registrationList.Flush();
Assert.That(registrationList.IsRegistered("A"), Is.False);
Assert.That(registrationList.IsRegistered("B"), Is.True);
Assert.That(registrationList.registeredSnapshot, Is.EqualTo(new[] { "B" }));
}
[Test]
public void RegistrationListGetRegisteredItemsIncludesAll()
{
var registrationList = new XRInteractionManager.RegistrationList<string>();
var registeredItems = new List<string>();
registrationList.GetRegisteredItems(registeredItems);
Assert.That(registeredItems, Is.Empty);
// Should include pending adds
Assert.That(registrationList.Register("A"), Is.True);
registrationList.GetRegisteredItems(registeredItems);
Assert.That(registeredItems, Is.EqualTo(new[] { "A" }));
registrationList.Flush();
// Should still be equal after flush
registrationList.GetRegisteredItems(registeredItems);
Assert.That(registeredItems, Is.EqualTo(new[] { "A" }));
// Should include all in the order they were registered
Assert.That(registrationList.Register("B"), Is.True);
registrationList.GetRegisteredItems(registeredItems);
Assert.That(registeredItems, Is.EqualTo(new[] { "A", "B" }));
// Should filter out pending removes from the snapshot
Assert.That(registrationList.Unregister("A"), Is.True);
registrationList.GetRegisteredItems(registeredItems);
Assert.That(registeredItems, Is.EqualTo(new[] { "B" }));
}
[Test]
public void RegistrationListFastPathMatches()
{
var registrationList = new XRInteractionManager.RegistrationList<string>();
Assert.That(registrationList.Register("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.True);
registrationList.Flush();
Assert.That(registrationList.IsRegistered("A"), Is.True);
Assert.That(registrationList.IsStillRegistered("A"), Is.True);
Assert.That(registrationList.Unregister("A"), Is.True);
Assert.That(registrationList.IsRegistered("A"), Is.False);
Assert.That(registrationList.IsStillRegistered("A"), Is.False);
}
/// <summary>
/// Interactor that enables another Interactor and Interactable during <see cref="ProcessInteractor"/>.
/// </summary>
class EnablerInteractor : XRBaseInteractor
{
public XRBaseInteractor interactor { get; set; }
public XRBaseInteractable interactable { get; set; }
public bool enableBehaviors { get; set; }
/// <inheritdoc />
public override void ProcessInteractor(XRInteractionUpdateOrder.UpdatePhase updatePhase)
{
base.ProcessInteractor(updatePhase);
if (updatePhase == XRInteractionUpdateOrder.UpdatePhase.Dynamic)
{
if (interactor != null)
interactor.enabled = enableBehaviors;
if (interactable != null)
interactable.enabled = enableBehaviors;
}
}
/// <inheritdoc />
public override void GetValidTargets(List<XRBaseInteractable> targets)
{
targets.Clear();
}
public static EnablerInteractor CreateInteractor()
{
var interactorGO = new GameObject { name = "Enabler Interactor" };
var interactor = interactorGO.AddComponent<EnablerInteractor>();
return interactor;
}
}
/// <summary>
/// Interactable that enables another Interactor and Interactable during <see cref="ProcessInteractable"/>.
/// </summary>
class EnablerInteractable : XRBaseInteractable
{
public XRBaseInteractor interactor { get; set; }
public XRBaseInteractable interactable { get; set; }
public bool enableBehaviors { get; set; }
/// <inheritdoc />
public override void ProcessInteractable(XRInteractionUpdateOrder.UpdatePhase updatePhase)
{
base.ProcessInteractable(updatePhase);
if (updatePhase == XRInteractionUpdateOrder.UpdatePhase.Dynamic)
{
if (interactor != null)
interactor.enabled = enableBehaviors;
if (interactable != null)
interactable.enabled = enableBehaviors;
}
}
public static EnablerInteractable CreateInteractable()
{
var interactableGO = new GameObject { name = "Enabler Interactable" };
var interactable = interactableGO.AddComponent<EnablerInteractable>();
return interactable;
}
}
}
}
| 43.492997
| 158
| 0.643717
|
[
"MIT"
] |
rgonzaleztec/electivaRV
|
guias/VRHMD/OpenXRDemoLocomotion/Library/PackageCache/com.unity.xr.interaction.toolkit@1.0.0-pre.8/Tests/Runtime/InteractionManagerTests.cs
| 31,054
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PagedList;
using PagedList.Mvc;
namespace Seminarski.ViewModels
{
public class CjenovnikIndexVM
{
public List<Rows> rows { get; set; }
public class Rows
{
public int Id { get; set; }
public float Cijena { get; set; }
public string Usluga { get; set; }
public string Trajanje { get; set; }
public string Opis { get; set; }
}
}
}
| 24.363636
| 48
| 0.593284
|
[
"MIT"
] |
Hatidza97/RS1
|
Seminarski/ViewModels/CjenovnikIndexVM.cs
| 538
|
C#
|
/*
* Square Connect API
*
* Client library for accessing the Square Connect APIs
*
* OpenAPI spec version: 2.0
* Contact: developers@squareup.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Square.Connect.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class V1CreateDiscountRequest : IEquatable<V1CreateDiscountRequest>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="V1CreateDiscountRequest" /> class.
/// </summary>
/// <param name="Body">An object containing the fields to POST for the request. See the corresponding object definition for field details..</param>
public V1CreateDiscountRequest(V1Discount Body = default(V1Discount))
{
this.Body = Body;
}
/// <summary>
/// An object containing the fields to POST for the request. See the corresponding object definition for field details.
/// </summary>
/// <value>An object containing the fields to POST for the request. See the corresponding object definition for field details.</value>
[DataMember(Name="body", EmitDefaultValue=false)]
public V1Discount Body { 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 V1CreateDiscountRequest {\n");
sb.Append(" Body: ").Append(Body).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 V1CreateDiscountRequest);
}
/// <summary>
/// Returns true if V1CreateDiscountRequest instances are equal
/// </summary>
/// <param name="other">Instance of V1CreateDiscountRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(V1CreateDiscountRequest other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Body == other.Body ||
this.Body != null &&
this.Body.Equals(other.Body)
);
}
/// <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.Body != null)
hash = hash * 59 + this.Body.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 33.585366
| 156
| 0.58412
|
[
"Apache-2.0"
] |
jmawebtech/connect-csharp-sdk
|
src/Square.Connect/Model/V1CreateDiscountRequest.cs
| 4,131
|
C#
|
/**
* CameraController
*
* Author: Kirurobo http://twitter.com/kirurobo
* License: CC0 https://creativecommons.org/publicdomain/zero/1.0/
*/
using System;
using UnityEngine;
using UnityEngine.Serialization;
public class CameraController : MonoBehaviour
{
[Flags]
public enum RotationAxes
{
None = 0,
Pitch = 1,
Yaw = 2,
PitchAndYaw = 3
}
[Flags]
public enum ZoomType
{
None = 0,
Dolly = 1, // Dolly in/out
Zoom = 2, // Zoom in/out
}
public RotationAxes axes = RotationAxes.PitchAndYaw;
[FormerlySerializedAs("zoomMode")] public ZoomType zoomType = ZoomType.Dolly;
public float sensitivityX = 15f;
public float sensitivityY = 15f;
public float dragSensitivity = 0.1f;
public float wheelSensitivity = 0.5f;
public Vector2 minimumAngles = new Vector2(-90f, -360f);
public Vector2 maximumAngles = new Vector2(90f, 360f);
[Tooltip("None means to set the parent transform")]
public Transform centerTransform; // 回転中心
private GameObject centerObject = null; // 回転中心Transformが指定されなかった場合に作成される
internal Vector3 rotation;
internal Vector3 translation;
[SerializeField]
internal float distance;
internal Vector3 relativePosition;
internal Quaternion relativeRotation;
internal float originalDistance;
internal float originalFieldOfView;
internal float dolly;
internal float zoom;
internal Camera currentCamera;
void Start()
{
Initialize();
SetupTransform();
}
void OnDestroy()
{
// 回転中心を独自に作成していれば、削除
if (centerObject) GameObject.Destroy(centerObject);
}
void Update()
{
if (!currentCamera.isActiveAndEnabled) return;
if (!Input.GetKey(KeyCode.LeftShift) && !Input.GetKey(KeyCode.RightShift))
{
HandleMouse();
}
}
/// <summary>
/// 必要なオブジェクトを取得・準備
/// </summary>
internal void Initialize()
{
if (!centerTransform)
{
centerTransform = this.transform.parent;
if (!centerTransform || centerTransform == this.transform)
{
centerObject = new GameObject();
centerTransform.position = Vector3.zero;
centerTransform = centerObject.transform;
}
}
if (!currentCamera)
{
currentCamera = GetComponent<Camera>();
}
if (!currentCamera)
{
currentCamera = Camera.main;
}
}
/// <summary>
/// 初期位置・姿勢の設定
/// 対象となるオブジェクトがそろった後で実行する
/// </summary>
internal void SetupTransform()
{
relativePosition = centerTransform.position - transform.position; // カメラから中心座標へのベクトル
relativeRotation = Quaternion.LookRotation(relativePosition, Vector3.up);
originalDistance = relativePosition.magnitude;
originalFieldOfView = currentCamera.fieldOfView;
ResetTransform();
}
/// <summary>
/// Reset rotation and translation.
/// </summary>
public void ResetTransform()
{
rotation = relativeRotation.eulerAngles;
translation = Vector3.zero;
distance = originalDistance;
dolly = 0f;
zoom = Mathf.Log10(originalFieldOfView);
UpdateTransform();
}
/// <summary>
/// Apply rotation and translation
/// </summary>
internal void UpdateTransform()
{
Quaternion rot = Quaternion.Euler(rotation);
transform.rotation = rot;
transform.position = centerTransform.position + transform.rotation * Vector3.back * distance + transform.rotation * translation;
currentCamera.fieldOfView = Mathf.Pow(10f, zoom);
}
internal virtual void HandleMouse()
{
if (Input.GetMouseButton(1))
{
// 右ボタンドラッグで回転
if ((axes & RotationAxes.Yaw) > RotationAxes.None)
{
rotation.y += Input.GetAxis("Mouse X") * sensitivityX;
rotation.y = ClampAngle(rotation.y, minimumAngles.y, maximumAngles.y);
}
if ((axes & RotationAxes.Pitch) > RotationAxes.None)
{
rotation.x -= Input.GetAxis("Mouse Y") * sensitivityY;
rotation.x = ClampAngle(rotation.x, minimumAngles.x, maximumAngles.x);
}
UpdateTransform();
}
else if (Input.GetMouseButton(2))
{
// 中ボタンドラッグで並進移動
Vector3 screenVector = new Vector3(
Input.GetAxis("Mouse X") * dragSensitivity,
Input.GetAxis("Mouse Y") * dragSensitivity,
0f
);
//translation -= transform.rotation * screenVector;
translation -= screenVector;
UpdateTransform();
}
else
{
// ホイールで接近・離脱
float wheelDelta = Input.GetAxis("Mouse ScrollWheel") * wheelSensitivity;
ZoomType type = zoomType;
// Shiftキーが押されていて、かつZoomModeがZoomかDollyならば、モードを入れ替える
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
{
if (type == ZoomType.Dolly)
{
type = ZoomType.Zoom;
}
else if (type == ZoomType.Zoom)
{
type = ZoomType.Dolly;
}
}
if (wheelDelta != 0f)
{
if ((type & ZoomType.Dolly) != ZoomType.None)
{
// ドリーの場合。カメラを近づけたり遠ざけたり。
dolly += wheelDelta;
dolly = Mathf.Clamp(dolly, -2f, 5f); // Logarithm of distance [m] range
distance = originalDistance * Mathf.Pow(10f, -dolly);
UpdateTransform();
}
else if ((type & ZoomType.Zoom) != ZoomType.None)
{
// ズームの場合。カメラのFOVを変更
zoom -= wheelDelta;
zoom = Mathf.Clamp(zoom, -1f, 2f); // Logarithm of field-of-view [deg] range
UpdateTransform();
}
}
}
}
/// <summary>
/// 指定範囲から外れる角度の場合、補正する
/// </summary>
/// <param name="angle"></param>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -min) angle = -((-angle) % 360f);
if (angle > max) angle = angle % 360f;
return Mathf.Clamp(angle, min, max);
}
}
| 28.377119
| 136
| 0.555025
|
[
"MIT"
] |
kirurobo/UniWinApi
|
Assets/UniWinApiVrmViewer/Utils/CameraController.cs
| 7,139
|
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.Web.V20200601
{
public static class GetWebAppInstanceFunctionSlot
{
/// <summary>
/// Function information.
/// </summary>
public static Task<GetWebAppInstanceFunctionSlotResult> InvokeAsync(GetWebAppInstanceFunctionSlotArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetWebAppInstanceFunctionSlotResult>("azure-nextgen:web/v20200601:getWebAppInstanceFunctionSlot", args ?? new GetWebAppInstanceFunctionSlotArgs(), options.WithVersion());
}
public sealed class GetWebAppInstanceFunctionSlotArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Function name.
/// </summary>
[Input("functionName", required: true)]
public string FunctionName { get; set; } = null!;
/// <summary>
/// Site name.
/// </summary>
[Input("name", required: true)]
public string Name { get; set; } = null!;
/// <summary>
/// Name of the resource group to which the resource belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// Name of the deployment slot.
/// </summary>
[Input("slot", required: true)]
public string Slot { get; set; } = null!;
public GetWebAppInstanceFunctionSlotArgs()
{
}
}
[OutputType]
public sealed class GetWebAppInstanceFunctionSlotResult
{
/// <summary>
/// Config information.
/// </summary>
public readonly object? Config;
/// <summary>
/// Config URI.
/// </summary>
public readonly string? ConfigHref;
/// <summary>
/// File list.
/// </summary>
public readonly ImmutableDictionary<string, string>? Files;
/// <summary>
/// Function App ID.
/// </summary>
public readonly string? FunctionAppId;
/// <summary>
/// Function URI.
/// </summary>
public readonly string? Href;
/// <summary>
/// Resource Id.
/// </summary>
public readonly string Id;
/// <summary>
/// The invocation URL
/// </summary>
public readonly string? InvokeUrlTemplate;
/// <summary>
/// Gets or sets a value indicating whether the function is disabled
/// </summary>
public readonly bool? IsDisabled;
/// <summary>
/// Kind of resource.
/// </summary>
public readonly string? Kind;
/// <summary>
/// The function language
/// </summary>
public readonly string? Language;
/// <summary>
/// Resource Name.
/// </summary>
public readonly string Name;
/// <summary>
/// Script URI.
/// </summary>
public readonly string? ScriptHref;
/// <summary>
/// Script root path URI.
/// </summary>
public readonly string? ScriptRootPathHref;
/// <summary>
/// Secrets file URI.
/// </summary>
public readonly string? SecretsFileHref;
/// <summary>
/// Test data used when testing via the Azure Portal.
/// </summary>
public readonly string? TestData;
/// <summary>
/// Test data URI.
/// </summary>
public readonly string? TestDataHref;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetWebAppInstanceFunctionSlotResult(
object? config,
string? configHref,
ImmutableDictionary<string, string>? files,
string? functionAppId,
string? href,
string id,
string? invokeUrlTemplate,
bool? isDisabled,
string? kind,
string? language,
string name,
string? scriptHref,
string? scriptRootPathHref,
string? secretsFileHref,
string? testData,
string? testDataHref,
string type)
{
Config = config;
ConfigHref = configHref;
Files = files;
FunctionAppId = functionAppId;
Href = href;
Id = id;
InvokeUrlTemplate = invokeUrlTemplate;
IsDisabled = isDisabled;
Kind = kind;
Language = language;
Name = name;
ScriptHref = scriptHref;
ScriptRootPathHref = scriptRootPathHref;
SecretsFileHref = secretsFileHref;
TestData = testData;
TestDataHref = testDataHref;
Type = type;
}
}
}
| 28.565934
| 224
| 0.550298
|
[
"Apache-2.0"
] |
pulumi/pulumi-azure-nextgen
|
sdk/dotnet/Web/V20200601/GetWebAppInstanceFunctionSlot.cs
| 5,199
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// 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("SatelliteContract")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SatelliteContract")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("1f08915a-fc0e-4adf-97d5-1b97a069ba83")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: SatelliteContractVersion("2.0.0.0")]
| 37.923077
| 84
| 0.748479
|
[
"MIT"
] |
atkins126/I18N
|
Samples/WindowsForms/Signed/SatelliteContract/Properties/AssemblyInfo.cs
| 1,482
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NLog;
namespace Revo.Infrastructure.DataAccess.Migrations
{
public class DatabaseMigrationExecutor : IDatabaseMigrationExecutor
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly IDatabaseMigrationProvider[] migrationProviders;
private readonly IDatabaseMigrationRegistry migrationRegistry;
private readonly IDatabaseMigrationDiscovery[] migrationDiscoveries;
private readonly IDatabaseMigrationSelector migrationSelector;
private readonly IDatabaseMigrationExecutionOptions options;
private bool hasDiscoveryRun = false;
public DatabaseMigrationExecutor(IDatabaseMigrationProvider[] migrationProviders,
IDatabaseMigrationRegistry migrationRegistry,
IDatabaseMigrationDiscovery[] migrationDiscoveries,
IDatabaseMigrationSelector migrationSelector,
IDatabaseMigrationExecutionOptions options)
{
this.migrationProviders = migrationProviders;
this.migrationRegistry = migrationRegistry;
this.migrationDiscoveries = migrationDiscoveries;
this.migrationSelector = migrationSelector;
this.options = options;
}
public async Task<IReadOnlyCollection<PendingModuleMigration>> ExecuteAsync()
{
DiscoverAndRegister();
return await SelectAndExecuteMigrationsAsync();
}
public async Task<IReadOnlyCollection<PendingModuleMigration>> PreviewAsync()
{
DiscoverAndRegister();
var migrations = await SelectMigrationsAsync();
return migrations.ToArray();
}
private void DiscoverAndRegister()
{
if (hasDiscoveryRun)
{
return;
}
int migrationCount = 0;
foreach (var discovery in migrationDiscoveries)
{
var migrations = discovery.DiscoverMigrations();
foreach (var migration in migrations)
{
migrationRegistry.AddMigration(migration);
migrationCount++;
}
}
migrationRegistry.ValidateMigrations();
Logger.Debug($"Discovered {migrationCount} database migrations");
hasDiscoveryRun = true;
}
private async Task<IReadOnlyCollection<PendingModuleMigration>> SelectAndExecuteMigrationsAsync()
{
var pendingModuleMigrations = await SelectMigrationsAsync();
foreach (var pendingModuleMigration in pendingModuleMigrations)
{
await MigrateModuleAsync(pendingModuleMigration);
}
return pendingModuleMigrations;
}
private async Task<IReadOnlyCollection<PendingModuleMigration>> SelectMigrationsAsync()
{
IReadOnlyCollection<PendingModuleMigration> migrations;
if (options.MigrateOnlySpecifiedModules != null)
{
var moduleSpecifiers = SearchModules(options.MigrateOnlySpecifiedModules);
migrations = await SelectModuleMigrationsAsync(moduleSpecifiers.ToArray());
}
else
{
migrations = await SelectModuleMigrationsAsync(
migrationRegistry.GetAvailableModules()
.Select(x => new DatabaseMigrationSpecifier(x, null)).ToArray());
}
return migrations;
}
private List<DatabaseMigrationSpecifier> SearchModules(IReadOnlyCollection<DatabaseMigrationSearchSpecifier> searchedModules)
{
var result = new List<DatabaseMigrationSpecifier>();
foreach (var searchedModule in searchedModules)
{
var matchingModules = migrationRegistry.SearchModules(searchedModule.ModuleNameWildcard)
.Select(x => new DatabaseMigrationSpecifier(x, searchedModule.Version))
.ToArray();
foreach (var matchingModule in matchingModules)
{
if (!result.Contains(matchingModule))
{
result.Add(matchingModule);
}
}
}
return result;
}
private async Task<IReadOnlyCollection<PendingModuleMigration>> SelectModuleMigrationsAsync(DatabaseMigrationSpecifier[] migratedModules)
{
var migrations = new List<PendingModuleMigration>();
foreach (var provider in migrationProviders)
{
var environmentTags = options.EnvironmentTags
.Concat(provider.GetProviderEnvironmentTags())
.Distinct()
.ToArray();
var selectedMigrations = await migrationSelector.SelectMigrationsAsync(migratedModules, environmentTags);
if (selectedMigrations.Count > 0 && selectedMigrations.SelectMany(x => x.Migrations)
.All(provider.SupportsMigration))
{
migrations.AddRange(selectedMigrations.Select(x => new PendingModuleMigration(x.Specifier, x.Migrations, provider)));
}
}
return migrations;
}
private async Task MigrateModuleAsync(PendingModuleMigration migration)
{
var highestVersion = migration.Migrations.Where(x =>
string.Equals(x.ModuleName, migration.Specifier.ModuleName,
StringComparison.InvariantCultureIgnoreCase)
&& x.Version != null)
.OrderByDescending(x => x.Version)
.FirstOrDefault();
Logger.Info($"About to apply {migration.Migrations.Count} migrations to database for module {migration.Specifier.ModuleName} (up to version {highestVersion?.Version})");
await migration.Provider.ApplyMigrationsAsync(migration.Migrations);
Logger.Info($"Successfully migrated {migration.Specifier.ModuleName} module database to version {highestVersion?.Version}");
}
}
}
| 39.378882
| 181
| 0.623186
|
[
"MIT"
] |
Zev-OwitGlobal/Revo
|
Revo.Infrastructure/DataAccess/Migrations/DatabaseMigrationExecutor.cs
| 6,342
|
C#
|
using System;
namespace zmachine
{
public class ConsoleInputOutput : IZmachineInputOutput
{
public string ReadLine()
{
return Console.ReadLine();
}
public void Write(String str)
{
Console.Write(str);
}
public void WriteLine(String str)
{
Console.WriteLine(str);
}
}
}
| 18.52381
| 58
| 0.524422
|
[
"MIT"
] |
dshifflet/WasmZork
|
main/zmachine/ConsoleInputOutput.cs
| 389
|
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.Extensions.DiagnosticAdapter.Internal
{
public class InvalidProxyOperationException : InvalidOperationException
{
public InvalidProxyOperationException(string message) : base(message)
{
}
}
}
| 28.8
| 111
| 0.736111
|
[
"Apache-2.0"
] |
188867052/Extensions
|
src/DiagnosticAdapter/src/Internal/InvalidProxyOperationException.cs
| 434
|
C#
|
//
// ProgressBarBackend.cs
//
// Author:
// Andres G. Aragoneses <knocte@gmail.com>
//
// Copyright (c) 2012 Andres G. Aragoneses
//
// 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 Xwt.Backends;
namespace Xwt.WPFBackend
{
public class ProgressBarBackend: WidgetBackend, IProgressBarBackend
{
protected override void Initialize()
{
base.Initialize();
var progressBar = new System.Windows.Controls.ProgressBar();
Widget = progressBar;
progressBar.Maximum = 1.0;
progressBar.Minimum = 0.0;
progressBar.Value = 0.0;
progressBar.IsIndeterminate = false;
}
public void SetFraction (double fraction)
{
var widget = (System.Windows.Controls.ProgressBar) Widget;
if (widget.Value == fraction)
return;
widget.Value = fraction;
}
public void SetIndeterminate (bool value) {
var widget = (System.Windows.Controls.ProgressBar) Widget;
if (widget.IsIndeterminate == value)
return;
widget.IsIndeterminate = value;
}
}
}
| 31.681818
| 81
| 0.70923
|
[
"MIT"
] |
Bert1974/xwt
|
Xwt.WPF/Xwt.WPFBackend/ProgressBarBackend.cs
| 2,093
|
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.Datadog.Outputs
{
[OutputType]
public sealed class DashboardWidgetGroupDefinitionWidgetTimeseriesDefinitionRequestApmQueryGroupBy
{
public readonly string? Facet;
public readonly int? Limit;
public readonly Outputs.DashboardWidgetGroupDefinitionWidgetTimeseriesDefinitionRequestApmQueryGroupBySortQuery? SortQuery;
[OutputConstructor]
private DashboardWidgetGroupDefinitionWidgetTimeseriesDefinitionRequestApmQueryGroupBy(
string? facet,
int? limit,
Outputs.DashboardWidgetGroupDefinitionWidgetTimeseriesDefinitionRequestApmQueryGroupBySortQuery? sortQuery)
{
Facet = facet;
Limit = limit;
SortQuery = sortQuery;
}
}
}
| 32.323529
| 131
| 0.725205
|
[
"ECL-2.0",
"Apache-2.0"
] |
pulumi/pulumi-datadog
|
sdk/dotnet/Outputs/DashboardWidgetGroupDefinitionWidgetTimeseriesDefinitionRequestApmQueryGroupBy.cs
| 1,099
|
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace Contoso.FraudProtection.Web.Views.Manage
{
public static class ManageNavPages
{
public static string ActivePageKey => "ActivePage";
public static string Index => "Index";
public static string ManagePaymentInstrument => "ManagePaymentInstrument";
public static string ChangePassword => "ChangePassword";
public static string ExternalLogins => "ExternalLogins";
public static string IndexNavClass(ViewContext viewContext) => PageNavClass(viewContext, Index);
public static string ManagePaymentInstrumentNavClass(ViewContext viewContext) => PageNavClass(viewContext, ManagePaymentInstrument);
public static string ChangePasswordNavClass(ViewContext viewContext) => PageNavClass(viewContext, ChangePassword);
public static string ExternalLoginsNavClass(ViewContext viewContext) => PageNavClass(viewContext, ExternalLogins);
public static string PageNavClass(ViewContext viewContext, string page)
{
var activePage = viewContext.ViewData["ActivePage"] as string;
return string.Equals(activePage, page, StringComparison.OrdinalIgnoreCase) ? "active" : null;
}
public static void AddActivePage(this ViewDataDictionary viewData, string activePage) => viewData[ActivePageKey] = activePage;
}
}
| 39.025641
| 140
| 0.743758
|
[
"MIT"
] |
Bhaskers-Blu-Org2/Dynamics-365-Fraud-Protection-Samples
|
src/Web/Views/Manage/ManageNavPages.cs
| 1,522
|
C#
|
namespace MyExam.BindingModels
{
using System.ComponentModel.DataAnnotations;
public class OrderBindingModel
{
[Required]
[RegularExpression(@"\d{12}")]
public string Barcode { get; set; }
[Required]
public int Quantity { get; set; }
}
}
| 21.142857
| 48
| 0.608108
|
[
"MIT"
] |
mayapeneva/Web-Development-Basics
|
EXAMS/MyExam_18.12.2018/MyExam.BindingModels/OrderBindingModel.cs
| 298
|
C#
|
namespace MassTransit.Registration
{
public class EndpointRegistration<T> :
IEndpointRegistration
where T : class
{
public IEndpointDefinition GetDefinition(IConfigurationServiceProvider provider)
{
return provider.GetRequiredService<IEndpointDefinition<T>>();
}
}
}
| 25.461538
| 88
| 0.673716
|
[
"ECL-2.0",
"Apache-2.0"
] |
Aerodynamite/MassTrans
|
src/MassTransit/Configuration/Registration/EndpointRegistration.cs
| 331
|
C#
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.Sql.Replication.Model;
using System.Collections.Generic;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Sql.Replication.Cmdlet
{
[Cmdlet(VerbsCommon.Get, "AzureRmSqlDatabaseReplicationLink",
DefaultParameterSetName = ByDatabaseName,
ConfirmImpact = ConfirmImpact.None)]
public class GetAzureSqlDatabaseReplicationLink : AzureSqlDatabaseSecondaryCmdletBase
{
/// <summary>
/// ParameterSet to get all Replication Links for a given Azure SQL Database
/// </summary>
internal const string ByDatabaseName = "ByDatabaseName";
/// <summary>
/// ParameterSet to get a Replication Link by its partner Azure SQL Server Name
/// </summary>
internal const string ByPartnerServerName = "ByPartnerServerName";
/// <summary>
/// Gets or sets the name of the Azure SQL Database to retrieve links for.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
Position = 2,
HelpMessage = "The name of the Azure SQL Database to retrieve links for.")]
[ValidateNotNullOrEmpty]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the name of the resource group for the partner.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the resource group for the partner.")]
[ValidateNotNullOrEmpty]
public string PartnerResourceGroupName { get; set; }
/// <summary>
/// Gets or sets the name of the Azure SQL Server that has the Azure SQL Database partner.
/// </summary>
[Parameter(Mandatory = false,
ParameterSetName = ByPartnerServerName,
ValueFromPipelineByPropertyName = false,
HelpMessage = "The name of the Azure SQL Server that has the Azure SQL Database partner.")]
[ValidateNotNullOrEmpty]
public string PartnerServerName { get; set; }
/// <summary>
/// Get the entities from the service
/// </summary>
/// <returns>The list of entities</returns>
protected override IEnumerable<AzureReplicationLinkModel> GetEntity()
{
ICollection<AzureReplicationLinkModel> results;
if (ParameterSetName == ByPartnerServerName)
{
results = new List<AzureReplicationLinkModel>();
results.Add(ModelAdapter.GetLink(this.ResourceGroupName, this.ServerName, this.DatabaseName, this.PartnerResourceGroupName, this.PartnerServerName));
}
else
{
results = ModelAdapter.ListLinks(this.ResourceGroupName, this.ServerName, this.DatabaseName, this.PartnerResourceGroupName);
}
return results;
}
/// <summary>
/// No user input to apply to model
/// </summary>
/// <param name="model">Model retrieved from service</param>
/// <returns>The model that was passed in</returns>
protected override IEnumerable<AzureReplicationLinkModel> ApplyUserInputToModel(IEnumerable<AzureReplicationLinkModel> model)
{
return model;
}
/// <summary>
/// No changes to persist to Azure SQL Server
/// </summary>
/// <param name="entity">The output of apply user input to model</param>
/// <returns>The input entity</returns>
protected override IEnumerable<AzureReplicationLinkModel> PersistChanges(IEnumerable<AzureReplicationLinkModel> entity)
{
return entity;
}
}
}
| 43.242991
| 166
| 0.614005
|
[
"MIT"
] |
hchungmsft/azure-powershell
|
src/ResourceManager/Sql/Commands.Sql/Replication/Cmdlet/GetAzureSqlDatabaseReplicationLink.cs
| 4,523
|
C#
|
using System;
using System.IO;
using Gtk;
using QSProjectsLib;
namespace QSBanks
{
public partial class BanksUpdateWindow : Gtk.Window
{
BanksUpdater updater = new BanksUpdater(new QS.BaseParameters.ParametersService(QSMain.ConnectionDB));
public BanksUpdateWindow() :
base(Gtk.WindowType.Toplevel)
{
this.Build();
this.WidthRequest = 400;
this.HeightRequest = 300;
vboxManualLoad.Visible = checkbutton.Active = false;
var txtFilter = new FileFilter();
txtFilter.AddPattern("*.zip");
txtFilter.Name = "Zip архив (*.zip)";
filechooser.AddFilter(txtFilter);
filechooser.SelectMultiple = false;
progressbar.Adjustment = new Adjustment(0, 0, 100, 1, 1, 1);
updater.OnOutputMessage += Updater_OnOutputMessage;
updater.OnProgress += Updater_OnProgress;;
}
protected void OnCheckbuttonToggled(object sender, EventArgs e)
{
vboxManualLoad.Visible = checkbutton.Active;
}
protected void OnButtonUpdateClicked(object sender, EventArgs e)
{
textviewOutput.Buffer.Clear();
progressbar.Adjustment.Value = 0;
if(checkbutton.Active && !string.IsNullOrWhiteSpace(filechooser.Filename) && File.Exists(filechooser.Filename)) {
FileStream fs = new FileStream(filechooser.Filename, FileMode.Open);
updater.UpdateBanks(fs);
} else {
updater.UpdateBanks();
}
}
void Updater_OnOutputMessage(object sender, string e)
{
textviewOutput.Buffer.Text += e + "\n";
QSMain.WaitRedraw();
}
void Updater_OnProgress(object sender, int e)
{
progressbar.Adjustment.Value = e;
QSMain.WaitRedraw();
}
}
}
| 26.533333
| 116
| 0.721106
|
[
"Apache-2.0"
] |
Art8m/QSProjects
|
Modules/QSBanks/BanksUpdateWindow.cs
| 1,599
|
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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\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;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void HashUpdateParity_Vector128_UInt32()
{
var test = new SecureHashTernaryOpTest__HashUpdateParity_Vector128_UInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SecureHashTernaryOpTest__HashUpdateParity_Vector128_UInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] inArray3, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt32, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt32> _fld1;
public Vector64<UInt32> _fld2;
public Vector128<UInt32> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 0x44556677; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SecureHashTernaryOpTest__HashUpdateParity_Vector128_UInt32 testClass)
{
var result = Sha1.HashUpdateParity(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SecureHashTernaryOpTest__HashUpdateParity_Vector128_UInt32 testClass)
{
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector64<UInt32>* pFld2 = &_fld2)
fixed (Vector128<UInt32>* pFld3 = &_fld3)
{
var result = Sha1.HashUpdateParity(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector64((UInt32*)(pFld2)),
AdvSimd.LoadVector128((UInt32*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static UInt32[] _data3 = new UInt32[Op3ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector64<UInt32> _clsVar2;
private static Vector128<UInt32> _clsVar3;
private Vector128<UInt32> _fld1;
private Vector64<UInt32> _fld2;
private Vector128<UInt32> _fld3;
private DataTable _dataTable;
static SecureHashTernaryOpTest__HashUpdateParity_Vector128_UInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 0x44556677; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public SecureHashTernaryOpTest__HashUpdateParity_Vector128_UInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 0x44556677; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = 0x00112233; }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 0x44556677; }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = 0x8899AABB; }
_dataTable = new DataTable(_data1, _data2, _data3, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sha1.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sha1.HashUpdateParity(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sha1.HashUpdateParity(
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sha1).GetMethod(nameof(Sha1.HashUpdateParity), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sha1).GetMethod(nameof(Sha1.HashUpdateParity), new Type[] { typeof(Vector128<UInt32>), typeof(Vector64<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sha1.HashUpdateParity(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector64<UInt32>* pClsVar2 = &_clsVar2)
fixed (Vector128<UInt32>* pClsVar3 = &_clsVar3)
{
var result = Sha1.HashUpdateParity(
AdvSimd.LoadVector128((UInt32*)(pClsVar1)),
AdvSimd.LoadVector64((UInt32*)(pClsVar2)),
AdvSimd.LoadVector128((UInt32*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray3Ptr);
var result = Sha1.HashUpdateParity(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray3Ptr));
var result = Sha1.HashUpdateParity(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SecureHashTernaryOpTest__HashUpdateParity_Vector128_UInt32();
var result = Sha1.HashUpdateParity(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SecureHashTernaryOpTest__HashUpdateParity_Vector128_UInt32();
fixed (Vector128<UInt32>* pFld1 = &test._fld1)
fixed (Vector64<UInt32>* pFld2 = &test._fld2)
fixed (Vector128<UInt32>* pFld3 = &test._fld3)
{
var result = Sha1.HashUpdateParity(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector64((UInt32*)(pFld2)),
AdvSimd.LoadVector128((UInt32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sha1.HashUpdateParity(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector64<UInt32>* pFld2 = &_fld2)
fixed (Vector128<UInt32>* pFld3 = &_fld3)
{
var result = Sha1.HashUpdateParity(
AdvSimd.LoadVector128((UInt32*)(pFld1)),
AdvSimd.LoadVector64((UInt32*)(pFld2)),
AdvSimd.LoadVector128((UInt32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sha1.HashUpdateParity(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sha1.HashUpdateParity(
AdvSimd.LoadVector128((UInt32*)(&test._fld1)),
AdvSimd.LoadVector64((UInt32*)(&test._fld2)),
AdvSimd.LoadVector128((UInt32*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt32> op1, Vector64<UInt32> op2, Vector128<UInt32> op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] inArray3 = new UInt32[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] inArray3 = new UInt32[Op3ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] secondOp, UInt32[] thirdOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
UInt32[] expectedResult = new UInt32[]{0xDAB2AF34, 0xFF990D18, 0xCB4F938C, 0x73C91E71};
for (int i = 0; i < RetElementCount; i++)
{
if (result[i] != expectedResult[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sha1)}.{nameof(Sha1.HashUpdateParity)}<UInt32>(Vector128<UInt32>, Vector64<UInt32>, Vector128<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 45.738676
| 200
| 0.594119
|
[
"MIT"
] |
06needhamt/runtime
|
src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/Sha1/HashUpdateParity.Vector128.UInt32.cs
| 26,254
|
C#
|
namespace RenamerCore.Models
{
public class FileMatch
{
public string OldPath { get; set; }
public string NewPath { get; set; }
}
}
| 16.1
| 43
| 0.596273
|
[
"MIT"
] |
amoscardino/renamer-core
|
Models/FileMatch.cs
| 161
|
C#
|
namespace ch4_TypingGame
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.listBox1 = new System.Windows.Forms.ListBox();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.correctLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.missedLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.totalLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.accuracyLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
this.difficultyProgressBar = new System.Windows.Forms.ToolStripProgressBar();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.timer2 = new System.Windows.Forms.Timer(this.components);
this.statusStrip1.SuspendLayout();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.BackColor = System.Drawing.SystemColors.WindowText;
this.listBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 72F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.listBox1.ForeColor = System.Drawing.SystemColors.HighlightText;
this.listBox1.FormattingEnabled = true;
this.listBox1.ItemHeight = 108;
this.listBox1.Location = new System.Drawing.Point(0, 0);
this.listBox1.MultiColumn = true;
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(860, 135);
this.listBox1.TabIndex = 0;
//
// timer1
//
this.timer1.Interval = 800;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.correctLabel,
this.missedLabel,
this.totalLabel,
this.accuracyLabel,
this.toolStripStatusLabel1,
this.difficultyProgressBar});
this.statusStrip1.Location = new System.Drawing.Point(0, 113);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(860, 22);
this.statusStrip1.SizingGrip = false;
this.statusStrip1.TabIndex = 1;
this.statusStrip1.Text = "statusStrip1";
//
// correctLabel
//
this.correctLabel.Name = "correctLabel";
this.correctLabel.Size = new System.Drawing.Size(58, 17);
this.correctLabel.Text = "Correct: 0";
//
// missedLabel
//
this.missedLabel.Name = "missedLabel";
this.missedLabel.Size = new System.Drawing.Size(56, 17);
this.missedLabel.Text = "Missed: 0";
//
// totalLabel
//
this.totalLabel.Name = "totalLabel";
this.totalLabel.Size = new System.Drawing.Size(45, 17);
this.totalLabel.Text = "Total: 0";
//
// accuracyLabel
//
this.accuracyLabel.Name = "accuracyLabel";
this.accuracyLabel.Size = new System.Drawing.Size(78, 17);
this.accuracyLabel.Text = "Accuracy: 0%";
//
// toolStripStatusLabel1
//
this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
this.toolStripStatusLabel1.Size = new System.Drawing.Size(506, 17);
this.toolStripStatusLabel1.Spring = true;
this.toolStripStatusLabel1.Text = "Difficulty";
this.toolStripStatusLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// difficultyProgressBar
//
this.difficultyProgressBar.Maximum = 701;
this.difficultyProgressBar.Name = "difficultyProgressBar";
this.difficultyProgressBar.Size = new System.Drawing.Size(100, 16);
//
// button1
//
this.button1.BackColor = System.Drawing.Color.SteelBlue;
this.button1.Location = new System.Drawing.Point(262, 32);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(115, 51);
this.button1.TabIndex = 2;
this.button1.Text = "Start";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.BackColor = System.Drawing.Color.SteelBlue;
this.button2.Location = new System.Drawing.Point(409, 32);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(115, 51);
this.button2.TabIndex = 3;
this.button2.Text = "About";
this.button2.UseVisualStyleBackColor = false;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.BackColor = System.Drawing.Color.SteelBlue;
this.button3.Location = new System.Drawing.Point(530, 32);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(115, 51);
this.button3.TabIndex = 4;
this.button3.Text = "Play Again";
this.button3.UseVisualStyleBackColor = false;
this.button3.Visible = false;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// timer2
//
this.timer2.Interval = 1000;
this.timer2.Tick += new System.EventHandler(this.timer2_Tick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ControlText;
this.ClientSize = new System.Drawing.Size(860, 135);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.statusStrip1);
this.Controls.Add(this.listBox1);
this.ForeColor = System.Drawing.SystemColors.HighlightText;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.Text = "How Fast U R @ Typing";
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel correctLabel;
private System.Windows.Forms.ToolStripStatusLabel missedLabel;
private System.Windows.Forms.ToolStripStatusLabel totalLabel;
private System.Windows.Forms.ToolStripStatusLabel accuracyLabel;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
private System.Windows.Forms.ToolStripProgressBar difficultyProgressBar;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Timer timer2;
}
}
| 46.004902
| 169
| 0.581993
|
[
"MIT"
] |
dark-jay/Typing-Game
|
ch4_TypingGame/Form1.Designer.cs
| 9,387
|
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 brainHatSharpGUI.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("0")]
public int BoardId {
get {
return ((int)(this["BoardId"]));
}
set {
this["BoardId"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string ComPort {
get {
return ((string)(this["ComPort"]));
}
set {
this["ComPort"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("225.1.1.1")]
public string IPAddress {
get {
return ((string)(this["IPAddress"]));
}
set {
this["IPAddress"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("6677")]
public int IPPort {
get {
return ((int)(this["IPPort"]));
}
set {
this["IPPort"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool UseBFStream {
get {
return ((bool)(this["UseBFStream"]));
}
set {
this["UseBFStream"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool LogToFile {
get {
return ((bool)(this["LogToFile"]));
}
set {
this["LogToFile"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool StartSRB {
get {
return ((bool)(this["StartSRB"]));
}
set {
this["StartSRB"] = value;
}
}
}
}
| 36.144144
| 151
| 0.544367
|
[
"MIT"
] |
GrahamBriggs/bcibeginner
|
brainHatServer/brainHatSharpGUI/Properties/Settings.Designer.cs
| 4,014
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Core;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
[JsonConverter(typeof(AzureBlobStorageLinkedServiceConverter))]
public partial class AzureBlobStorageLinkedService : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("type");
writer.WriteStringValue(Type);
if (Optional.IsDefined(ConnectVia))
{
writer.WritePropertyName("connectVia");
writer.WriteObjectValue(ConnectVia);
}
if (Optional.IsDefined(Description))
{
writer.WritePropertyName("description");
writer.WriteStringValue(Description);
}
if (Optional.IsCollectionDefined(Parameters))
{
writer.WritePropertyName("parameters");
writer.WriteStartObject();
foreach (var item in Parameters)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
if (Optional.IsCollectionDefined(Annotations))
{
writer.WritePropertyName("annotations");
writer.WriteStartArray();
foreach (var item in Annotations)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
}
writer.WritePropertyName("typeProperties");
writer.WriteStartObject();
if (Optional.IsDefined(ConnectionString))
{
writer.WritePropertyName("connectionString");
writer.WriteObjectValue(ConnectionString);
}
if (Optional.IsDefined(AccountKey))
{
writer.WritePropertyName("accountKey");
writer.WriteObjectValue(AccountKey);
}
if (Optional.IsDefined(SasUri))
{
writer.WritePropertyName("sasUri");
writer.WriteObjectValue(SasUri);
}
if (Optional.IsDefined(SasToken))
{
writer.WritePropertyName("sasToken");
writer.WriteObjectValue(SasToken);
}
if (Optional.IsDefined(ServiceEndpoint))
{
writer.WritePropertyName("serviceEndpoint");
writer.WriteStringValue(ServiceEndpoint);
}
if (Optional.IsDefined(ServicePrincipalId))
{
writer.WritePropertyName("servicePrincipalId");
writer.WriteObjectValue(ServicePrincipalId);
}
if (Optional.IsDefined(ServicePrincipalKey))
{
writer.WritePropertyName("servicePrincipalKey");
writer.WriteObjectValue(ServicePrincipalKey);
}
if (Optional.IsDefined(Tenant))
{
writer.WritePropertyName("tenant");
writer.WriteObjectValue(Tenant);
}
if (Optional.IsDefined(AzureCloudType))
{
writer.WritePropertyName("azureCloudType");
writer.WriteObjectValue(AzureCloudType);
}
if (Optional.IsDefined(EncryptedCredential))
{
writer.WritePropertyName("encryptedCredential");
writer.WriteStringValue(EncryptedCredential);
}
writer.WriteEndObject();
foreach (var item in AdditionalProperties)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
internal static AzureBlobStorageLinkedService DeserializeAzureBlobStorageLinkedService(JsonElement element)
{
string type = default;
Optional<IntegrationRuntimeReference> connectVia = default;
Optional<string> description = default;
Optional<IDictionary<string, ParameterSpecification>> parameters = default;
Optional<IList<object>> annotations = default;
Optional<object> connectionString = default;
Optional<AzureKeyVaultSecretReference> accountKey = default;
Optional<object> sasUri = default;
Optional<AzureKeyVaultSecretReference> sasToken = default;
Optional<string> serviceEndpoint = default;
Optional<object> servicePrincipalId = default;
Optional<SecretBase> servicePrincipalKey = default;
Optional<object> tenant = default;
Optional<object> azureCloudType = default;
Optional<string> encryptedCredential = default;
IDictionary<string, object> additionalProperties = default;
Dictionary<string, object> additionalPropertiesDictionary = new Dictionary<string, object>();
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("connectVia"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
connectVia = IntegrationRuntimeReference.DeserializeIntegrationRuntimeReference(property.Value);
continue;
}
if (property.NameEquals("description"))
{
description = property.Value.GetString();
continue;
}
if (property.NameEquals("parameters"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
Dictionary<string, ParameterSpecification> dictionary = new Dictionary<string, ParameterSpecification>();
foreach (var property0 in property.Value.EnumerateObject())
{
dictionary.Add(property0.Name, ParameterSpecification.DeserializeParameterSpecification(property0.Value));
}
parameters = dictionary;
continue;
}
if (property.NameEquals("annotations"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
List<object> array = new List<object>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(item.GetObject());
}
annotations = array;
continue;
}
if (property.NameEquals("typeProperties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("connectionString"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
connectionString = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("accountKey"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
accountKey = AzureKeyVaultSecretReference.DeserializeAzureKeyVaultSecretReference(property0.Value);
continue;
}
if (property0.NameEquals("sasUri"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
sasUri = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("sasToken"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
sasToken = AzureKeyVaultSecretReference.DeserializeAzureKeyVaultSecretReference(property0.Value);
continue;
}
if (property0.NameEquals("serviceEndpoint"))
{
serviceEndpoint = property0.Value.GetString();
continue;
}
if (property0.NameEquals("servicePrincipalId"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
servicePrincipalId = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("servicePrincipalKey"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
servicePrincipalKey = SecretBase.DeserializeSecretBase(property0.Value);
continue;
}
if (property0.NameEquals("tenant"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
tenant = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("azureCloudType"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
azureCloudType = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("encryptedCredential"))
{
encryptedCredential = property0.Value.GetString();
continue;
}
}
continue;
}
additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject());
}
additionalProperties = additionalPropertiesDictionary;
return new AzureBlobStorageLinkedService(type, connectVia.Value, description.Value, Optional.ToDictionary(parameters), Optional.ToList(annotations), additionalProperties, connectionString.Value, accountKey.Value, sasUri.Value, sasToken.Value, serviceEndpoint.Value, servicePrincipalId.Value, servicePrincipalKey.Value, tenant.Value, azureCloudType.Value, encryptedCredential.Value);
}
internal partial class AzureBlobStorageLinkedServiceConverter : JsonConverter<AzureBlobStorageLinkedService>
{
public override void Write(Utf8JsonWriter writer, AzureBlobStorageLinkedService model, JsonSerializerOptions options)
{
writer.WriteObjectValue(model);
}
public override AzureBlobStorageLinkedService Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using var document = JsonDocument.ParseValue(ref reader);
return DeserializeAzureBlobStorageLinkedService(document.RootElement);
}
}
}
}
| 44.81877
| 394
| 0.492454
|
[
"MIT"
] |
AME-Redmond/azure-sdk-for-net
|
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/AzureBlobStorageLinkedService.Serialization.cs
| 13,849
|
C#
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Graphics;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModSuddenDeath : Mod, IApplicableToScoreProcessor
{
public override string Name => "Sudden Death";
public override string ShortenedName => "SD";
public override FontAwesome Icon => FontAwesome.fa_osu_mod_suddendeath;
public override ModType Type => ModType.DifficultyIncrease;
public override string Description => "Miss a note and fail.";
public override double ScoreMultiplier => 1;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModNoFail), typeof(ModRelax), typeof(ModAutoplay) };
public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor)
{
scoreProcessor.FailConditions += FailCondition;
}
protected virtual bool FailCondition(ScoreProcessor scoreProcessor) => scoreProcessor.Combo.Value == 0;
}
}
| 41
| 119
| 0.692178
|
[
"MIT"
] |
StefanYohansson/osu
|
osu.Game/Rulesets/Mods/ModSuddenDeath.cs
| 1,189
|
C#
|
/**
This work is licensed under a Creative Commons Attribution 3.0 Unported License.
http://creativecommons.org/licenses/by/3.0/deed.en_GB
You are free:
to copy, distribute, display, and perform the work
to make derivative works
to make commercial use of the work
*/
using UnityEngine;
[ExecuteInEditMode]
[AddComponentMenu("Image Effects/GlitchEffect")]
[RequireComponent(typeof(Camera))]
public class GlitchEffect : MonoBehaviour
{
public Texture2D displacementMap;
public Shader Shader;
[Header("Glitch Intensity")]
[Range(0, 1)]
public float intensity;
[Range(0, 1)]
public float flipIntensity;
[Range(0, 1)]
public float colorIntensity;
private float _glitchup;
private float _glitchdown;
private float flicker;
private float _glitchupTime = 0.05f;
private float _glitchdownTime = 0.05f;
private float _flickerTime = 0.5f;
private Material _material;
void Start()
{
_material = new Material(Shader);
}
// Called by camera to apply image effect
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
_material.SetFloat("_Intensity", intensity);
_material.SetFloat("_ColorIntensity", colorIntensity);
_material.SetTexture("_DispTex", displacementMap);
flicker += Time.deltaTime * colorIntensity * 10f;
if (flicker > _flickerTime)
{
_material.SetFloat("filterRadius", Random.Range(-1f, 1f) * colorIntensity);
_material.SetVector("direction", Quaternion.AngleAxis(Random.Range(0, 10) * colorIntensity, Vector3.forward) * Vector4.one);
flicker = 0;
_flickerTime = Random.value;
}
if (colorIntensity == 0)
_material.SetFloat("filterRadius", 0);
_glitchup += Time.deltaTime * flipIntensity;
if (_glitchup > _glitchupTime)
{
if (Random.value < 0.1f * flipIntensity)
_material.SetFloat("flip_up", Random.Range(0, 1f) * flipIntensity);
else
_material.SetFloat("flip_up", 0);
_glitchup = 0;
_glitchupTime = Random.value / 10f;
}
if (flipIntensity == 0)
_material.SetFloat("flip_up", 0);
_glitchdown += Time.deltaTime * flipIntensity;
if (_glitchdown > _glitchdownTime)
{
if (Random.value < 0.1f * flipIntensity)
_material.SetFloat("flip_down", 1 - Random.Range(0, 3f) * flipIntensity);
else
_material.SetFloat("flip_down", 1);
_glitchdown = 0;
_glitchdownTime = Random.value / 10f;
}
if (flipIntensity == 0)
_material.SetFloat("flip_down", 1);
if (Random.value < 0.05 * intensity)
{
_material.SetFloat("displace", Random.value * intensity);
_material.SetFloat("scale", 1 - Random.value * intensity);
}
else
_material.SetFloat("displace", 0);
Graphics.Blit(source, destination, _material);
}
}
| 25.361905
| 127
| 0.717987
|
[
"MIT"
] |
kiskovi97/RewindMan
|
RewindMan/Assets/Scripts/Glitch/unityglitch-master/GlitchEffect.cs
| 2,663
|
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 Vip.RichTextBox.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Vip.RichTextBox.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 43.65625
| 181
| 0.613815
|
[
"MIT"
] |
leandrovip/Vip.RichTextBox
|
src/Vip.RichTextBox/Properties/Resources.Designer.cs
| 2,796
|
C#
|
using System.Web.Mvc;
namespace App.Client.Infastructure.Controllers
{
public class ErrorController : BaseController
{
public ActionResult Generic()
{
return View();
}
public ActionResult Lockout()
{
return View();
}
public ActionResult Http400()
{
return View();
}
public ActionResult Http404()
{
return View();
}
public ActionResult Http500()
{
return View();
}
}
}
| 17.65625
| 49
| 0.484956
|
[
"MIT"
] |
Geekballs/Bootmock
|
App.Client/Infastructure/Controllers/ErrorController.cs
| 567
|
C#
|
using System.Drawing;
namespace YAXLibTests.SampleClasses
{
public class RectangleDynamicKnownTypeSample
{
public Rectangle Rect { get; set; }
public static RectangleDynamicKnownTypeSample GetSampleInstance()
{
return new RectangleDynamicKnownTypeSample {Rect = new Rectangle(10, 20, 30, 40)};
}
public override string ToString()
{
return GeneralToStringProvider.GeneralToString(this);
}
}
}
| 24.45
| 94
| 0.650307
|
[
"Apache-2.0"
] |
GoodAI/BrainSimulator
|
Sources/Libs/3rd/YAXLib/YAXLibTests/SampleClasses/RectangleDynamicKnownTypeSample.cs
| 491
|
C#
|
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace P1_DaytonSchuh.Controllers
{
public class RoleManagerController : Controller
{
private readonly RoleManager<IdentityRole> _roleManager;
public RoleManagerController(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
public async Task<IActionResult> Index()
{
var roles = await _roleManager.Roles.ToListAsync();
return View(roles);
}
[HttpPost]
public async Task<IActionResult> AddRole(string roleName)
{
if (roleName != null)
{
await _roleManager.CreateAsync(new IdentityRole(roleName.Trim()));
}
return RedirectToAction("Index");
}
[HttpPost]
public async Task<IActionResult> DeleteRole(string roleName)
{
if(roleName != null)
{
await _roleManager.DeleteAsync(_roleManager.FindByNameAsync(roleName).Result);
}
return RedirectToAction("Index");
}
}
}
| 29.159091
| 94
| 0.618862
|
[
"MIT"
] |
12142020-dotnet-uta/DaytonSchuhRepo1
|
Projects/P1_DaytonSchuh/P1_DaytonSchuh/Controllers/Manage/RoleManagerController.cs
| 1,285
|
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 Float = System.Single;
using System;
using System.Linq;
using System.Text;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.CommandLine;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.Internal.Utilities;
using Microsoft.ML.Runtime.Model;
using Microsoft.ML.Runtime.EntryPoints;
using Microsoft.ML.Transforms.Text;
[assembly: LoadableClass(NgramTransform.Summary, typeof(NgramTransform), typeof(NgramTransform.Arguments), typeof(SignatureDataTransform),
"Ngram Transform", "NgramTransform", "Ngram")]
[assembly: LoadableClass(NgramTransform.Summary, typeof(NgramTransform), null, typeof(SignatureLoadDataTransform),
"Ngram Transform", NgramTransform.LoaderSignature)]
namespace Microsoft.ML.Transforms.Text
{
using Conditional = System.Diagnostics.ConditionalAttribute;
public sealed class NgramTransform : OneToOneTransformBase
{
/// <summary>
/// Weighting criteria: a statistical measure used to evaluate how important a word is to a document in a corpus.
/// This enumeration is serialized.
/// </summary>
public enum WeightingCriteria
{
[EnumValueDisplay("TF (Term Frequency)")]
Tf = 0,
[EnumValueDisplay("IDF (Inverse Document Frequency)")]
Idf = 1,
[EnumValueDisplay("TF-IDF")]
TfIdf = 2
}
public sealed class Column : OneToOneColumn
{
[Argument(ArgumentType.AtMostOnce, HelpText = "Maximum ngram length", ShortName = "ngram")]
public int? NgramLength;
[Argument(ArgumentType.AtMostOnce, HelpText =
"Whether to include all ngram lengths up to " + nameof(NgramLength) + " or only " + nameof(NgramLength), ShortName = "all")]
public bool? AllLengths;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Maximum number of tokens to skip when constructing an ngram",
ShortName = "skips")]
public int? SkipLength;
[Argument(ArgumentType.Multiple, HelpText = "Maximum number of ngrams to store in the dictionary", ShortName = "max")]
public int[] MaxNumTerms = null;
[Argument(ArgumentType.AtMostOnce, HelpText = "Statistical measure used to evaluate how important a word is to a document in a corpus")]
public WeightingCriteria? Weighting;
public static Column Parse(string str)
{
Contracts.AssertNonEmpty(str);
var res = new Column();
if (res.TryParse(str))
return res;
return null;
}
public bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
if (NgramLength != null || AllLengths != null || SkipLength != null || Utils.Size(MaxNumTerms) != 0)
return false;
return TryUnparseCore(sb);
}
}
public sealed class Arguments : TransformInputBase
{
internal const int DefaultMaxTerms = 10000000;
[Argument(ArgumentType.Multiple, HelpText = "New column definition(s) (optional form: name:src)", ShortName = "col", SortOrder = 1)]
public Column[] Column;
[Argument(ArgumentType.AtMostOnce, HelpText = "Maximum ngram length", ShortName = "ngram")]
public int NgramLength = 2;
[Argument(ArgumentType.AtMostOnce, HelpText =
"Whether to store all ngram lengths up to ngramLength, or only ngramLength", ShortName = "all")]
public bool AllLengths = true;
[Argument(ArgumentType.AtMostOnce,
HelpText = "Maximum number of tokens to skip when constructing an ngram",
ShortName = "skips")]
public int SkipLength = 0;
[Argument(ArgumentType.Multiple, HelpText = "Maximum number of ngrams to store in the dictionary", ShortName = "max")]
public int[] MaxNumTerms = new int[] { DefaultMaxTerms };
[Argument(ArgumentType.AtMostOnce, HelpText = "The weighting criteria")]
public WeightingCriteria Weighting = WeightingCriteria.Tf;
}
private sealed class ColInfoEx
{
// Position i, indicates whether the pool contains any (i+1)-grams
public readonly bool[] NonEmptyLevels;
public readonly int NgramLength;
public readonly int SkipLength;
public readonly WeightingCriteria Weighting;
public bool RequireIdf()
{
return Weighting == WeightingCriteria.Idf || Weighting == WeightingCriteria.TfIdf;
}
public ColInfoEx(Column item, Arguments args)
{
NgramLength = item.NgramLength ?? args.NgramLength;
Contracts.CheckUserArg(0 < NgramLength && NgramLength <= NgramBufferBuilder.MaxSkipNgramLength, nameof(item.NgramLength));
SkipLength = item.SkipLength ?? args.SkipLength;
Contracts.CheckUserArg(0 <= SkipLength && SkipLength <= NgramBufferBuilder.MaxSkipNgramLength, nameof(item.SkipLength));
if (NgramLength + SkipLength > NgramBufferBuilder.MaxSkipNgramLength)
{
throw Contracts.ExceptUserArg(nameof(item.SkipLength),
"The sum of skipLength and ngramLength must be less than or equal to {0}",
NgramBufferBuilder.MaxSkipNgramLength);
}
Contracts.CheckUserArg(Enum.IsDefined(typeof(WeightingCriteria), args.Weighting), nameof(args.Weighting));
Weighting = item.Weighting ?? args.Weighting;
NonEmptyLevels = new bool[NgramLength];
}
public ColInfoEx(ModelLoadContext ctx, bool readWeighting)
{
Contracts.AssertValue(ctx);
// *** Binary format ***
// int: NgramLength
// int: SkipLength
// int: Weighting Criteria (if readWeighting == true)
// bool[NgramLength]: NonEmptyLevels
NgramLength = ctx.Reader.ReadInt32();
Contracts.CheckDecode(0 < NgramLength && NgramLength <= NgramBufferBuilder.MaxSkipNgramLength);
SkipLength = ctx.Reader.ReadInt32();
Contracts.CheckDecode(0 <= SkipLength && SkipLength <= NgramBufferBuilder.MaxSkipNgramLength);
Contracts.CheckDecode(NgramLength <= NgramBufferBuilder.MaxSkipNgramLength - SkipLength);
if (readWeighting)
Weighting = (WeightingCriteria)ctx.Reader.ReadInt32();
Contracts.CheckDecode(Enum.IsDefined(typeof(WeightingCriteria), Weighting));
NonEmptyLevels = ctx.Reader.ReadBoolArray(NgramLength);
}
public void Save(ModelSaveContext ctx)
{
Contracts.AssertValue(ctx);
// *** Binary format ***
// int: NgramLength
// int: SkipLength
// int: Weighting Criteria
// bool[NgramLength]: NonEmptyLevels
Contracts.Assert(0 < NgramLength && NgramLength <= NgramBufferBuilder.MaxSkipNgramLength);
ctx.Writer.Write(NgramLength);
Contracts.Assert(0 <= SkipLength && SkipLength <= NgramBufferBuilder.MaxSkipNgramLength);
Contracts.Assert(NgramLength + SkipLength <= NgramBufferBuilder.MaxSkipNgramLength);
ctx.Writer.Write(SkipLength);
Contracts.Assert(Enum.IsDefined(typeof(WeightingCriteria), Weighting));
ctx.Writer.Write((int)Weighting);
Contracts.Assert(Utils.Size(NonEmptyLevels) == NgramLength);
ctx.Writer.WriteBoolBytesNoCount(NonEmptyLevels);
}
}
private const uint VerTfIdfSupported = 0x00010002;
public const string LoaderSignature = "NgramTransform";
internal const string Summary = "Produces a bag of counts of ngrams (sequences of consecutive values of length 1-n) in a given vector of keys. "
+ "It does so by building a dictionary of ngrams and using the id in the dictionary as the index in the bag.";
internal const string UserName = "NGram Transform";
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "NGRAMTRN",
// verWrittenCur: 0x00010001, // Initial
verWrittenCur: 0x00010002, // Add support for TF-IDF
verReadableCur: 0x00010002,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(NgramTransform).Assembly.FullName);
}
private readonly VectorType[] _types;
// REVIEW: The slot names types are not really needed. They are only used to "remember" which new
// columns have slot names.
private readonly VectorType[] _slotNamesTypes;
private readonly ColInfoEx[] _exes;
// These contain the ngram maps
private readonly SequencePool[] _ngramMaps;
// Ngram inverse document frequencies
private readonly double[][] _invDocFreqs;
private const string RegistrationName = "Ngram";
/// <summary>
/// Public constructor corresponding to SignatureDataTransform.
/// </summary>
public NgramTransform(IHostEnvironment env, Arguments args, IDataView input)
: base(env, RegistrationName, Contracts.CheckRef(args, nameof(args)).Column, input, TestType)
{
Host.AssertNonEmpty(Infos);
Host.Assert(Utils.Size(Infos) == Utils.Size(args.Column));
_exes = new ColInfoEx[Infos.Length];
for (int iinfo = 0; iinfo < _exes.Length; iinfo++)
_exes[iinfo] = new ColInfoEx(args.Column[iinfo], args);
_ngramMaps = Train(args, input, out _invDocFreqs);
InitColumnTypeAndMetadata(out _types, out _slotNamesTypes);
}
private NgramTransform(IHost host, ModelLoadContext ctx, IDataView input)
: base(host, ctx, input, TestType)
{
Host.AssertValue(ctx);
// *** Binary format ***
// <prefix handled in static Create method>
// <base>
// for each column
// ColInfoEx
// the ngram SequencePool
// the ngram inverse document frequencies
_exes = new ColInfoEx[Infos.Length];
_ngramMaps = new SequencePool[Infos.Length];
_invDocFreqs = new double[Infos.Length][];
for (int i = 0; i < Infos.Length; i++)
{
_exes[i] = new ColInfoEx(ctx, ctx.Header.ModelVerWritten >= VerTfIdfSupported);
_ngramMaps[i] = new SequencePool(ctx.Reader);
if (ctx.Header.ModelVerWritten >= VerTfIdfSupported)
{
_invDocFreqs[i] = ctx.Reader.ReadDoubleArray();
for (int j = 0; j < Utils.Size(_invDocFreqs[i]); j++)
Host.CheckDecode(_invDocFreqs[i][j] >= 0);
}
}
InitColumnTypeAndMetadata(out _types, out _slotNamesTypes);
}
public static NgramTransform Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
var h = env.Register(RegistrationName);
h.CheckValue(ctx, nameof(ctx));
h.CheckValue(input, nameof(input));
ctx.CheckAtModel(GetVersionInfo());
return h.Apply("Loading Model",
ch =>
{
// *** Binary format ***
// int: sizeof(Float)
// <remainder handled in ctors>
int cbFloat = ctx.Reader.ReadInt32();
ch.CheckDecode(cbFloat == sizeof(Float));
return new NgramTransform(h, ctx, input);
});
}
public override void Save(ModelSaveContext ctx)
{
Host.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel();
ctx.SetVersionInfo(GetVersionInfo());
// *** Binary format ***
// int: sizeof(Float)
// <base>
// for each added column
// ColInfoEx
// the ngram SequencePool
// the ngram inverse document frequencies
ctx.Writer.Write(sizeof(Float));
SaveBase(ctx);
var ngramsNames = default(VBuffer<ReadOnlyMemory<char>>);
for (int i = 0; i < _exes.Length; i++)
{
_exes[i].Save(ctx);
_ngramMaps[i].Save(ctx.Writer);
ctx.Writer.WriteDoubleArray(_invDocFreqs[i]);
if (_slotNamesTypes[i] != null)
{
GetSlotNames(i, ref ngramsNames);
Host.Assert(_ngramMaps[i].Count == ngramsNames.Count);
Host.Assert(ngramsNames.IsDense);
ctx.SaveTextStream(string.Format("{0}-ngrams.txt", Infos[i].Name),
writer =>
{
writer.WriteLine("# Number of Ngrams terms = {0}", ngramsNames.Count);
for (int j = 0; j < ngramsNames.Count; j++)
writer.WriteLine("{0}\t{1}", j, ngramsNames.Values[j]);
});
}
}
}
private static string TestType(ColumnType type)
{
const string reason = "Expected vector of Key type, and Key is convertable to U4";
Contracts.AssertValue(type);
if (!type.IsVector)
return reason;
if (!type.ItemType.IsKey)
return reason;
// Can only accept key types that can be converted to U4.
if (type.ItemType.KeyCount == 0 && type.ItemType.RawKind > DataKind.U4)
return reason;
return null;
}
private void InitColumnTypeAndMetadata(out VectorType[] types, out VectorType[] slotNamesTypes)
{
types = new VectorType[Infos.Length];
slotNamesTypes = new VectorType[Infos.Length];
var md = Metadata;
for (int iinfo = 0; iinfo < _exes.Length; iinfo++)
{
var vectorSize = _ngramMaps[iinfo].Count;
if (vectorSize == 0)
{
// If we the ngram map is empty, we should output the fixed-size vector of size 0. This is not a
// valid VectorType (it would be considered variable), so we make it size 1 in this case.
vectorSize = 1;
}
types[iinfo] = new VectorType(NumberType.Float, vectorSize);
var info = Infos[iinfo];
if (!Source.Schema.HasKeyNames(info.Source, info.TypeSrc.ItemType.KeyCount))
continue;
using (var bldr = md.BuildMetadata(iinfo))
{
if (_ngramMaps[iinfo].Count > 0)
{
slotNamesTypes[iinfo] = new VectorType(TextType.Instance, _ngramMaps[iinfo].Count);
bldr.AddGetter<VBuffer<ReadOnlyMemory<char>>>(MetadataUtils.Kinds.SlotNames,
slotNamesTypes[iinfo], GetSlotNames);
}
}
}
md.Seal();
}
private void GetSlotNames(int iinfo, ref VBuffer<ReadOnlyMemory<char>> dst)
{
Host.Assert(0 <= iinfo && iinfo < Infos.Length);
Host.Assert(_slotNamesTypes[iinfo] != null);
var keyCount = Infos[iinfo].TypeSrc.ItemType.KeyCount;
Host.Assert(Source.Schema.HasKeyNames(Infos[iinfo].Source, keyCount));
var unigramNames = new VBuffer<ReadOnlyMemory<char>>();
// Get the key values of the unigrams.
Source.Schema.GetMetadata(MetadataUtils.Kinds.KeyValues, Infos[iinfo].Source, ref unigramNames);
Host.Check(unigramNames.Length == keyCount);
var pool = _ngramMaps[iinfo];
var values = dst.Values;
var ngramCount = pool.Count;
if (Utils.Size(values) < ngramCount)
Array.Resize(ref values, ngramCount);
StringBuilder sb = new StringBuilder();
uint[] ngram = new uint[_exes[iinfo].NgramLength];
for (int slot = 0; slot < pool.Count; slot++)
{
var n = pool.GetById(slot, ref ngram);
Host.Assert(n >= 0);
// Get the unigrams composing the current ngram.
ComposeNgramString(ngram, n, sb, keyCount,
unigramNames.GetItemOrDefault);
values[slot] = sb.ToString().AsMemory();
}
dst = new VBuffer<ReadOnlyMemory<char>>(ngramCount, values, dst.Indices);
}
private delegate void TermGetter(int index, ref ReadOnlyMemory<char> term);
private void ComposeNgramString(uint[] ngram, int count, StringBuilder sb, int keyCount, TermGetter termGetter)
{
Host.AssertValue(sb);
Host.AssertValue(ngram);
Host.Assert(keyCount > 0);
sb.Clear();
ReadOnlyMemory<char> term = default;
string sep = "";
for (int iterm = 0; iterm < count; iterm++)
{
sb.Append(sep);
sep = "|";
var unigram = ngram[iterm];
if (unigram <= 0 || unigram > keyCount)
sb.Append("*");
else
{
termGetter((int)unigram - 1, ref term);
sb.AppendMemory(term);
}
}
}
private SequencePool[] Train(Arguments args, IDataView trainingData, out double[][] invDocFreqs)
{
// Contains the maximum number of grams to store in the dictionary, for each level of ngrams,
// from 1 (in position 0) up to ngramLength (in position ngramLength-1)
var lims = new int[Infos.Length][];
for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
{
var all = args.Column[iinfo].AllLengths ?? args.AllLengths;
var ngramLength = _exes[iinfo].NgramLength;
var maxNumTerms = Utils.Size(args.Column[iinfo].MaxNumTerms) > 0 ? args.Column[iinfo].MaxNumTerms : args.MaxNumTerms;
if (!all)
{
Host.CheckUserArg(Utils.Size(maxNumTerms) == 0 ||
Utils.Size(maxNumTerms) == 1 && maxNumTerms[0] > 0, nameof(args.MaxNumTerms));
lims[iinfo] = new int[ngramLength];
lims[iinfo][ngramLength - 1] = Utils.Size(maxNumTerms) == 0 ? Arguments.DefaultMaxTerms : maxNumTerms[0];
}
else
{
Host.CheckUserArg(Utils.Size(maxNumTerms) <= ngramLength, nameof(args.MaxNumTerms));
Host.CheckUserArg(Utils.Size(maxNumTerms) == 0 || maxNumTerms.All(i => i >= 0) && maxNumTerms[maxNumTerms.Length - 1] > 0, nameof(args.MaxNumTerms));
var extend = Utils.Size(maxNumTerms) == 0 ? Arguments.DefaultMaxTerms : maxNumTerms[maxNumTerms.Length - 1];
lims[iinfo] = Utils.BuildArray(ngramLength,
i => i < Utils.Size(maxNumTerms) ? maxNumTerms[i] : extend);
}
}
var helpers = new NgramBufferBuilder[Infos.Length];
var getters = new ValueGetter<VBuffer<uint>>[Infos.Length];
var src = new VBuffer<uint>[Infos.Length];
// Keep track of how many grams are in the pool for each value of n. Position
// i in _counts counts how many (i+1)-grams are in the pool for column iinfo.
var counts = new int[Infos.Length][];
var ngramMaps = new SequencePool[Infos.Length];
bool[] activeInput = new bool[trainingData.Schema.ColumnCount];
foreach (var info in Infos)
activeInput[info.Source] = true;
using (var cursor = trainingData.GetRowCursor(col => activeInput[col]))
using (var pch = Host.StartProgressChannel("Building n-gram dictionary"))
{
for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
{
Host.Assert(Infos[iinfo].TypeSrc.IsVector && Infos[iinfo].TypeSrc.ItemType.IsKey);
var ngramLength = _exes[iinfo].NgramLength;
var skipLength = _exes[iinfo].SkipLength;
getters[iinfo] = RowCursorUtils.GetVecGetterAs<uint>(NumberType.U4, cursor, Infos[iinfo].Source);
src[iinfo] = default(VBuffer<uint>);
counts[iinfo] = new int[ngramLength];
ngramMaps[iinfo] = new SequencePool();
// Note: GetNgramIdFinderAdd will control how many ngrams of a specific length will
// be added (using lims[iinfo]), therefore we set slotLim to the maximum
helpers[iinfo] = new NgramBufferBuilder(ngramLength, skipLength, Utils.ArrayMaxSize,
GetNgramIdFinderAdd(counts[iinfo], lims[iinfo], ngramMaps[iinfo], _exes[iinfo].RequireIdf(), Host));
}
int cInfoFull = 0;
bool[] infoFull = new bool[Infos.Length];
invDocFreqs = new double[Infos.Length][];
long totalDocs = 0;
Double rowCount = trainingData.GetRowCount(true) ?? Double.NaN;
var buffers = new VBuffer<float>[Infos.Length];
pch.SetHeader(new ProgressHeader(new[] { "Total n-grams" }, new[] { "documents" }),
e => e.SetProgress(0, totalDocs, rowCount));
while (cInfoFull < Infos.Length && cursor.MoveNext())
{
totalDocs++;
for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
{
getters[iinfo](ref src[iinfo]);
var keyCount = (uint)Infos[iinfo].TypeSrc.ItemType.KeyCount;
if (keyCount == 0)
keyCount = uint.MaxValue;
if (!infoFull[iinfo])
{
if (_exes[iinfo].RequireIdf())
helpers[iinfo].Reset();
helpers[iinfo].AddNgrams(in src[iinfo], 0, keyCount);
if (_exes[iinfo].RequireIdf())
{
int totalNgrams = counts[iinfo].Sum();
Utils.EnsureSize(ref invDocFreqs[iinfo], totalNgrams);
helpers[iinfo].GetResult(ref buffers[iinfo]);
foreach (var pair in buffers[iinfo].Items())
{
if (pair.Value >= 1)
invDocFreqs[iinfo][pair.Key] += 1;
}
}
}
AssertValid(counts[iinfo], lims[iinfo], ngramMaps[iinfo]);
}
}
pch.Checkpoint(counts.Sum(c => c.Sum()), totalDocs);
for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
{
for (int i = 0; i < Utils.Size(invDocFreqs[iinfo]); i++)
if (invDocFreqs[iinfo][i] != 0)
invDocFreqs[iinfo][i] = Math.Log(totalDocs / invDocFreqs[iinfo][i]);
}
for (int iinfo = 0; iinfo < Infos.Length; iinfo++)
{
AssertValid(counts[iinfo], lims[iinfo], ngramMaps[iinfo]);
int ngramLength = _exes[iinfo].NgramLength;
for (int i = 0; i < ngramLength; i++)
_exes[iinfo].NonEmptyLevels[i] = counts[iinfo][i] > 0;
}
return ngramMaps;
}
}
[Conditional("DEBUG")]
private void AssertValid(int[] counts, int[] lims, SequencePool pool)
{
int count = 0;
int countFull = 0;
for (int i = 0; i < lims.Length; i++)
{
Host.Assert(counts[i] >= 0);
Host.Assert(counts[i] <= lims[i]);
if (counts[i] == lims[i])
countFull++;
count += counts[i];
}
Host.Assert(count == pool.Count);
}
private static NgramIdFinder GetNgramIdFinderAdd(int[] counts, int[] lims, SequencePool pool, bool requireIdf, IHost host)
{
Contracts.AssertValue(host);
host.Assert(Utils.Size(lims) > 0);
host.Assert(Utils.Size(lims) == Utils.Size(counts));
int numFull = lims.Count(l => l <= 0);
int ngramLength = lims.Length;
return
(uint[] ngram, int lim, int icol, ref bool more) =>
{
host.Assert(0 < lim && lim <= Utils.Size(ngram));
host.Assert(lim <= Utils.Size(counts));
host.Assert(lim <= Utils.Size(lims));
host.Assert(icol == 0);
var max = lim - 1;
int slot = -1;
if (counts[max] < lims[max] && pool.TryAdd(ngram, 0, lim, out slot) && ++counts[max] >= lims[max])
numFull++;
// Note: 'slot' is either the id of the added ngram or -1. In case it is -1, find its id.
// Note: 'more' controls whether more ngrams/skip-grams should be processed in the current
// row. For IDF, as we are interested in counting the occurrence of ngrams/skip-
// grams, more should not be updated.
if (requireIdf)
return slot != -1 ? slot : pool.Get(ngram, 0, lim);
more = numFull < ngramLength;
return -1;
};
}
private NgramIdFinder GetNgramIdFinder(int iinfo)
{
return
(uint[] ngram, int lim, int icol, ref bool more) =>
{
Host.Assert(0 < lim && lim <= Utils.Size(ngram));
Host.Assert(lim <= Utils.Size(_exes[iinfo].NonEmptyLevels));
if (!_exes[iinfo].NonEmptyLevels[lim - 1])
return -1;
return _ngramMaps[iinfo].Get(ngram, 0, lim);
};
}
protected override ColumnType GetColumnTypeCore(int iinfo)
{
Host.Check(0 <= iinfo & iinfo < Infos.Length);
return _types[iinfo];
}
protected override Delegate GetGetterCore(IChannel ch, IRow input, int iinfo, out Action disposer)
{
Host.AssertValueOrNull(ch);
Host.AssertValue(input);
Host.Assert(0 <= iinfo && iinfo < Infos.Length);
Host.Assert(Infos[iinfo].TypeSrc.IsVector);
Host.Assert(Infos[iinfo].TypeSrc.ItemType.IsKey);
disposer = null;
var getSrc = RowCursorUtils.GetVecGetterAs<uint>(NumberType.U4, input, Infos[iinfo].Source);
var src = default(VBuffer<uint>);
var bldr = new NgramBufferBuilder(_exes[iinfo].NgramLength, _exes[iinfo].SkipLength,
_ngramMaps[iinfo].Count, GetNgramIdFinder(iinfo));
var keyCount = (uint)Infos[iinfo].TypeSrc.ItemType.KeyCount;
if (keyCount == 0)
keyCount = uint.MaxValue;
ValueGetter<VBuffer<Float>> del;
switch (_exes[iinfo].Weighting)
{
case WeightingCriteria.TfIdf:
Host.AssertValue(_invDocFreqs[iinfo]);
del =
(ref VBuffer<Float> dst) =>
{
getSrc(ref src);
if (!bldr.IsEmpty)
{
bldr.Reset();
bldr.AddNgrams(in src, 0, keyCount);
bldr.GetResult(ref dst);
VBufferUtils.Apply(ref dst, (int i, ref Float v) => v = (Float)(v * _invDocFreqs[iinfo][i]));
}
else
dst = new VBuffer<Float>(0, dst.Values, dst.Indices);
};
break;
case WeightingCriteria.Idf:
Host.AssertValue(_invDocFreqs[iinfo]);
del =
(ref VBuffer<Float> dst) =>
{
getSrc(ref src);
if (!bldr.IsEmpty)
{
bldr.Reset();
bldr.AddNgrams(in src, 0, keyCount);
bldr.GetResult(ref dst);
VBufferUtils.Apply(ref dst, (int i, ref Float v) => v = v >= 1 ? (Float)_invDocFreqs[iinfo][i] : 0);
}
else
dst = new VBuffer<Float>(0, dst.Values, dst.Indices);
};
break;
case WeightingCriteria.Tf:
del =
(ref VBuffer<Float> dst) =>
{
getSrc(ref src);
if (!bldr.IsEmpty)
{
bldr.Reset();
bldr.AddNgrams(in src, 0, keyCount);
bldr.GetResult(ref dst);
}
else
dst = new VBuffer<Float>(0, dst.Values, dst.Indices);
};
break;
default:
throw Host.Except("Unsupported weighting criteria");
}
return del;
}
}
}
| 43.960452
| 169
| 0.524675
|
[
"MIT"
] |
Caraul/machinelearning
|
src/Microsoft.ML.Transforms/Text/NgramTransform.cs
| 31,124
|
C#
|
using SkyMoon.Views;
using Storm.Mvvm;
namespace SkyMoon
{
public class App : MvvmApplication<SkyPage>
{
}
}
| 10.636364
| 44
| 0.709402
|
[
"MIT"
] |
Julien-Mialon/XamarinTD
|
TD-01/SkyMoon/SkyMoon/SkyMoon/App.cs
| 119
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nybus;
namespace Tests
{
public class TestClass { }
public class TestCommand : ICommand { }
public class TestEvent : IEvent { }
public class TestCommandHandler : ICommandHandler<TestCommand>
{
public Task Handle(CommandContext<TestCommand> commandMessage)
{
throw new NotImplementedException();
}
}
public class TestEventHandler : IEventHandler<TestEvent>
{
public Task Handle(EventContext<TestEvent> eventMessage)
{
throw new NotImplementedException();
}
}
}
| 21.75
| 70
| 0.668103
|
[
"MIT"
] |
Kralizek/NybusLegacyAdapter
|
tests/Tests.Nybus.Legacy.NetExtensions.Adapters/TestTypes.cs
| 698
|
C#
|
using PowerAdmin.Admin.Usecases.Profile;
using PowerAdmin.Admin.Usecases.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace PowerAdmin.Admin.Services.Interfaces
{
public interface IIdentityService
{
Task<GetProfileCase.Response> GetProfile(ClaimsPrincipal principal);
Task<PagedList<GetUsersCase.Response>> GetUsers(string? search, int pageIndex = 1, int pageSize = 10);
Task<GetUserCase.Response> GetUser(string id);
Task<CreateUserCase.Response> CreateUser(CreateUserCase.Request request);
}
}
| 28.521739
| 110
| 0.76372
|
[
"MIT"
] |
PowerReport/pa
|
pa/src/PowerAdmin.Admin/Services/Interfaces/IIdentityService.cs
| 658
|
C#
|
/**
Copyright (c) 2016 Foundation.IO (https://github.com/foundationio). All rights reserved.
This work is licensed under the terms of the BSD license.
For a copy, see <https://opensource.org/licenses/BSD-3-Clause>.
**/
namespace CodeGenerator.Models
{
using System;
using System.Collections.Generic;
[Serializable]
public class TMethod
{
public MethodCallType CallType { get; set; } = MethodCallType.None;
public string MethodName { get; set; } = "";
public string ApiMethodName { get { if (MethodName == null) return MethodName; if (!MethodName.EndsWith("Async")) return MethodName; return MethodName.Substring(0, MethodName.Length - 5); } }
public List<InputParam> InputParameters { get; set; } = new List<InputParam>();
public string OutputParameterType { get; set; } = "";
public string GetOutputParameterTypeWithModuleNamePrefix(bool isTS)
{
var item = CodeGenUtils.ModelPrefixedClassName(isTS, OutputParameterType) ?? "";
if (isTS)
{
if (item.Trim() == "")
return "Promise";
else
return "Promise<" + item + ">";
}
else
{
if (item.Trim() == "")
return "void";
else
return item;
}
}
public bool CanIgnore { get; set; }
}
}
| 34.642857
| 199
| 0.562199
|
[
"BSD-3-Clause"
] |
FoundationIO/CodeGenerator
|
Models/TMethod.cs
| 1,457
|
C#
|
//
// ClassBind.cs
//
// Author:
// JasonXuDeveloper(傑) <jasonxudeveloper@gmail.com>
//
// Copyright (c) 2020 JEngine
//
// 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 libx;
using System;
using System.ComponentModel;
using Malee.List;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.Runtime.Intepreter;
using ProjectAdapter;
using UnityEngine;
using Component = UnityEngine.Component;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif
namespace JEngine.Core
{
[HelpURL("https://github.com/JasonXuDeveloper/JEngine/wiki/%e4%bb%a3%e7%a0%81%e7%bb%91%e5%ae%9a")]
public class ClassBind : MonoBehaviour
{
public _ClassBind[] ScriptsToBind = new _ClassBind[1];
/// <summary>
/// Set value
/// </summary>
/// <param name="_class"></param>
public void SetVal(_ClassBind _class)
{
string classType = $"{_class.Namespace + (_class.Namespace == "" ? "" : ".")}{_class.Class}";
IType type = Init.appdomain.LoadedTypes[classType];
Type t = type.ReflectionType;//获取实际属性
var clrInstance = this.gameObject.GetComponents<MonoBehaviourAdapter.Adaptor>()
.Last(clr => clr.ILInstance.Type == type as ILType);
//绑定数据
if (_class.RequireBindFields)
{
_class.BoundData = false;
var fields = _class.Fields.ToArray();
foreach (_ClassField field in fields)
{
object obj = new object();
try
{
if (field.fieldType == _ClassField.FieldType.Short)
{
obj = int.Parse(field.value);
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.UShort)
{
obj = ushort.Parse(field.value);
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.Int)
{
obj = short.Parse(field.value);
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.UInt)
{
obj = uint.Parse(field.value);
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.Long)
{
obj = long.Parse(field.value);
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.ULong)
{
obj = ulong.Parse(field.value);
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.Float)
{
obj = float.Parse(field.value);
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.Decimal)
{
obj = decimal.Parse(field.value);
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.Double)
{
obj = Double.Parse(field.value);
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.String)
{
obj = field.value;
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.Bool)
{
field.value = field.value.ToLower();
obj = field.value == "true";
_class.BoundData = true;
}
if (field.fieldType == _ClassField.FieldType.GameObject)
{
GameObject go = field.gameObject;
if (go == null)
{
try
{
go = field.value == "${this}"
? this.gameObject
: GameObject.Find(field.value);
if (go == null) //找父物体
{
go = FindSubGameObject(field);
if (go == null) //如果父物体还不存在
{
continue;
}
}
}
catch (Exception ex) //找父物体(如果抛出空异常)
{
go = FindSubGameObject(field);
if (go == null) //如果父物体还不存在
{
continue;
}
}
}
obj = go;
_class.BoundData = true;
}
else if (field.fieldType == _ClassField.FieldType.UnityComponent)
{
GameObject go = field.gameObject;
if (go == null)
{
try
{
if (field.value.Contains("."))
{
field.value =
field.value.Remove(field.value.IndexOf(".", StringComparison.Ordinal));
}
go = field.value == "${this}"
? this.gameObject
: GameObject.Find(field.value);
if (go == null) //找父物体
{
go = FindSubGameObject(field);
if (go == null) //如果父物体还不存在
{
continue;
}
}
}
catch (Exception ex) //找父物体(如果抛出空异常)
{
go = FindSubGameObject(field);
if (go == null) //如果父物体还不存在
{
continue;
}
}
}
var tp = t.GetField(field.fieldName,
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.Static);
if (tp != null)
{
string tName = tp.FieldType.Name;
if (tp.FieldType.Assembly.ToString().Contains("ILRuntime")) //如果在热更中
{
var components = go.GetComponents<MonoBehaviourAdapter.Adaptor>();
foreach (var c in components)
{
if (c.ILInstance.Type.Name == tName)
{
obj = c.ILInstance;
_class.BoundData = true;
break;
}
}
}
else
{
var component = go.GetComponents<Component>().ToList()
.Find(c => c.GetType().ToString().Contains(tName));
if (component != null)
{
obj = component;
_class.BoundData = true;
}
}
}
else
{
var pi = t.GetProperty(field.fieldName,
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.Static);
if (pi != null)
{
string tName = pi.PropertyType.Name;
if (pi.PropertyType.Assembly.ToString().Contains("ILRuntime")) //如果在热更中
{
var components = go.GetComponents<MonoBehaviourAdapter.Adaptor>();
foreach (var c in components)
{
if (c.ILInstance.Type.Name == tName)
{
obj = c.ILInstance;
_class.BoundData = true;
break;
}
}
}
else
{
var component = go.GetComponents<Component>().ToList()
.Find(c => c.GetType().ToString().Contains(tName));
if (component != null)
{
obj = component;
_class.BoundData = true;
}
}
}
else
{
Log.PrintError($"自动绑定{this.name}出错:{classType}.{field.fieldName}赋值出错:{field.fieldName}不存在");
}
}
}
else if (field.fieldType == _ClassField.FieldType.HotUpdateResource)
{
obj = Assets.LoadAsset(field.value, typeof(UnityEngine.Object)).asset;
_class.BoundData = true;
}
}
catch (Exception except)
{
Log.PrintError(
$"自动绑定{this.name}出错:{classType}.{field.fieldName}获取值{field.value}出错:{except.Message},已跳过");
}
//如果有数据再绑定
if (_class.BoundData)
{
var fi = t.GetField(field.fieldName,
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.Static);
if (fi != null)
{
try
{
fi.SetValue(clrInstance.ILInstance, obj);
}
catch (Exception e)
{
Log.PrintError(
$"自动绑定{this.name}出错:{classType}.{field.fieldName}赋值出错:{e.Message},已跳过");
}
}
else
{
//没FieldInfo尝试PropertyInfo
var pi = t.GetProperty(field.fieldName,
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.Static);
if (pi != null)
{
pi.SetValue(clrInstance.ILInstance, obj);
}
else
{
Log.PrintError($"自动绑定{this.name}出错:{classType}不存在{field.fieldName},已跳过");
}
}
}
}
}
}
/// <summary>
/// Active
/// </summary>
/// <param name="_class"></param>
public void Active(_ClassBind _class)
{
string classType = $"{_class.Namespace + (_class.Namespace == "" ? "" : ".")}{_class.Class}";
IType type = Init.appdomain.LoadedTypes[classType];
Type t = type.ReflectionType;//获取实际属性
var clrInstance = this.gameObject.GetComponents<MonoBehaviourAdapter.Adaptor>()
.Last(clr => clr.ILInstance.Type == type as ILType);
//是否激活
if (_class.ActiveAfter)
{
if (_class.BoundData == false && _class.RequireBindFields && _class.Fields.Count > 0)
{
Log.PrintError($"自动绑定{this.name}出错:{classType}没有成功绑定数据,自动激活成功,但可能会抛出空异常!");
}
clrInstance.enabled = true;
clrInstance.Awake();
_class.Activated = true;
}
Remove();
}
/// <summary>
/// Remove cb
/// </summary>
public void Remove()
{
//添加后删除
Destroy(this);
}
/// <summary>
/// Add class
/// </summary>
/// <param name="_class"></param>
/// <returns></returns>
public string AddClass(_ClassBind _class)
{
//添加脚本
string classType = $"{_class.Namespace + (_class.Namespace == "" ? "" : ".")}{_class.Class}";
if (!Init.appdomain.LoadedTypes.ContainsKey(classType))
{
Log.PrintError($"自动绑定{this.name}出错:{classType}不存在,已跳过");
return null;
}
IType type = Init.appdomain.LoadedTypes[classType];
Type t = type.ReflectionType;//获取实际属性
var instance = _class.UseConstructor
? Init.appdomain.Instantiate(classType)
: new ILTypeInstance(type as ILType, false);
//JBehaviour需自动赋值一个值
var JBehaviourType = Init.appdomain.LoadedTypes["JEngine.Core.JBehaviour"];
bool isJBehaviour = t.IsSubclassOf(JBehaviourType.ReflectionType);
bool isMono = t.IsSubclassOf(typeof(MonoBehaviour));
if (_class.UseConstructor && isMono)
{
JEngine.Core.Log.PrintWarning($"{t.FullName}由于带构造函数生成,会有来自Unity的警告,请忽略");
}
var clrInstance = this.gameObject.AddComponent<MonoBehaviourAdapter.Adaptor>();
clrInstance.enabled = false;
clrInstance.ILInstance = instance;
clrInstance.AppDomain = Init.appdomain;
if (isMono)
{
instance.CLRInstance = clrInstance;
}
else
{
instance.CLRInstance = instance;
}
//判断类型
clrInstance.isMonoBehaviour = isMono;
if (isJBehaviour)
{
clrInstance.isJBehaviour = true;
var go = t.GetField("_gameObject",BindingFlags.Public);
go.SetValue(clrInstance.ILInstance, this.gameObject);
}
_class.Added = true;
//JBehaviour返回实例ID
if (isJBehaviour)
{
var f = t.GetField("_instanceID", BindingFlags.NonPublic);
var id = f.GetValue(clrInstance.ILInstance).ToString();
return id;
}
return null;
}
private GameObject FindSubGameObject(_ClassField field)
{
if (field.value.Contains("/")) //如果有父级
{
try
{
var parent =
GameObject.Find(field.value.Substring(0,
field.value.IndexOf('/'))); //寻找父物体
var go = parent.transform
.Find(field.value.Substring(field.value.IndexOf('/') + 1))
.gameObject;
return go;
}
catch
{
Log.PrintError($"自动绑定{this.name}出错:{field.value}对象被隐藏或不存在,无法获取,已跳过");
}
}
else
{
Log.PrintError($"自动绑定{this.name}出错:{field.value}对象被隐藏或不存在,无法获取,已跳过");
}
return null;
}
#if UNITY_EDITOR
[ContextMenu("Convert Path to GameObject")]
private void Convert()
{
foreach (_ClassBind _class in ScriptsToBind)
{
Log.Print(
$"<color=#34ebc9>==========Start processing {_class.Namespace}.{_class.Class}==========</color>");
var fields = _class.Fields.ToArray();
foreach (_ClassField field in fields)
{
if (field.fieldType == _ClassField.FieldType.GameObject ||
field.fieldType == _ClassField.FieldType.UnityComponent)
{
if (!string.IsNullOrEmpty(field.value))
{
if (field.value.Contains("."))
{
field.value =
field.value.Remove(field.value.IndexOf(".", StringComparison.Ordinal));
}
GameObject go = field.gameObject;
try
{
go = field.value == "${this}"
? this.gameObject
: GameObject.Find(field.value);
if (go == null) //找父物体
{
go = FindSubGameObject(field);
}
}
catch (Exception ex) //找父物体(如果抛出空异常)
{
go = FindSubGameObject(field);
}
if (go != null)
{
field.gameObject = go;
Log.Print(
$"Convert path {field.value} to GameObject <color=green>successfully</color>");
field.value = "";
}
else
{
Log.PrintError(
$"Convert path {field.value} to GameObject failed: path does not exists");
}
}
}
}
Log.Print(
$"<color=#34ebc9>==========Finish processing {_class.Namespace}.{_class.Class}==========</color>");
}
//转换后保存场景
var scene = EditorSceneManager.GetActiveScene();
bool saveResult = EditorSceneManager.SaveScene(scene,scene.path);
Debug.Log("Saved Scene " + scene.path + " " +(saveResult ? "Success" : "Failed!"));
}
#endif
}
[System.Serializable]
public class _ClassBind
{
public string Namespace = "HotUpdateScripts";
public string Class = "";
public bool ActiveAfter = false;
public bool RequireBindFields = false;
[Tooltip("是否使用构造函数")]
public bool UseConstructor = true;
[Tooltip("如果是GameObject,请填写完整路径,如果没有父物体,请务必为Active,如果有父物体,请确保父物体是Active;\r\n" +
"如果是Unity脚本,请填写该脚本所属的GameObject完整路径,参考GameObject写法")]
[Reorderable(elementNameProperty = "fieldName")]
public FieldList Fields;
public bool BoundData { get; set; } = false;
public bool Added { get; set; } = false;
public bool Activated { get; set; } = false;
}
[System.Serializable]
public class _ClassField
{
public enum FieldType
{
Short,
UShort,
Int,
UInt,
Long,
ULong,
Float,
Decimal,
Double,
String,
Bool,
GameObject,
UnityComponent,
HotUpdateResource
}
public FieldType fieldType;
[Tooltip("需要赋值的键的名字")] public string fieldName;
[Header("For Normal Value and Hot Update Resource Field Type")]
[Tooltip("非GameObject和UnityComponent的fieldType的值")]
public string value;
[Header("For GameObject or Unity Component Field Type")]
[Tooltip("如果fieldType是GameObject或UnityComponent,此处可填,否则无效")]
public GameObject gameObject;
}
[System.Serializable]
public class FieldList : ReorderableArray<_ClassField>
{
}
}
| 41.465035
| 128
| 0.391812
|
[
"MIT"
] |
forget-myself/JEngine
|
UnityProject/Assets/Dependencies/JEngine/Core/ClassBind.cs
| 24,640
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptTriggerController : MonoBehaviour
{
public string scriptContent = "Script Stem";
}
| 23.25
| 52
| 0.801075
|
[
"Apache-2.0"
] |
MLH-Fellowship/red-panda
|
Assets/Scripts/ScriptTriggerController.cs
| 188
|
C#
|
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
namespace uFlex
{
public class FlexDiffuseParticles : MonoBehaviour
{
public int m_diffuseParticlesCount = 0;
public int m_maxDiffuseParticlesCount = 0;
[HideInInspector]
public Vector4[] m_diffuseParticles;
[HideInInspector]
public Vector4[] m_diffuseVelocities;
[HideInInspector]
public int[] m_sortedDepth;
/*
/// <summary>
/// Particles with kinetic energy + divergence above this threshold will spawn new diffuse particles.
/// </summary>
[Tooltip("Particles with kinetic energy + divergence above this threshold will spawn new diffuse particles.")]
public float m_DiffuseThreshold = 100.0f;
/// <summary>
/// Scales force opposing gravity that diffuse particles receive.
/// </summary>
[Tooltip("Scales force opposing gravity that diffuse particles receive.")]
public float m_DiffuseBuoyancy = 0.0f;
/// <summary>
/// Scales force diffuse particles receive in direction of neighbor fluid particles.
/// </summary>
[Tooltip("Scales force diffuse particles receive in direction of neighbor fluid particles.")]
public float m_DiffuseDrag = 0.0f;
/// <summary>
/// The number of neighbors below which a diffuse particle is considered ballistic.
/// </summary>
[Tooltip("The number of neighbors below which a diffuse particle is considered ballistic.")]
public int m_DiffuseBallistic = 16;
/// <summary>
/// Diffuse particles will be sorted by depth along this axis if non-zero.
/// </summary>
[Tooltip("Diffuse particles will be sorted by depth along this axis if non-zero.")]
public Vector3 m_DiffuseSortAxis = new Vector3(0, 0, 0);
/// <summary>
/// Time in seconds that a diffuse particle will live for after being spawned, particles will be spawned with a random lifetime in the range [0, mDiffuseLifetime].
/// </summary>
[Tooltip("Time in seconds that a diffuse particle will live for after being spawned, particles will be spawned with a random lifetime in the range [0, mDiffuseLifetime].")]
public float m_DiffuseLifetime = 2.0f;
*/
public GCHandle m_diffuseParticlesHndl;
public GCHandle m_diffuseVelocitiesHndl;
public GCHandle m_sortedDepthHndl;
void Awake()
{
m_diffuseParticles = new Vector4[m_maxDiffuseParticlesCount];
m_diffuseVelocities = new Vector4[m_maxDiffuseParticlesCount];
m_sortedDepth = new int[m_maxDiffuseParticlesCount];
m_diffuseParticlesHndl = GCHandle.Alloc(m_diffuseParticles, GCHandleType.Pinned);
m_diffuseVelocitiesHndl = GCHandle.Alloc(m_diffuseVelocities, GCHandleType.Pinned);
m_sortedDepthHndl = GCHandle.Alloc(m_sortedDepth, GCHandleType.Pinned);
}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnApplicationQuit()
{
//free pinned arrays
m_diffuseParticlesHndl.Free();
m_diffuseVelocitiesHndl.Free();
m_sortedDepthHndl.Free();
}
}
}
| 35.43299
| 180
| 0.644457
|
[
"MIT"
] |
DavidAzouz29/FleXFoamUnity
|
Assets/uFlex/Scripts/Solver/FlexDiffuseParticles.cs
| 3,439
|
C#
|
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Harmony;
namespace NoAurora
{
[HarmonyPatch(typeof(LargeWorldEntity), nameof(LargeWorldEntity.OnEnable))]
public class EntityCellPatch
{
public static void Postfix(LargeWorldEntity __instance)
{
foreach(Renderer rend in __instance.fadeRenderers)
{
ErrorMessage.AddMessage($"Destroying {rend.name}");
Object.Destroy(rend);
}
}
}
}
| 25.52381
| 79
| 0.641791
|
[
"Apache-2.0"
] |
EckoTheBat/SubnauticaMods
|
NoAurora/EntityCellPatch.cs
| 538
|
C#
|
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/* SubFieldCollection.cs -- коллекция подполей
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
* Status: poor
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using AM;
using AM.IO;
using AM.Logging;
using AM.Runtime;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
#endregion
namespace ManagedIrbis
{
/// <summary>
/// Коллекция подполей.
/// Отличается тем, что принципиально не принимает
/// значения <c>null</c>.
/// </summary>
[PublicAPI]
[Serializable]
[XmlRoot("subfields")]
[DebuggerDisplay("Count={" + nameof(Count) + "}")]
public sealed class SubFieldCollection
: Collection<SubField>,
IHandmadeSerializable,
IReadOnly<SubFieldCollection>
{
#region Properties
/// <summary>
/// Field.
/// </summary>
[CanBeNull]
[XmlIgnore]
[JsonIgnore]
public RecordField Field { get { return _field; } }
#endregion
#region Construction
#endregion
#region Private members
// ReSharper disable InconsistentNaming
[NonSerialized]
private RecordField _field;
[ExcludeFromCodeCoverage]
internal SubFieldCollection _SetField
(
RecordField newField
)
{
_field = newField;
foreach (SubField subField in this)
{
subField.Field = newField;
}
return this;
}
// ReSharper restore InconsistentNaming
internal void SetModified()
{
if (!ReferenceEquals(Field, null))
{
Field.SetModified();
}
}
#endregion
#region Public methods
/// <summary>
/// Добавление в коллекцию нескольких подполей сразу
/// </summary>
[NotNull]
public SubFieldCollection AddRange
(
[NotNull] IEnumerable<SubField> subFields
)
{
Sure.NotNull(subFields, nameof(subFields));
ThrowIfReadOnly();
foreach (SubField subField in subFields)
{
Add(subField);
}
return this;
}
/// <summary>
/// Assign.
/// </summary>
[NotNull]
public SubFieldCollection Assign
(
[NotNull] SubFieldCollection other
)
{
ThrowIfReadOnly();
Sure.NotNull(other, nameof(other));
Clear();
_field = other.Field;
AddRange(other);
return this;
}
/// <summary>
/// Assign clone.
/// </summary>
[NotNull]
public SubFieldCollection AssignClone
(
[NotNull] SubFieldCollection other
)
{
ThrowIfReadOnly();
Sure.NotNull(other, nameof(other));
Clear();
_field = other.Field;
foreach (SubField subField in other)
{
Add(subField.Clone());
}
return this;
}
/// <summary>
/// Создание "глубокой" копии коллекции.
/// </summary>
[NotNull]
public SubFieldCollection Clone()
{
SubFieldCollection result = new SubFieldCollection
{
_field = Field
};
foreach (SubField subField in this)
{
SubField clone = subField.Clone();
clone.Field = Field;
result.Add(clone);
}
return result;
}
/// <summary>
/// Поиск с помощью предиката.
/// </summary>
[CanBeNull]
public SubField Find
(
[NotNull] Predicate<SubField> predicate
)
{
Sure.NotNull(predicate, nameof(predicate));
return this
.FirstOrDefault
(
subField => predicate(subField)
);
}
/// <summary>
/// Отбор с помощью предиката.
/// </summary>
[NotNull]
public SubField[] FindAll
(
[NotNull] Predicate<SubField> predicate
)
{
Sure.NotNull(predicate, nameof(predicate));
return this
.Where(subField => predicate(subField))
.ToArray();
}
/// <summary>
/// Restore the collection from JSON.
/// </summary>
[NotNull]
public static SubFieldCollection FromJson
(
[NotNull] string text
)
{
Sure.NotNullNorEmpty(text, nameof(text));
SubFieldCollection result = JsonConvert.DeserializeObject<SubFieldCollection>
(
text
);
return result;
}
/// <summary>
/// Convert the collection to JSON.
/// </summary>
[NotNull]
public string ToJson()
{
string result = JArray.FromObject(this).ToString();
return result;
}
#endregion
#region Collection<T> members
/// <inheritdoc cref="Collection{T}.ClearItems" />
protected override void ClearItems()
{
ThrowIfReadOnly();
foreach (SubField subField in this)
{
subField.Field = null;
}
SetModified();
base.ClearItems();
}
/// <inheritdoc cref="Collection{T}.InsertItem" />
protected override void InsertItem
(
int index,
SubField item
)
{
ThrowIfReadOnly();
Sure.NotNull(item, nameof(item));
item.Field = Field;
SetModified();
base.InsertItem(index, item);
}
/// <inheritdoc cref="Collection{T}.RemoveItem" />
protected override void RemoveItem
(
int index
)
{
ThrowIfReadOnly();
if (index >= 0 && index < Count)
{
SubField subField = this[index];
if (subField != null)
{
subField.Field = null;
}
SetModified();
}
base.RemoveItem(index);
}
/// <inheritdoc cref="Collection{T}.SetItem" />
protected override void SetItem
(
int index,
SubField item
)
{
ThrowIfReadOnly();
Sure.NotNull(item, nameof(item));
item.Field = Field;
SetModified();
base.SetItem(index, item);
}
#endregion
#region IHandmadeSerializable members
/// <inheritdoc cref= "IHandmadeSerializable.RestoreFromStream" />
public void RestoreFromStream
(
BinaryReader reader
)
{
ThrowIfReadOnly();
Sure.NotNull(reader, nameof(reader));
ClearItems();
SubField[] array = reader.ReadArray<SubField>();
AddRange(array);
}
/// <inheritdoc cref="IHandmadeSerializable.SaveToStream" />
public void SaveToStream
(
BinaryWriter writer
)
{
Sure.NotNull(writer, nameof(writer));
writer.WriteArray(this.ToArray());
}
#endregion
#region IReadOnly<T> members
// ReSharper disable InconsistentNaming
//[NonSerialized]
internal bool _readOnly;
/// <inheritdoc cref="IReadOnly{T}.ReadOnly" />
public bool ReadOnly { get { return _readOnly; } }
// ReSharper restore InconsistentNaming
/// <inheritdoc cref="IReadOnly{T}.AsReadOnly" />
public SubFieldCollection AsReadOnly()
{
SubFieldCollection result = Clone();
result.SetReadOnly();
return result;
}
/// <inheritdoc cref="IReadOnly{T}.ThrowIfReadOnly" />
public void ThrowIfReadOnly()
{
if (ReadOnly)
{
Log.Error
(
"SubFieldCollection::ThrowIfReadOnly"
);
throw new ReadOnlyException();
}
}
/// <inheritdoc cref="IReadOnly{T}.SetReadOnly" />
public void SetReadOnly()
{
_readOnly = true;
foreach (SubField subField in this)
{
subField.SetReadOnly();
}
}
#endregion
}
}
| 23.277916
| 89
| 0.485023
|
[
"MIT"
] |
amironov73/ManagedIrbis2
|
OldSource/Libs/ManagedIrbis/Source/SubFieldCollection.cs
| 9,582
|
C#
|
using DataAccess.Abstract;
using Entities.Concrete;
using Entities.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace DataAccess.Concrete.InMemory
{
public class InMemoryCarDal:ICarDal
{
List<Car> _cars;
public InMemoryCarDal()//constructor-ctor-
{
_cars = new List<Car>
{
new Car {Id=1, BrandId=20, ColorId=10, ModelYear=2020, DailyPrice=250, Description="Auid"},
new Car {Id=2, BrandId=21, ColorId=11, ModelYear=2002, DailyPrice=100, Description="BMW"},
new Car {Id=3, BrandId=22, ColorId=12, ModelYear=2010, DailyPrice=120, Description="Mercedes"},
new Car {Id=4, BrandId=23, ColorId=13, ModelYear=2016, DailyPrice=150, Description="Opel"},
new Car {Id=5, BrandId=24, ColorId=14, ModelYear=2008, DailyPrice=110, Description="Seat"},
};
}
public void Add(Car car)
{
_cars.Add(car);
}
public void Delete(Car car)
{
Car carDelete = _cars.SingleOrDefault(c=>c.Id==car.Id); //Tek Tek dolaşma için foreach yerine
_cars.Remove(carDelete);
}
public void Update(Car car)
{
Car carUpdate = _cars.SingleOrDefault(c => c.Id == car.Id);
carUpdate.BrandId = car.BrandId;
carUpdate.ColorId = car.ColorId;
carUpdate.ModelYear = car.ModelYear;
carUpdate.DailyPrice = car.DailyPrice;
carUpdate.Description = car.Description;
}
public List<Car> GetAll()
{
return _cars;
}
public List<Car> GetById(int carId)
{
return _cars.Where(c=>c.Id==carId).ToList();
}
public List<Car> GetAll(Expression<Func<Car, bool>> filter = null)
{
throw new NotImplementedException();
}
public Car Get(Expression<Func<Car, bool>> filter)
{
throw new NotImplementedException();
}
public List<CarDetailDto> GetCarDetailDtos()
{
throw new NotImplementedException();
}
}
}
| 30.712329
| 111
| 0.576271
|
[
"MIT"
] |
Sena-Sakalli/ReCapProject
|
ReCapProject/DataAccess/Concrete/InMemory/InMemoryCarDal.cs
| 2,246
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.269
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ClearCanvas.Dicom.Network {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class SR {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal SR() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ClearCanvas.Dicom.Network.SR", typeof(SR).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to The message was not understood..
/// </summary>
internal static string CannotUnderstand {
get {
return ResourceManager.GetString("CannotUnderstand", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A duplicate SOP Instance could not be processed..
/// </summary>
internal static string DuplicateSOPInstance {
get {
return ResourceManager.GetString("DuplicateSOPInstance", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Some instances of this study are not supported by the remote application. See log for more details..
/// </summary>
internal static string ErrorSendSopClassNotSupported {
get {
return ResourceManager.GetString("ErrorSendSopClassNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected failure reported by the printer..
/// </summary>
internal static string MessagePrinterError {
get {
return ResourceManager.GetString("MessagePrinterError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A failure occurred due to a missing DICOM attribute..
/// </summary>
internal static string MissingAttribute {
get {
return ResourceManager.GetString("MissingAttribute", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The remote server is out of resources..
/// </summary>
internal static string OutOfResources {
get {
return ResourceManager.GetString("OutOfResources", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A failure occurred while processing..
/// </summary>
internal static string ProcessingFailure {
get {
return ResourceManager.GetString("ProcessingFailure", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Retrieve failed due to the remote application not being able to reach your computer, possibly due to misconfiguration..
/// </summary>
internal static string QueryRetrieveMoveDestinationUnknown {
get {
return ResourceManager.GetString("QueryRetrieveMoveDestinationUnknown", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The remote server was unable to process the request..
/// </summary>
internal static string UnableToProcess {
get {
return ResourceManager.GetString("UnableToProcess", resourceCulture);
}
}
}
}
| 41.986207
| 173
| 0.575066
|
[
"Apache-2.0"
] |
SNBnani/Xian
|
Dicom/Network/SR.Designer.cs
| 6,090
|
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.AzureNative.RecoveryServices.V20210601.Inputs
{
/// <summary>
/// Details about inquired protectable items under a given container.
/// </summary>
public sealed class InquiryInfoArgs : Pulumi.ResourceArgs
{
[Input("inquiryDetails")]
private InputList<Inputs.WorkloadInquiryDetailsArgs>? _inquiryDetails;
/// <summary>
/// Inquiry Details which will have workload specific details.
/// For e.g. - For SQL and oracle this will contain different details.
/// </summary>
public InputList<Inputs.WorkloadInquiryDetailsArgs> InquiryDetails
{
get => _inquiryDetails ?? (_inquiryDetails = new InputList<Inputs.WorkloadInquiryDetailsArgs>());
set => _inquiryDetails = value;
}
/// <summary>
/// Inquiry Status for this container such as
/// InProgress | Failed | Succeeded
/// </summary>
[Input("status")]
public Input<string>? Status { get; set; }
public InquiryInfoArgs()
{
}
}
}
| 32.255814
| 109
| 0.645278
|
[
"Apache-2.0"
] |
polivbr/pulumi-azure-native
|
sdk/dotnet/RecoveryServices/V20210601/Inputs/InquiryInfoArgs.cs
| 1,387
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Player : Character
{
//health
[SerializeField] bool regenerateHealth = true;
[SerializeField] float healthRegenerateTime;
[SerializeField, Range(0f,1f)] float healthRegeneratePercent;
[SerializeField] StatsBar_HUD statsBar_HUD;
//audio
[Header("Audio")]
[SerializeField] AudioClip projectileSFX;
[SerializeField] float projectileSFXVolume = 0.4f;
// Start is called before the first frame update
[Header("input")]
[SerializeField] PlayerInput input;
//move
[Header("Move")]
[SerializeField] float moveSpeed = 10f;
[SerializeField] float paddingX = 0.2f;
[SerializeField] float paddingY = 0.2f;
[SerializeField] float accelerationTime = 0.5f;
[SerializeField] float decelerationTime = 0.5f;
[SerializeField] float moveRotationAngle = 50f;
//fire
[Header("Fire")]
[SerializeField] GameObject projectile;
[SerializeField] GameObject projectile1;
[SerializeField] GameObject projectile2;
[SerializeField] Transform muzzleMiddle;
[SerializeField] Transform muzzleTop;
[SerializeField] Transform muzzleBottom;
[SerializeField, Range(0,2)] int weaponPower = 0;
[SerializeField] float fireInterval = 0.2f;
WaitForSeconds waiteForFireInterval;
WaitForSeconds waitHealthRegenerateTime;
new Rigidbody2D rigidbody;
Coroutine moveCoroutine;
Coroutine healthRegenerateCoroutine;
void Awake(){
rigidbody = GetComponent<Rigidbody2D>();
}
protected override void OnEnable() {
base.OnEnable();
input.onMove += Move;
input.onStopMove += StopMove;
input.onFire += Fire;
input.onStopFire +=StopFire;
}
void OnDisable() {
input.onMove -= Move;
input.onStopMove -= StopMove;
input.onFire -= Fire;
input.onStopFire -=StopFire;
}
void Start()
{
rigidbody.gravityScale = 0f;
waiteForFireInterval = new WaitForSeconds(fireInterval);
waitHealthRegenerateTime = new WaitForSeconds(healthRegenerateTime);
//health
statsBar_HUD.Init(health,maxHealth);
input.EnableGameplayInput();
}
//override
//take damage
public override void TakeDamage(float damage){
base.TakeDamage(damage);
statsBar_HUD.UpdateStats(health,maxHealth);
if(gameObject.activeSelf){
if(regenerateHealth){
if(healthRegenerateCoroutine!=null){
StopCoroutine(healthRegenerateCoroutine);
}
healthRegenerateCoroutine = StartCoroutine(HealthRegenerateCoroutine(waitHealthRegenerateTime,healthRegeneratePercent));
}
}
}
//override
//restore health
public override void RestoreHealth(float value){
base.RestoreHealth(value);
statsBar_HUD.UpdateStats(health,maxHealth);
}
//override
//die
public override void Die(){
GameManager.onGameOver?.Invoke();
GameManager.GameState = GameState.GameOver;
statsBar_HUD.UpdateStats(0f,maxHealth);
base.Die();
}
//move
// Update is called once per frame
void Move(Vector2 moveInput){
//Vector2 moveAmount = moveInput * moveSpeed;
//rigidbody.velocity = moveInput * moveSpeed;
if(moveCoroutine!=null){
StopCoroutine(moveCoroutine);
}
//add rotation angle
Quaternion moveRotation = Quaternion.AngleAxis(moveRotationAngle * moveInput.y, Vector3.right);
moveCoroutine = StartCoroutine(MoveCoroutine(accelerationTime,moveInput.normalized * moveSpeed, moveRotation));
StartCoroutine(nameof(MovePositionLimitCoroutine));
}
void StopMove(){
//rigidbody.velocity = Vector2.zero;
if(moveCoroutine!=null){
StopCoroutine(moveCoroutine);
}
moveCoroutine = StartCoroutine(MoveCoroutine(decelerationTime,Vector2.zero,Quaternion.identity));
StopCoroutine(nameof(MovePositionLimitCoroutine));
}
IEnumerator MovePositionLimitCoroutine(){
while(true){
transform.position = Viewport.Instance.PlayerMoveablePosition(transform.position, paddingX, paddingY);
yield return null;
}
}
IEnumerator MoveCoroutine(float time, Vector2 moveVelovity,Quaternion moveRotation){
float t = 0f;
Vector2 previousVelocity = rigidbody.velocity;
Quaternion previousRotation = transform.rotation;
while(t < 1f){
t += Time.fixedDeltaTime / time;
rigidbody.velocity = Vector2.Lerp(previousVelocity, moveVelovity, t);
//rotation
transform.rotation = Quaternion.Lerp(previousRotation, moveRotation, t);
yield return new WaitForFixedUpdate();
}
}
//fire
void Fire(){
StartCoroutine(nameof(FireCoroutine));
}
void StopFire(){
StopCoroutine(nameof(FireCoroutine));
}
IEnumerator FireCoroutine(){
while(true){
switch (weaponPower)
{
case 0:
PoolManager.Release(projectile,muzzleMiddle.position);
break;
case 1:
PoolManager.Release(projectile1,muzzleTop.position);
PoolManager.Release(projectile2,muzzleBottom.position);
break;
case 2:
PoolManager.Release(projectile1,muzzleTop.position);
PoolManager.Release(projectile,muzzleMiddle.position);
PoolManager.Release(projectile2,muzzleBottom.position);
break;
default:
break;
}
//audio
AudioManager.Instance.PlaySFX(projectileSFX,projectileSFXVolume);
//fire interval
yield return waiteForFireInterval;
}
}
}
| 29.86385
| 137
| 0.608867
|
[
"MIT"
] |
wbc277072080/ThunderSpace
|
ThunderSpace/Assets/Scripts/Characters/Player/Player.cs
| 6,361
|
C#
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DispatcherExtensions.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#if !XAMARIN
namespace Catel.Windows.Threading
{
using System;
using System.Threading.Tasks;
// Required for DispatcherOperation on all platforms
using System.Windows.Threading;
#if NETFX_CORE
using Dispatcher = global::Windows.UI.Core.CoreDispatcher;
#endif
/// <summary>
/// Extension methods for the dispatcher.
/// </summary>
public static partial class DispatcherExtensions
{
#if !NETFX_CORE
/// <summary>
/// Executes the specified action asynchronously with the specified arguments on the thread that the Dispatcher was created on.
/// </summary>
/// <param name="dispatcher">The dispatcher.</param>
/// <param name="action">The action.</param>
/// <returns>The DispatcherOperation or <c>null</c> if the action was not dispatched but executed directly.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="action" /> is <c>null</c>.</exception>
/// <remarks>For target frameworks where the <see cref="Dispatcher" /> class does not contain the <c>Invoke</c> method, the <c>BeginInvoke</c>
/// method will be used instead.</remarks>
public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action action)
{
return BeginInvoke(dispatcher, action, false);
}
/// <summary>
/// Executes the specified delegate asynchronously with the specified arguments on the thread that the Dispatcher was created on.
/// </summary>
/// <param name="dispatcher">The dispatcher.</param>
/// <param name="method">A delegate to a method that takes parameters specified in args, which is pushed onto the Dispatcher event queue.</param>
/// <param name="args">An array of objects to pass as arguments to the given method. Can be <c>null</c>.</param>
/// <returns>The DispatcherOperation or <c>null</c> if the action was not dispatched but executed directly.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="method" /> is <c>null</c>.</exception>
public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Delegate method, params object[] args)
{
Argument.IsNotNull("method", method);
return BeginInvoke(dispatcher, () => method.DynamicInvoke(args), false);
}
#endif
/// <summary>
/// Executes the specified action asynchronously with the specified arguments on the thread that the Dispatcher was created on if required.
/// <para />
/// To check whether this is necessary, it will check whether the current thread has access to the dispatcher.
/// </summary>
/// <param name="dispatcher">The dispatcher.</param>
/// <param name="action">The action.</param>
/// <returns>The DispatcherOperation or <c>null</c> if the action was not dispatched but executed directly.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="action" /> is <c>null</c>.</exception>
/// <remarks>For target frameworks where the <see cref="Dispatcher" /> class does not contain the <c>Invoke</c> method, the <c>BeginInvoke</c>
/// method will be used instead.</remarks>
public static DispatcherOperation BeginInvokeIfRequired(this Dispatcher dispatcher, Action action)
{
return BeginInvoke(dispatcher, action, true);
}
/// <summary>
/// Executes the specified delegate asynchronously with the specified arguments on the thread that the Dispatcher was created on if required.
/// <para />
/// To check whether this is necessary, it will check whether the current thread has access to the dispatcher.
/// </summary>
/// <param name="dispatcher">The dispatcher.</param>
/// <param name="method">A delegate to a method that takes parameters specified in args, which is pushed onto the Dispatcher event queue.</param>
/// <param name="args">An array of objects to pass as arguments to the given method. Can be <c>null</c>.</param>
/// <returns>The DispatcherOperation or <c>null</c> if the action was not dispatched but executed directly.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="method" /> is <c>null</c>.</exception>
public static DispatcherOperation BeginInvokeIfRequired(this Dispatcher dispatcher, Delegate method, params object[] args)
{
Argument.IsNotNull("method", method);
return BeginInvoke(dispatcher, () => method.DynamicInvoke(args), true);
}
/// <summary>
/// Executes the specified delegate asynchronously with the specified arguments on the thread that the Dispatcher was created on.
/// </summary>
/// <param name="dispatcher">The dispatcher.</param>
/// <param name="action">The action.</param>
/// <param name="onlyBeginInvokeWhenNoAccess">If set to <c>true</c>, the action will be executed directly if possible. Otherwise,
/// <c>Dispatcher.BeginInvoke</c> will be used.</param>
/// <returns>The DispatcherOperation or <c>null</c> if the action was not dispatched but executed directly.</returns>
public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action action, bool onlyBeginInvokeWhenNoAccess)
{
Argument.IsNotNull("action", action);
if (dispatcher != null)
{
if (!onlyBeginInvokeWhenNoAccess || !dispatcher.CheckAccess())
{
#if NETFX_CORE
dispatcher.BeginInvoke(action);
return DispatcherOperation.Default;
#else
return dispatcher.BeginInvoke(action, null);
#endif
}
}
action.Invoke();
return null;
}
}
}
#endif
| 52.479339
| 153
| 0.629606
|
[
"MIT"
] |
uQr/Catel
|
src/Catel.MVVM/Catel.MVVM.Shared/Windows/Threading/Extensions/DispatcherExtensions.begininvoke.cs
| 6,352
|
C#
|
namespace NorthWind.NorthWindDB.DesktopUI.Forms
{
partial class CategoriesPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tbxCategoryName = new System.Windows.Forms.TextBox();
this.tbxDescription = new System.Windows.Forms.TextBox();
this.btnDelete = new System.Windows.Forms.Button();
this.btnSend = new System.Windows.Forms.Button();
this.dgvCategories = new System.Windows.Forms.DataGridView();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvCategories)).BeginInit();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.tbxCategoryName);
this.groupBox1.Controls.Add(this.tbxDescription);
this.groupBox1.Location = new System.Drawing.Point(21, 22);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(490, 127);
this.groupBox1.TabIndex = 7;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "General Information";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(254, 28);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(70, 15);
this.label2.TabIndex = 7;
this.label2.Text = "Description:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 28);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(93, 15);
this.label1.TabIndex = 6;
this.label1.Text = "Category Name:";
//
// tbxCategoryName
//
this.tbxCategoryName.Location = new System.Drawing.Point(6, 46);
this.tbxCategoryName.Name = "tbxCategoryName";
this.tbxCategoryName.Size = new System.Drawing.Size(229, 23);
this.tbxCategoryName.TabIndex = 1;
//
// tbxDescription
//
this.tbxDescription.Location = new System.Drawing.Point(254, 46);
this.tbxDescription.Name = "tbxDescription";
this.tbxDescription.Size = new System.Drawing.Size(229, 23);
this.tbxDescription.TabIndex = 2;
//
// btnDelete
//
this.btnDelete.Location = new System.Drawing.Point(270, 155);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(75, 23);
this.btnDelete.TabIndex = 16;
this.btnDelete.Text = "Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnSend
//
this.btnSend.Location = new System.Drawing.Point(165, 155);
this.btnSend.Name = "btnSend";
this.btnSend.Size = new System.Drawing.Size(75, 23);
this.btnSend.TabIndex = 15;
this.btnSend.Text = "Send";
this.btnSend.UseVisualStyleBackColor = true;
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// dgvCategories
//
this.dgvCategories.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvCategories.Dock = System.Windows.Forms.DockStyle.Bottom;
this.dgvCategories.Location = new System.Drawing.Point(0, 226);
this.dgvCategories.Name = "dgvCategories";
this.dgvCategories.RowTemplate.Height = 25;
this.dgvCategories.Size = new System.Drawing.Size(526, 224);
this.dgvCategories.TabIndex = 17;
this.dgvCategories.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvCategories_CellDoubleClick);
//
// CategoriesPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(526, 450);
this.Controls.Add(this.dgvCategories);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnSend);
this.Controls.Add(this.groupBox1);
this.Name = "CategoriesPage";
this.Text = "CategoriesPage";
this.Load += new System.EventHandler(this.CategoriesPage_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvCategories)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbxCategoryName;
private System.Windows.Forms.TextBox tbxDescription;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.Button btnSend;
private System.Windows.Forms.DataGridView dgvCategories;
}
}
| 44.5
| 140
| 0.59221
|
[
"Unlicense"
] |
Hknyvz/NorthWind
|
NorthWind.NorthWindDB.DesktopUI/Forms/CategoriesPage.Designer.cs
| 6,677
|
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("TestFrameworkWebApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestFrameworkWebApp")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("7c7e0f57-8b65-4254-a0ad-7b491a23078d")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.083333
| 84
| 0.751276
|
[
"MIT"
] |
jinnstudios/WebApi-FullFramework
|
1BaseFrameworkWebApi/BaseFrameworkWebApi/Properties/AssemblyInfo.cs
| 1,374
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MyHeritage.App.Models.ManageViewModels
{
public class VerifyPhoneNumberViewModel
{
[Required]
public string Code { get; set; }
[Required]
[Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
}
}
| 21.9
| 48
| 0.673516
|
[
"MIT"
] |
nimeshvaghasiya/MyHeritage
|
src/MyHeritage.App/Models/ManageViewModels/VerifyPhoneNumberViewModel.cs
| 440
|
C#
|
// <auto-generated />
using System;
using AutoLot.Dal.EfStructures;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace AutoLot.Dal.EfStructures.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20201024233510_CustomSql")]
partial class CustomSql
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.0-rc.2.20475.6");
modelBuilder.Entity("AutoLot.Models.Entities.Car", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Color")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<int>("MakeId")
.HasColumnType("int");
b.Property<string>("PetName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<byte[]>("TimeStamp")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.HasKey("Id");
b.HasIndex("MakeId");
b.ToTable("Inventory", "Dbo");
});
modelBuilder.Entity("AutoLot.Models.Entities.CreditRisk", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("CustomerId")
.HasColumnType("int");
b.Property<byte[]>("TimeStamp")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.HasKey("Id");
b.HasIndex("CustomerId");
b.ToTable("CreditRisks", "Dbo");
});
modelBuilder.Entity("AutoLot.Models.Entities.Customer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<byte[]>("TimeStamp")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.HasKey("Id");
b.ToTable("Customers", "Dbo");
});
modelBuilder.Entity("AutoLot.Models.Entities.Make", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<byte[]>("TimeStamp")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.HasKey("Id");
b.ToTable("Makes", "dbo");
});
modelBuilder.Entity("AutoLot.Models.Entities.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b.Property<int>("CarId")
.HasColumnType("int");
b.Property<int>("CustomerId")
.HasColumnType("int");
b.Property<byte[]>("TimeStamp")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("CustomerId", "CarId")
.IsUnique();
b.ToTable("Orders", "Dbo");
});
modelBuilder.Entity("AutoLot.Models.ViewModels.CustomerOrderViewModel", b =>
{
b.Property<string>("Color")
.HasColumnType("nvarchar(max)");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Make")
.HasColumnType("nvarchar(max)");
b.Property<string>("PetName")
.HasColumnType("nvarchar(max)");
b.ToView("CustomerOrderView", "dbo");
});
modelBuilder.Entity("AutoLot.Models.Entities.Car", b =>
{
b.HasOne("AutoLot.Models.Entities.Make", "MakeNavigation")
.WithMany("Cars")
.HasForeignKey("MakeId")
.HasConstraintName("FK_Make_Inventory")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("MakeNavigation");
});
modelBuilder.Entity("AutoLot.Models.Entities.CreditRisk", b =>
{
b.HasOne("AutoLot.Models.Entities.Customer", "CustomerNavigation")
.WithMany("CreditRisks")
.HasForeignKey("CustomerId")
.HasConstraintName("FK_CreditRisks_Customers")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.OwnsOne("AutoLot.Models.Entities.Owned.Person", "PersonalInformation", b1 =>
{
b1.Property<int>("CreditRiskId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b1.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("FirstName");
b1.Property<string>("LastName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("LastName");
b1.HasKey("CreditRiskId");
b1.ToTable("CreditRisks");
b1.WithOwner()
.HasForeignKey("CreditRiskId");
});
b.Navigation("CustomerNavigation");
b.Navigation("PersonalInformation")
.IsRequired();
});
modelBuilder.Entity("AutoLot.Models.Entities.Customer", b =>
{
b.OwnsOne("AutoLot.Models.Entities.Owned.Person", "PersonalInformation", b1 =>
{
b1.Property<int>("CustomerId")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.UseIdentityColumn();
b1.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("FirstName");
b1.Property<string>("LastName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)")
.HasColumnName("LastName");
b1.HasKey("CustomerId");
b1.ToTable("Customers");
b1.WithOwner()
.HasForeignKey("CustomerId");
});
b.Navigation("PersonalInformation")
.IsRequired();
});
modelBuilder.Entity("AutoLot.Models.Entities.Order", b =>
{
b.HasOne("AutoLot.Models.Entities.Car", "CarNavigation")
.WithMany("Orders")
.HasForeignKey("CarId")
.HasConstraintName("FK_Orders_Inventory")
.IsRequired();
b.HasOne("AutoLot.Models.Entities.Customer", "CustomerNavigation")
.WithMany("Orders")
.HasForeignKey("CustomerId")
.HasConstraintName("FK_Orders_Customers")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CarNavigation");
b.Navigation("CustomerNavigation");
});
modelBuilder.Entity("AutoLot.Models.Entities.Car", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("AutoLot.Models.Entities.Customer", b =>
{
b.Navigation("CreditRisks");
b.Navigation("Orders");
});
modelBuilder.Entity("AutoLot.Models.Entities.Make", b =>
{
b.Navigation("Cars");
});
#pragma warning restore 612, 618
}
}
}
| 36.523973
| 98
| 0.422597
|
[
"BSD-3-Clause",
"MIT"
] |
RomitMehta/presentations
|
DOTNETCORE/ASP.NETCore/v5.0/AutoLot50/AutoLot.Dal/EfStructures/Migrations/20201024233510_CustomSql.Designer.cs
| 10,667
|
C#
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace TR2Randomizer
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.166667
| 42
| 0.706422
|
[
"MIT"
] |
Anopob/TR2-Rando
|
TR2Randomizer/App.xaml.cs
| 329
|
C#
|
using Executorlibs.Bilibili.Protocol.Clients;
using Executorlibs.Bilibili.Protocol.Models.General;
using Executorlibs.MessageFramework.Handlers;
namespace Executorlibs.Bilibili.Protocol.Handlers
{
public interface IInvarianceBilibiliMessageHandler<TMessage> : IBilibiliMessageHandler<TMessage>, IInvarianceMessageHandler<IDanmakuClient, TMessage> where TMessage : IBilibiliMessage
{
}
}
| 33.416667
| 187
| 0.835411
|
[
"MIT"
] |
Executor-Cheng/Executorlibs
|
src/Executorlibs.Bilibili.Protocol/Handlers/IInvarianceBilibiliMessageHandler.cs
| 401
|
C#
|
// Copyright (c) MOSA Project. Licensed under the New BSD License.
// This code was generated by an automated template.
using Mosa.Compiler.Framework;
namespace Mosa.Platform.x64.Instructions
{
/// <summary>
/// Int
/// </summary>
/// <seealso cref="Mosa.Platform.x64.X64Instruction" />
public sealed class Int : X64Instruction
{
public override int ID { get { return 373; } }
internal Int()
: base(0, 1)
{
}
public override bool HasUnspecifiedSideEffect { get { return true; } }
public override bool IsZeroFlagUnchanged { get { return true; } }
public override bool IsZeroFlagUndefined { get { return true; } }
public override bool IsCarryFlagUnchanged { get { return true; } }
public override bool IsCarryFlagUndefined { get { return true; } }
public override bool IsSignFlagUnchanged { get { return true; } }
public override bool IsSignFlagUndefined { get { return true; } }
public override bool IsOverflowFlagUnchanged { get { return true; } }
public override bool IsOverflowFlagUndefined { get { return true; } }
public override bool IsParityFlagUnchanged { get { return true; } }
public override bool IsParityFlagUndefined { get { return true; } }
public override void Emit(InstructionNode node, BaseCodeEmitter emitter)
{
System.Diagnostics.Debug.Assert(node.ResultCount == 0);
System.Diagnostics.Debug.Assert(node.OperandCount == 1);
emitter.OpcodeEncoder.Append8Bits(0xCD);
emitter.OpcodeEncoder.Append8BitImmediate(node.Operand1);
}
}
}
| 28.185185
| 74
| 0.722076
|
[
"BSD-3-Clause"
] |
marcelocaetano/MOSA-Project
|
Source/Mosa.Platform.x64/Instructions/Int.cs
| 1,522
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace HandlebarsViewEngine.Web
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddHandlebars();
// If you want to override the default layout location
//services.Configure<HandlebarsViewEngineOptions>(options =>
//{
// options.DefaultLayout = "Views/Shared/layout.hbs";
//});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Could not match route");
});
}
}
}
| 32.056604
| 122
| 0.589759
|
[
"MIT"
] |
philrawlings/AspNetCore-Handlebars
|
src/HandlebarsViewEngine.Web/Startup.cs
| 1,701
|
C#
|
namespace FubuMVC.Core.Security.AntiForgery
{
public class FormToken
{
public string Name { get; set; }
public string TokenString { get; set; }
}
}
| 22
| 47
| 0.625
|
[
"Apache-2.0"
] |
DarthFubuMVC/fubumvc
|
src/FubuMVC.Core/Security/AntiForgery/FormToken.cs
| 178
|
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("Topshelf.Unity.Sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Topshelf.Unity.Sample")]
[assembly: AssemblyCopyright("Copyright © 2014-2015")]
[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("a22122c9-d4d1-4f64-aff7-685d659dcea7")]
// 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("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
| 38.378378
| 84
| 0.745775
|
[
"MIT"
] |
Kesmy/Topshelf.Unity
|
src/Topshelf.Unity.Sample/Properties/AssemblyInfo.cs
| 1,423
|
C#
|
using Ramone.Tests.Common;
namespace Ramone.Tests.Server.Handlers
{
public class EncodingHandler
{
public object Get(string type)
{
if (type == "html" || type == "xml")
return new EncodingData
{
Data = "<html><body>ÆØÅúï´`'</body></html>"
};
else
return new EncodingData
{
Data = "{ Name: \"ÆØÅúï´`'\\\"\" }"
};
}
public object Post(string type, EncodingData data)
{
return new EncodingData
{
Data = data.Data
};
}
}
}
| 19
| 55
| 0.480475
|
[
"MIT"
] |
ArvoX/Ramone
|
Ramone.Tests.Server/Handlers/EncodingHandler.cs
| 603
|
C#
|
using System.Collections.ObjectModel;
namespace gjp.io
{
/// <summary>
/// Configuration used for determining how lines are read/processed
/// </summary>
public class Configuration
{
/// <summary>
/// Gets or sets a value indicating whether to trim whitespace from lines.
/// </summary>
/// <value>
/// <c>true</c> if [trim lines]; otherwise, <c>false</c>.
/// </value>
public bool TrimLines { get; set; } = false;
/// <summary>
/// Gets or sets a value indicating whether to skip null or empty lines.
/// </summary>
/// <value>
/// <c>true</c> if [skip null or empty lines]; otherwise, <c>false</c>.
/// </value>
public bool SkipNullOrEmptyLines { get; set; } = false;
/// <summary>
/// Gets or sets a value indicating whether skip null, empty or white space lines.
/// </summary>
/// <value>
/// <c>true</c> if [skip null or white space lines]; otherwise, <c>false</c>.
/// </value>
public bool SkipNullOrWhiteSpaceLines { get; set; } = false;
/// <summary>
/// Gets or sets the minimum acceptable length of the line.
/// <para>Default (not set) value is -1</para>
/// </summary>
/// <value>
/// The minimum length of the line.
/// </value>
public int MinLineLength { get; set; } = -1;
/// <summary>
/// Gets or sets the maximum acceptable length of the line.
/// <para>Default (not set) value is -1</para>
/// </summary>
/// <value>
/// The maximum length of the line.
/// </value>
public int MaxLineLength { get; set; } = -1;
/// <summary>
/// Gets a collection of strings that would result in a containing line being skipped.
/// </summary>
/// <value>
/// The skip lines that contain.
/// </value>
public Collection<string> SkipLinesThatContain { get; }
/// <summary>
/// Gets a collection of strings that would result in a line beginning with being skipped.
/// </summary>
/// <value>
/// The skip lines that begin with.
/// </value>
public Collection<string> SkipLinesThatBeginWith { get; }
/// <summary>
/// Gets a collection of strings that would result in a line ending with being skipped.
/// </summary>
/// <value>
/// The skip lines that end with.
/// </value>
public Collection<string> SkipLinesThatEndWith { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Configuration"/> class.
/// </summary>
public Configuration()
{
SkipLinesThatContain = new Collection<string>();
SkipLinesThatBeginWith = new Collection<string>();
SkipLinesThatEndWith = new Collection<string>();
}
}
}
| 32.333333
| 98
| 0.541071
|
[
"Unlicense"
] |
gary-palmer/TextPreReader
|
src/TextPreReader/Configuration.cs
| 3,009
|
C#
|
/*
* Copyright 2010-2014 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 glacier-2012-06-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Glacier.Model
{
/// <summary>
/// Container for the parameters to the ListJobs operation.
/// This operation lists jobs for a vault, including jobs that are in-progress and jobs
/// that have recently finished. The List Job operation returns a list of these jobs sorted
/// by job initiation time.
///
/// <note>
/// <para>
/// Amazon Glacier retains recently completed jobs for a period before deleting them;
/// however, it eventually removes completed jobs. The output of completed jobs can be
/// retrieved. Retaining completed jobs for a period of time after they have completed
/// enables you to get a job output in the event you miss the job completion notification
/// or your first attempt to download it fails. For example, suppose you start an archive
/// retrieval job to download an archive. After the job completes, you start to download
/// the archive but encounter a network error. In this scenario, you can retry and download
/// the archive while the job exists.
/// </para>
/// </note>
/// <para>
/// The List Jobs operation supports pagination. You should always check the response
/// <code>Marker</code> field. If there are no more jobs to list, the <code>Marker</code>
/// field is set to <code>null</code>. If there are more jobs to list, the <code>Marker</code>
/// field is set to a non-null value, which you can use to continue the pagination of
/// the list. To return a list of jobs that begins at a specific job, set the marker request
/// parameter to the <code>Marker</code> value for that job that you obtained from a previous
/// List Jobs request.
/// </para>
///
/// <para>
/// You can set a maximum limit for the number of jobs returned in the response by specifying
/// the <code>limit</code> parameter in the request. The default limit is 50. The number
/// of jobs returned might be fewer than the limit, but the number of returned jobs never
/// exceeds the limit.
/// </para>
///
/// <para>
/// Additionally, you can filter the jobs list returned by specifying the optional <code>statuscode</code>
/// parameter or <code>completed</code> parameter, or both. Using the <code>statuscode</code>
/// parameter, you can specify to return only jobs that match either the <code>InProgress</code>,
/// <code>Succeeded</code>, or <code>Failed</code> status. Using the <code>completed</code>
/// parameter, you can specify to return only jobs that were completed (<code>true</code>)
/// or jobs that were not completed (<code>false</code>).
/// </para>
///
/// <para>
/// For more information about using this operation, see the documentation for the underlying
/// REST API <a href="https://docs.aws.amazon.com/amazonglacier/latest/dev/api-jobs-get.html">List
/// Jobs</a>.
/// </para>
/// </summary>
public partial class ListJobsRequest : AmazonGlacierRequest
{
private string _accountId;
private bool? _completed;
private int? _limit;
private string _marker;
private string _statuscode;
private string _vaultName;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public ListJobsRequest() { }
/// <summary>
/// Instantiates ListJobsRequest with the parameterized properties
/// </summary>
/// <param name="vaultName">The name of the vault.</param>
public ListJobsRequest(string vaultName)
{
_vaultName = vaultName;
}
/// <summary>
/// Instantiates ListJobsRequest with the parameterized properties
/// </summary>
/// <param name="accountId">The <code>AccountId</code> value is the AWS account ID of the account that owns the vault. You can either specify an AWS account ID or optionally a single '<code>-</code>' (hyphen), in which case Amazon S3 Glacier uses the AWS account ID associated with the credentials used to sign the request. If you use an account ID, do not include any hyphens ('-') in the ID. </param>
/// <param name="vaultName">The name of the vault.</param>
public ListJobsRequest(string accountId, string vaultName)
{
_accountId = accountId;
_vaultName = vaultName;
}
/// <summary>
/// Gets and sets the property AccountId.
/// <para>
/// The <code>AccountId</code> value is the AWS account ID of the account that owns the
/// vault. You can either specify an AWS account ID or optionally a single '<code>-</code>'
/// (hyphen), in which case Amazon S3 Glacier uses the AWS account ID associated with
/// the credentials used to sign the request. If you use an account ID, do not include
/// any hyphens ('-') in the ID.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string AccountId
{
get { return this._accountId; }
set { this._accountId = value; }
}
// Check to see if AccountId property is set
internal bool IsSetAccountId()
{
return this._accountId != null;
}
/// <summary>
/// Gets and sets the property Completed.
/// <para>
/// The state of the jobs to return. You can specify <code>true</code> or <code>false</code>.
/// </para>
/// </summary>
public bool Completed
{
get { return this._completed.GetValueOrDefault(); }
set { this._completed = value; }
}
// Check to see if Completed property is set
internal bool IsSetCompleted()
{
return this._completed.HasValue;
}
/// <summary>
/// Gets and sets the property Limit.
/// <para>
/// The maximum number of jobs to be returned. The default limit is 50. The number of
/// jobs returned might be fewer than the specified limit, but the number of returned
/// jobs never exceeds the limit.
/// </para>
/// </summary>
public int Limit
{
get { return this._limit.GetValueOrDefault(); }
set { this._limit = value; }
}
// Check to see if Limit property is set
internal bool IsSetLimit()
{
return this._limit.HasValue;
}
/// <summary>
/// Gets and sets the property Marker.
/// <para>
/// An opaque string used for pagination. This value specifies the job at which the listing
/// of jobs should begin. Get the marker value from a previous List Jobs response. You
/// only need to include the marker if you are continuing the pagination of results started
/// in a previous List Jobs request.
/// </para>
/// </summary>
public string Marker
{
get { return this._marker; }
set { this._marker = value; }
}
// Check to see if Marker property is set
internal bool IsSetMarker()
{
return this._marker != null;
}
/// <summary>
/// Gets and sets the property Statuscode.
/// <para>
/// The type of job status to return. You can specify the following values: <code>InProgress</code>,
/// <code>Succeeded</code>, or <code>Failed</code>.
/// </para>
/// </summary>
public string Statuscode
{
get { return this._statuscode; }
set { this._statuscode = value; }
}
// Check to see if Statuscode property is set
internal bool IsSetStatuscode()
{
return this._statuscode != null;
}
/// <summary>
/// Gets and sets the property VaultName.
/// <para>
/// The name of the vault.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string VaultName
{
get { return this._vaultName; }
set { this._vaultName = value; }
}
// Check to see if VaultName property is set
internal bool IsSetVaultName()
{
return this._vaultName != null;
}
}
}
| 39.748936
| 410
| 0.613318
|
[
"Apache-2.0"
] |
NGL321/aws-sdk-net
|
sdk/src/Services/Glacier/Generated/Model/ListJobsRequest.cs
| 9,341
|
C#
|
using System;
namespace ECommerceApp.Features.Core
{
public class BaseRequest
{
public Guid TenantUniqueId { get; set; }
}
}
| 16.333333
| 48
| 0.653061
|
[
"MIT"
] |
QuinntyneBrown/e-commerce-app
|
Features/Core/BaseRequest.cs
| 149
|
C#
|
namespace StudentsAndWorkers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public abstract class Human
{
private string firstName;
private string lastName;
public Human(string firstName , string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public string LastName
{
get { return this.lastName; }
private set
{
if (value == null)
{
throw new ArgumentNullException();
}
this.lastName = value;
}
}
public string FirstName
{
get { return this.firstName; }
set
{
if (value == null)
{
throw new ArgumentNullException();
}
this.firstName = value;
}
}
public override string ToString()
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
}
}
| 22.754717
| 75
| 0.461028
|
[
"MIT"
] |
Konstantin-Todorov/CSharpOOP
|
C#OOP-Homeworks/04.OOP Principles-Part1/StudentsAndWorkers/Human.cs
| 1,208
|
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Formatters.Internal;
using Microsoft.AspNetCore.Mvc.TestCommon;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Primitives;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Test
{
public class ProducesAttributeTests
{
[Fact]
public void ProducesAttribute_SetsContentType()
{
// Arrange
var mediaType1 = new StringSegment("application/json");
var mediaType2 = new StringSegment("text/json;charset=utf-8");
var producesContentAttribute = new ProducesAttribute("application/json", "text/json;charset=utf-8");
var resultExecutingContext = CreateResultExecutingContext(new IFilterMetadata[] { producesContentAttribute });
var next = new ResultExecutionDelegate(
() => Task.FromResult(CreateResultExecutedContext(resultExecutingContext)));
// Act
producesContentAttribute.OnResultExecuting(resultExecutingContext);
// Assert
var objectResult = resultExecutingContext.Result as ObjectResult;
Assert.Equal(2, objectResult.ContentTypes.Count);
MediaTypeAssert.Equal(mediaType1, objectResult.ContentTypes[0]);
MediaTypeAssert.Equal(mediaType2, objectResult.ContentTypes[1]);
}
[Fact]
public void ProducesContentAttribute_FormatFilterAttribute_NotActive()
{
// Arrange
var producesContentAttribute = new ProducesAttribute("application/xml");
var formatFilter = new Mock<IFormatFilter>();
formatFilter
.Setup(f => f.GetFormat(It.IsAny<ActionContext>()))
.Returns((string)null);
var filters = new IFilterMetadata[] { producesContentAttribute, formatFilter.Object };
var resultExecutingContext = CreateResultExecutingContext(filters);
var next = new ResultExecutionDelegate(
() => Task.FromResult(CreateResultExecutedContext(resultExecutingContext)));
// Act
producesContentAttribute.OnResultExecuting(resultExecutingContext);
// Assert
var objectResult = Assert.IsType<ObjectResult>(resultExecutingContext.Result);
Assert.Single(objectResult.ContentTypes);
}
[Fact]
public void ProducesContentAttribute_FormatFilterAttribute_Active()
{
// Arrange
var producesContentAttribute = new ProducesAttribute("application/xml");
var formatFilter = new Mock<IFormatFilter>();
formatFilter
.Setup(f => f.GetFormat(It.IsAny<ActionContext>()))
.Returns("xml");
var filters = new IFilterMetadata[] { producesContentAttribute, formatFilter.Object };
var resultExecutingContext = CreateResultExecutingContext(filters);
var next = new ResultExecutionDelegate(
() => Task.FromResult(CreateResultExecutedContext(resultExecutingContext)));
// Act
producesContentAttribute.OnResultExecuting(resultExecutingContext);
// Assert
var objectResult = Assert.IsType<ObjectResult>(resultExecutingContext.Result);
Assert.Empty(objectResult.ContentTypes);
}
[Theory]
[InlineData("", "")]
[InlineData("application/xml,, application/json", "")]
[InlineData(", application/json", "")]
[InlineData("invalid", "invalid")]
[InlineData("application/xml,invalid, application/json", "invalid")]
[InlineData("invalid, application/json", "invalid")]
public void ProducesAttribute_UnParsableContentType_Throws(string content, string invalidContentType)
{
// Act
var contentTypes = content.Split(',').Select(contentType => contentType.Trim()).ToArray();
// Assert
var ex = Assert.Throws<FormatException>(
() => new ProducesAttribute(contentTypes[0], contentTypes.Skip(1).ToArray()));
Assert.Equal("The header contains invalid values at index 0: '" + (invalidContentType ?? "<null>") + "'",
ex.Message);
}
[Theory]
[InlineData("application/*", "application/*")]
[InlineData("application/xml, application/*, application/json", "application/*")]
[InlineData("application/*, application/json", "application/*")]
[InlineData("*/*", "*/*")]
[InlineData("application/xml, */*, application/json", "*/*")]
[InlineData("*/*, application/json", "*/*")]
[InlineData("application/*+json", "application/*+json")]
[InlineData("application/json;v=1;*", "application/json;v=1;*")]
public void ProducesAttribute_InvalidContentType_Throws(string content, string invalidContentType)
{
// Act
var contentTypes = content.Split(',').Select(contentType => contentType.Trim()).ToArray();
// Assert
var ex = Assert.Throws<InvalidOperationException>(
() => new ProducesAttribute(contentTypes[0], contentTypes.Skip(1).ToArray()));
Assert.Equal(
string.Format("The argument '{0}' is invalid. " +
"Media types which match all types or match all subtypes are not supported.",
invalidContentType),
ex.Message);
}
[Fact]
public void ProducesAttribute_WithTypeOnly_SetsTypeProperty()
{
// Arrange
var personType = typeof(Person);
var producesAttribute = new ProducesAttribute(personType);
// Act and Assert
Assert.NotNull(producesAttribute.Type);
Assert.Same(personType, producesAttribute.Type);
}
[Fact]
public void ProducesAttribute_WithTypeOnly_DoesNotSetContentTypes()
{
// Arrange
var producesAttribute = new ProducesAttribute(typeof(Person));
// Act and Assert
Assert.NotNull(producesAttribute.ContentTypes);
Assert.Empty(producesAttribute.ContentTypes);
}
private static ResultExecutedContext CreateResultExecutedContext(ResultExecutingContext context)
{
return new ResultExecutedContext(context, context.Filters, context.Result, context.Controller);
}
private static ResultExecutingContext CreateResultExecutingContext(IFilterMetadata[] filters)
{
return new ResultExecutingContext(
CreateActionContext(),
filters,
new ObjectResult("Some Value"),
controller: new object());
}
private static ActionContext CreateActionContext()
{
return new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
}
private class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}
}
| 40.326203
| 122
| 0.622331
|
[
"Apache-2.0"
] |
aneequrrehman/Mvc
|
test/Microsoft.AspNetCore.Mvc.Core.Test/ProducesAttributeTests.cs
| 7,541
|
C#
|
using UnityEngine;
namespace BIG.LayeredFSMs
{
/// <summary>
/// Base class for FSMs that provides a reference to the blackboard.
/// </summary>
public class BlackboardClient : MonoBehaviour
{
public Blackboard Blackboard { get; private set; }
protected virtual void Awake()
{
Blackboard = GetComponent<Blackboard>();
}
}
}
| 18.952381
| 72
| 0.60804
|
[
"CC0-1.0"
] |
tonyli99/aiPresentations
|
Assets/__02_Layered_FSMs/Scripts/FSMs/BlackboardClient.cs
| 400
|
C#
|
// **********************************************************************************
// Copyright (c) 2015-2021, Dmitry Merzlyakov. All rights reserved.
// Licensed under the FreeBSD Public License. See LICENSE file included with the distribution for details and disclaimer.
//
// This file is part of NLedger that is a .Net port of C++ Ledger tool (ledger-cli.org). Original code is licensed under:
// Copyright (c) 2003-2021, John Wiegley. All rights reserved.
// See LICENSE.LEDGER file included with the distribution for details and disclaimer.
// **********************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NLedger.Times
{
public enum FormatTypeEnum
{
FMT_WRITTEN,
FMT_PRINTED,
FMT_CUSTOM
}
}
| 38.083333
| 122
| 0.577681
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] |
VagyokC4/nledger
|
Source/NLedger/Times/FormatTypeEnum.cs
| 916
|
C#
|
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// 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("Zonkey")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kelly Birr")]
[assembly: AssemblyProduct("Zonkey Data Connector Library")]
[assembly: AssemblyCopyright("Copyright © Kelly Birr")]
[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)]
[assembly: CLSCompliant(true)]
// Permissions
[assembly: AllowPartiallyTrustedCallers]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0C45F4BC-2ADB-4070-8B85-C19B3376141D")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("4.2.8.222")]
[assembly: AssemblyFileVersion("4.2.8.222")]
// The following line allows the unit testing assembly to access private/internal classes and methods
[assembly: InternalsVisibleTo("Zonkey.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a5bcb7ed4e1434fc2a0d5bfb1f5091db85ab657e7e418f47b72ac60a8797b198c1e9c90e533eee17462f1a469a7484aa936fa53ac21631f137547cf91cb7bd3647016b00b3dccb2bf7c9136d27c275b6e1f10cd2e60a95ef46e2b19c0bc3fd97addcea88e25278264b3ff17e483ff92221101bd5c5155ceaa6f46e088fece5b7")]
| 44.266667
| 377
| 0.799197
|
[
"MIT"
] |
kellybirr/zonkey-archive
|
v4.2/Properties/AssemblyInfo.cs
| 1,993
|
C#
|
/*
* Copyright 2010-2014 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 cloudhsm-2014-05-30.normal.json service model.
*/
using System;
namespace Amazon.CloudHSM.Model
{
/// <summary>
/// Configuration for accessing Amazon ModifyHsm service
/// </summary>
public partial class ModifyHsmResponse : ModifyHsmResult
{
/// <summary>
/// Gets and sets the ModifyHsmResult property.
/// Represents the output of a ModifyHsm operation.
/// </summary>
[Obsolete(@"This property has been deprecated. All properties of the ModifyHsmResult class are now available on the ModifyHsmResponse class. You should use the properties on ModifyHsmResponse instead of accessing them through ModifyHsmResult.")]
public ModifyHsmResult ModifyHsmResult
{
get
{
return this;
}
}
}
}
| 35.238095
| 253
| 0.680405
|
[
"Apache-2.0"
] |
samritchie/aws-sdk-net
|
AWSSDK_DotNet35/Amazon.CloudHSM/Model/ModifyHsmResponse.cs
| 1,480
|
C#
|
using Daramee.Mint.Entities;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Text;
namespace Daramee.Mint.Systems
{
public interface ISystem
{
bool IsTarget ( Entity entity );
bool IsParallelExecution { get; }
int Order { get; }
void PreExecute ();
void PostExecute ();
void Execute ( Entity entity, GameTime gameTime );
}
}
| 18.47619
| 52
| 0.729381
|
[
"MIT"
] |
daramkun/MintEngine
|
Daramee.Mint.Shared/Systems/ISystem.cs
| 390
|
C#
|
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you 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.
*
* Copyright (c) The DotNetty Project (Microsoft). All rights reserved.
*
* https://github.com/azure/dotnetty
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com) All rights reserved.
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.Codecs.Mqtt.Packets
{
using System.Collections.Generic;
public sealed class SubAckPacket : PacketWithId
{
public override PacketType PacketType => PacketType.SUBACK;
public IReadOnlyList<QualityOfService> ReturnCodes { get; set; }
public static SubAckPacket InResponseTo(SubscribePacket subscribePacket, QualityOfService maxQoS)
{
var subAckPacket = new SubAckPacket
{
PacketId = subscribePacket.PacketId
};
var subscriptionRequests = subscribePacket.Requests;
var returnCodes = new QualityOfService[subscriptionRequests.Count];
for (int i = 0; i < subscriptionRequests.Count; i++)
{
QualityOfService requestedQos = subscriptionRequests[i].QualityOfService;
returnCodes[i] = requestedQos <= maxQoS ? requestedQos : maxQoS;
}
subAckPacket.ReturnCodes = returnCodes;
return subAckPacket;
}
}
}
| 37.172414
| 105
| 0.688776
|
[
"MIT"
] |
cuteant/SpanNetty
|
src/DotNetty.Codecs.Mqtt/Packets/SubAckPacket.cs
| 2,158
|
C#
|
namespace QuickDraft.WebServer
{
public interface IWorkUnit
{
IHttpContext HttpContext { get; }
void Process();
bool IsException { get; }
bool IsPaused { get; }
//void SetState(WorkUnitState state);
//void SetException(Exception ex, string message);
}
}
| 18.764706
| 58
| 0.601881
|
[
"MIT"
] |
whitestrannik/QuickDraft.WebServer
|
QuickDraft.WebServer/IWorkUnit.cs
| 321
|
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>
//------------------------------------------------------------------------------
// Generation date: 11/28/2021 8:55:09 PM
namespace Microsoft.Dynamics.DataEntities
{
/// <summary>
/// There are no comments for PurchaseOrderLineChargeSingle in the schema.
/// </summary>
public partial class PurchaseOrderLineChargeSingle : global::Microsoft.OData.Client.DataServiceQuerySingle<PurchaseOrderLineCharge>
{
/// <summary>
/// Initialize a new PurchaseOrderLineChargeSingle object.
/// </summary>
public PurchaseOrderLineChargeSingle(global::Microsoft.OData.Client.DataServiceContext context, string path)
: base(context, path) {}
/// <summary>
/// Initialize a new PurchaseOrderLineChargeSingle object.
/// </summary>
public PurchaseOrderLineChargeSingle(global::Microsoft.OData.Client.DataServiceContext context, string path, bool isComposable)
: base(context, path, isComposable) {}
/// <summary>
/// Initialize a new PurchaseOrderLineChargeSingle object.
/// </summary>
public PurchaseOrderLineChargeSingle(global::Microsoft.OData.Client.DataServiceQuerySingle<PurchaseOrderLineCharge> query)
: base(query) {}
/// <summary>
/// There are no comments for PurchaseOrderLineV2 in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.PurchaseOrderLineV2Single PurchaseOrderLineV2
{
get
{
if (!this.IsComposable)
{
throw new global::System.NotSupportedException("The previous function is not composable.");
}
if ((this._PurchaseOrderLineV2 == null))
{
this._PurchaseOrderLineV2 = new global::Microsoft.Dynamics.DataEntities.PurchaseOrderLineV2Single(this.Context, GetPath("PurchaseOrderLineV2"));
}
return this._PurchaseOrderLineV2;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.PurchaseOrderLineV2Single _PurchaseOrderLineV2;
/// <summary>
/// There are no comments for Currency in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.CurrencySingle Currency
{
get
{
if (!this.IsComposable)
{
throw new global::System.NotSupportedException("The previous function is not composable.");
}
if ((this._Currency == null))
{
this._Currency = new global::Microsoft.Dynamics.DataEntities.CurrencySingle(this.Context, GetPath("Currency"));
}
return this._Currency;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.CurrencySingle _Currency;
/// <summary>
/// There are no comments for TaxGroup in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.TaxGroupSingle TaxGroup
{
get
{
if (!this.IsComposable)
{
throw new global::System.NotSupportedException("The previous function is not composable.");
}
if ((this._TaxGroup == null))
{
this._TaxGroup = new global::Microsoft.Dynamics.DataEntities.TaxGroupSingle(this.Context, GetPath("TaxGroup"));
}
return this._TaxGroup;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.TaxGroupSingle _TaxGroup;
/// <summary>
/// There are no comments for TaxItemGroup in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.TaxItemGroupSingle TaxItemGroup
{
get
{
if (!this.IsComposable)
{
throw new global::System.NotSupportedException("The previous function is not composable.");
}
if ((this._TaxItemGroup == null))
{
this._TaxItemGroup = new global::Microsoft.Dynamics.DataEntities.TaxItemGroupSingle(this.Context, GetPath("TaxItemGroup"));
}
return this._TaxItemGroup;
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.TaxItemGroupSingle _TaxItemGroup;
}
/// <summary>
/// There are no comments for PurchaseOrderLineCharge in the schema.
/// </summary>
/// <KeyProperties>
/// dataAreaId
/// PurchaseOrderNumber
/// PurchaseOrderLineNumber
/// ChargeLineNumber
/// </KeyProperties>
[global::Microsoft.OData.Client.Key("dataAreaId", "PurchaseOrderNumber", "PurchaseOrderLineNumber", "ChargeLineNumber")]
[global::Microsoft.OData.Client.EntitySet("PurchaseOrderLineCharges")]
public partial class PurchaseOrderLineCharge : global::Microsoft.OData.Client.BaseEntityType, global::System.ComponentModel.INotifyPropertyChanged
{
/// <summary>
/// Create a new PurchaseOrderLineCharge object.
/// </summary>
/// <param name="dataAreaId">Initial value of dataAreaId.</param>
/// <param name="purchaseOrderNumber">Initial value of PurchaseOrderNumber.</param>
/// <param name="purchaseOrderLineNumber">Initial value of PurchaseOrderLineNumber.</param>
/// <param name="chargeLineNumber">Initial value of ChargeLineNumber.</param>
/// <param name="intercompanyChargePercentage">Initial value of IntercompanyChargePercentage.</param>
/// <param name="proportionalChargeAmount">Initial value of ProportionalChargeAmount.</param>
/// <param name="externalChargeAmount">Initial value of ExternalChargeAmount.</param>
/// <param name="unitChargeAmount">Initial value of UnitChargeAmount.</param>
/// <param name="chargePercentage">Initial value of ChargePercentage.</param>
/// <param name="fixedChargeAmount">Initial value of FixedChargeAmount.</param>
/// <param name="purchaseOrderLineV2">Initial value of PurchaseOrderLineV2.</param>
/// <param name="currency">Initial value of Currency.</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public static PurchaseOrderLineCharge CreatePurchaseOrderLineCharge(string dataAreaId,
string purchaseOrderNumber,
long purchaseOrderLineNumber,
decimal chargeLineNumber,
decimal intercompanyChargePercentage,
decimal proportionalChargeAmount,
decimal externalChargeAmount,
decimal unitChargeAmount,
decimal chargePercentage,
decimal fixedChargeAmount,
global::Microsoft.Dynamics.DataEntities.PurchaseOrderLineV2 purchaseOrderLineV2,
global::Microsoft.Dynamics.DataEntities.Currency currency)
{
PurchaseOrderLineCharge purchaseOrderLineCharge = new PurchaseOrderLineCharge();
purchaseOrderLineCharge.dataAreaId = dataAreaId;
purchaseOrderLineCharge.PurchaseOrderNumber = purchaseOrderNumber;
purchaseOrderLineCharge.PurchaseOrderLineNumber = purchaseOrderLineNumber;
purchaseOrderLineCharge.ChargeLineNumber = chargeLineNumber;
purchaseOrderLineCharge.IntercompanyChargePercentage = intercompanyChargePercentage;
purchaseOrderLineCharge.ProportionalChargeAmount = proportionalChargeAmount;
purchaseOrderLineCharge.ExternalChargeAmount = externalChargeAmount;
purchaseOrderLineCharge.UnitChargeAmount = unitChargeAmount;
purchaseOrderLineCharge.ChargePercentage = chargePercentage;
purchaseOrderLineCharge.FixedChargeAmount = fixedChargeAmount;
if ((purchaseOrderLineV2 == null))
{
throw new global::System.ArgumentNullException("purchaseOrderLineV2");
}
purchaseOrderLineCharge.PurchaseOrderLineV2 = purchaseOrderLineV2;
if ((currency == null))
{
throw new global::System.ArgumentNullException("currency");
}
purchaseOrderLineCharge.Currency = currency;
return purchaseOrderLineCharge;
}
/// <summary>
/// There are no comments for Property dataAreaId in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "dataAreaId is required.")]
public virtual string dataAreaId
{
get
{
return this._dataAreaId;
}
set
{
this.OndataAreaIdChanging(value);
this._dataAreaId = value;
this.OndataAreaIdChanged();
this.OnPropertyChanged("dataAreaId");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _dataAreaId;
partial void OndataAreaIdChanging(string value);
partial void OndataAreaIdChanged();
/// <summary>
/// There are no comments for Property PurchaseOrderNumber in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "PurchaseOrderNumber is required.")]
public virtual string PurchaseOrderNumber
{
get
{
return this._PurchaseOrderNumber;
}
set
{
this.OnPurchaseOrderNumberChanging(value);
this._PurchaseOrderNumber = value;
this.OnPurchaseOrderNumberChanged();
this.OnPropertyChanged("PurchaseOrderNumber");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _PurchaseOrderNumber;
partial void OnPurchaseOrderNumberChanging(string value);
partial void OnPurchaseOrderNumberChanged();
/// <summary>
/// There are no comments for Property PurchaseOrderLineNumber in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "PurchaseOrderLineNumber is required.")]
public virtual long PurchaseOrderLineNumber
{
get
{
return this._PurchaseOrderLineNumber;
}
set
{
this.OnPurchaseOrderLineNumberChanging(value);
this._PurchaseOrderLineNumber = value;
this.OnPurchaseOrderLineNumberChanged();
this.OnPropertyChanged("PurchaseOrderLineNumber");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private long _PurchaseOrderLineNumber;
partial void OnPurchaseOrderLineNumberChanging(long value);
partial void OnPurchaseOrderLineNumberChanged();
/// <summary>
/// There are no comments for Property ChargeLineNumber in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ChargeLineNumber is required.")]
public virtual decimal ChargeLineNumber
{
get
{
return this._ChargeLineNumber;
}
set
{
this.OnChargeLineNumberChanging(value);
this._ChargeLineNumber = value;
this.OnChargeLineNumberChanged();
this.OnPropertyChanged("ChargeLineNumber");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _ChargeLineNumber;
partial void OnChargeLineNumberChanging(decimal value);
partial void OnChargeLineNumberChanged();
/// <summary>
/// There are no comments for Property PurchaseChargeCode in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string PurchaseChargeCode
{
get
{
return this._PurchaseChargeCode;
}
set
{
this.OnPurchaseChargeCodeChanging(value);
this._PurchaseChargeCode = value;
this.OnPurchaseChargeCodeChanged();
this.OnPropertyChanged("PurchaseChargeCode");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _PurchaseChargeCode;
partial void OnPurchaseChargeCodeChanging(string value);
partial void OnPurchaseChargeCodeChanged();
/// <summary>
/// There are no comments for Property IsIntercompanyCharge in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.Nullable<global::Microsoft.Dynamics.DataEntities.NoYes> IsIntercompanyCharge
{
get
{
return this._IsIntercompanyCharge;
}
set
{
this.OnIsIntercompanyChargeChanging(value);
this._IsIntercompanyCharge = value;
this.OnIsIntercompanyChargeChanged();
this.OnPropertyChanged("IsIntercompanyCharge");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.Nullable<global::Microsoft.Dynamics.DataEntities.NoYes> _IsIntercompanyCharge;
partial void OnIsIntercompanyChargeChanging(global::System.Nullable<global::Microsoft.Dynamics.DataEntities.NoYes> value);
partial void OnIsIntercompanyChargeChanged();
/// <summary>
/// There are no comments for Property IntercompanyChargePercentage in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "IntercompanyChargePercentage is required.")]
public virtual decimal IntercompanyChargePercentage
{
get
{
return this._IntercompanyChargePercentage;
}
set
{
this.OnIntercompanyChargePercentageChanging(value);
this._IntercompanyChargePercentage = value;
this.OnIntercompanyChargePercentageChanged();
this.OnPropertyChanged("IntercompanyChargePercentage");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _IntercompanyChargePercentage;
partial void OnIntercompanyChargePercentageChanging(decimal value);
partial void OnIntercompanyChargePercentageChanged();
/// <summary>
/// There are no comments for Property ChargeDescription in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string ChargeDescription
{
get
{
return this._ChargeDescription;
}
set
{
this.OnChargeDescriptionChanging(value);
this._ChargeDescription = value;
this.OnChargeDescriptionChanged();
this.OnPropertyChanged("ChargeDescription");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _ChargeDescription;
partial void OnChargeDescriptionChanging(string value);
partial void OnChargeDescriptionChanged();
/// <summary>
/// There are no comments for Property ProportionalChargeAmount in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ProportionalChargeAmount is required.")]
public virtual decimal ProportionalChargeAmount
{
get
{
return this._ProportionalChargeAmount;
}
set
{
this.OnProportionalChargeAmountChanging(value);
this._ProportionalChargeAmount = value;
this.OnProportionalChargeAmountChanged();
this.OnPropertyChanged("ProportionalChargeAmount");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _ProportionalChargeAmount;
partial void OnProportionalChargeAmountChanging(decimal value);
partial void OnProportionalChargeAmountChanged();
/// <summary>
/// There are no comments for Property ExternalChargeAmount in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ExternalChargeAmount is required.")]
public virtual decimal ExternalChargeAmount
{
get
{
return this._ExternalChargeAmount;
}
set
{
this.OnExternalChargeAmountChanging(value);
this._ExternalChargeAmount = value;
this.OnExternalChargeAmountChanged();
this.OnPropertyChanged("ExternalChargeAmount");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _ExternalChargeAmount;
partial void OnExternalChargeAmountChanging(decimal value);
partial void OnExternalChargeAmountChanged();
/// <summary>
/// There are no comments for Property SalesTaxGroupCode in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string SalesTaxGroupCode
{
get
{
return this._SalesTaxGroupCode;
}
set
{
this.OnSalesTaxGroupCodeChanging(value);
this._SalesTaxGroupCode = value;
this.OnSalesTaxGroupCodeChanged();
this.OnPropertyChanged("SalesTaxGroupCode");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _SalesTaxGroupCode;
partial void OnSalesTaxGroupCodeChanging(string value);
partial void OnSalesTaxGroupCodeChanged();
/// <summary>
/// There are no comments for Property UnitChargeAmount in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "UnitChargeAmount is required.")]
public virtual decimal UnitChargeAmount
{
get
{
return this._UnitChargeAmount;
}
set
{
this.OnUnitChargeAmountChanging(value);
this._UnitChargeAmount = value;
this.OnUnitChargeAmountChanged();
this.OnPropertyChanged("UnitChargeAmount");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _UnitChargeAmount;
partial void OnUnitChargeAmountChanging(decimal value);
partial void OnUnitChargeAmountChanged();
/// <summary>
/// There are no comments for Property ChargeAccountingCurrencyCode in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string ChargeAccountingCurrencyCode
{
get
{
return this._ChargeAccountingCurrencyCode;
}
set
{
this.OnChargeAccountingCurrencyCodeChanging(value);
this._ChargeAccountingCurrencyCode = value;
this.OnChargeAccountingCurrencyCodeChanged();
this.OnPropertyChanged("ChargeAccountingCurrencyCode");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _ChargeAccountingCurrencyCode;
partial void OnChargeAccountingCurrencyCodeChanging(string value);
partial void OnChargeAccountingCurrencyCodeChanged();
/// <summary>
/// There are no comments for Property SalesTaxItemGroupCode in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual string SalesTaxItemGroupCode
{
get
{
return this._SalesTaxItemGroupCode;
}
set
{
this.OnSalesTaxItemGroupCodeChanging(value);
this._SalesTaxItemGroupCode = value;
this.OnSalesTaxItemGroupCodeChanged();
this.OnPropertyChanged("SalesTaxItemGroupCode");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private string _SalesTaxItemGroupCode;
partial void OnSalesTaxItemGroupCodeChanging(string value);
partial void OnSalesTaxItemGroupCodeChanged();
/// <summary>
/// There are no comments for Property ChargeCategory in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::System.Nullable<global::Microsoft.Dynamics.DataEntities.MarkupCategory> ChargeCategory
{
get
{
return this._ChargeCategory;
}
set
{
this.OnChargeCategoryChanging(value);
this._ChargeCategory = value;
this.OnChargeCategoryChanged();
this.OnPropertyChanged("ChargeCategory");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::System.Nullable<global::Microsoft.Dynamics.DataEntities.MarkupCategory> _ChargeCategory;
partial void OnChargeCategoryChanging(global::System.Nullable<global::Microsoft.Dynamics.DataEntities.MarkupCategory> value);
partial void OnChargeCategoryChanged();
/// <summary>
/// There are no comments for Property ChargePercentage in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ChargePercentage is required.")]
public virtual decimal ChargePercentage
{
get
{
return this._ChargePercentage;
}
set
{
this.OnChargePercentageChanging(value);
this._ChargePercentage = value;
this.OnChargePercentageChanged();
this.OnPropertyChanged("ChargePercentage");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _ChargePercentage;
partial void OnChargePercentageChanging(decimal value);
partial void OnChargePercentageChanged();
/// <summary>
/// There are no comments for Property FixedChargeAmount in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "FixedChargeAmount is required.")]
public virtual decimal FixedChargeAmount
{
get
{
return this._FixedChargeAmount;
}
set
{
this.OnFixedChargeAmountChanging(value);
this._FixedChargeAmount = value;
this.OnFixedChargeAmountChanged();
this.OnPropertyChanged("FixedChargeAmount");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private decimal _FixedChargeAmount;
partial void OnFixedChargeAmountChanging(decimal value);
partial void OnFixedChargeAmountChanged();
/// <summary>
/// There are no comments for Property PurchaseOrderLineV2 in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "PurchaseOrderLineV2 is required.")]
public virtual global::Microsoft.Dynamics.DataEntities.PurchaseOrderLineV2 PurchaseOrderLineV2
{
get
{
return this._PurchaseOrderLineV2;
}
set
{
this.OnPurchaseOrderLineV2Changing(value);
this._PurchaseOrderLineV2 = value;
this.OnPurchaseOrderLineV2Changed();
this.OnPropertyChanged("PurchaseOrderLineV2");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.PurchaseOrderLineV2 _PurchaseOrderLineV2;
partial void OnPurchaseOrderLineV2Changing(global::Microsoft.Dynamics.DataEntities.PurchaseOrderLineV2 value);
partial void OnPurchaseOrderLineV2Changed();
/// <summary>
/// There are no comments for Property Currency in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
[global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "Currency is required.")]
public virtual global::Microsoft.Dynamics.DataEntities.Currency Currency
{
get
{
return this._Currency;
}
set
{
this.OnCurrencyChanging(value);
this._Currency = value;
this.OnCurrencyChanged();
this.OnPropertyChanged("Currency");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.Currency _Currency;
partial void OnCurrencyChanging(global::Microsoft.Dynamics.DataEntities.Currency value);
partial void OnCurrencyChanged();
/// <summary>
/// There are no comments for Property TaxGroup in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.TaxGroup TaxGroup
{
get
{
return this._TaxGroup;
}
set
{
this.OnTaxGroupChanging(value);
this._TaxGroup = value;
this.OnTaxGroupChanged();
this.OnPropertyChanged("TaxGroup");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.TaxGroup _TaxGroup;
partial void OnTaxGroupChanging(global::Microsoft.Dynamics.DataEntities.TaxGroup value);
partial void OnTaxGroupChanged();
/// <summary>
/// There are no comments for Property TaxItemGroup in the schema.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public virtual global::Microsoft.Dynamics.DataEntities.TaxItemGroup TaxItemGroup
{
get
{
return this._TaxItemGroup;
}
set
{
this.OnTaxItemGroupChanging(value);
this._TaxItemGroup = value;
this.OnTaxItemGroupChanged();
this.OnPropertyChanged("TaxItemGroup");
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
private global::Microsoft.Dynamics.DataEntities.TaxItemGroup _TaxItemGroup;
partial void OnTaxItemGroupChanging(global::Microsoft.Dynamics.DataEntities.TaxItemGroup value);
partial void OnTaxItemGroupChanged();
/// <summary>
/// This event is raised when the value of the property is changed
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// The value of the property is changed
/// </summary>
/// <param name="property">property name</param>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")]
protected virtual void OnPropertyChanged(string property)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(property));
}
}
}
}
| 47.386591
| 164
| 0.630411
|
[
"MIT"
] |
NathanClouseAX/AAXDataEntityPerfTest
|
Projects/AAXDataEntityPerfTest/ODataUtility/Connected Services/D365/PurchaseOrderLineCharge.cs
| 33,220
|
C#
|
using System;
using System.Collections.Generic;
using CommonPasswordsValidator.Internal;
namespace CommonPasswordsValidator
{
/// <summary>
/// Validates that the supplied password is not one of the 100 most common passwords
/// </summary>
public class Top100PasswordValidator<TUser>
: CommonPasswordValidator<TUser> where TUser : class
{
///<inheritdoc />
protected override HashSet<string> Passwords {get;} = PasswordLists.Top100Passwords.Value;
}
}
| 29.588235
| 98
| 0.71173
|
[
"MIT"
] |
andrewlock/netcore2preview
|
src/CommonPasswordsValidator/Top100PasswordValidator.cs
| 505
|
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("TrackPlayerDemo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TrackPlayerDemo")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)]
| 36.068966
| 84
| 0.743786
|
[
"Apache-2.0"
] |
react-native-kit/react-native-track-player-demo
|
windows/TrackPlayerDemo/Properties/AssemblyInfo.cs
| 1,047
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TravelAgent.Web.admin.visa
{
public partial class EditVisaOrder : System.Web.UI.Page
{
public int orderid;
private static readonly TravelAgent.BLL.Club ClubBll = new TravelAgent.BLL.Club();
private static readonly TravelAgent.BLL.Order VisaOrderBll = new TravelAgent.BLL.Order();
private static readonly TravelAgent.BLL.VisaList VisaBll = new TravelAgent.BLL.VisaList();
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
orderid = Convert.ToInt32(Request.QueryString["id"]);
}
if (!this.IsPostBack)
{
DataBindState();
DataBindPay();
if (orderid > 0)
{
TravelAgent.Model.Order order = VisaOrderBll.GetModel(orderid);
if (order != null)
{
TravelAgent.Model.VisaList visa = VisaBll.GetModel(order.lineId);
if (visa != null)
{
this.hddonate.Value = visa.donatePoints.ToString();
}
this.hdordercode.Value = order.ordercode;
this.lblVisaName.Text = order.proName;
this.lblOrderCode.Text = order.ordercode;
this.lblOrderDate.Text = order.orderDate.ToString();
this.lblTravelDate.Text = order.TravelDate;
this.lblOrderRemark.Text = order.orderRemark;
TravelAgent.Model.Club club = ClubBll.GetModel(order.clubid);
if (club != null)
{
this.lblClubInfo.Text = club.clubName + " / " + club.clubMobile + " / " + club.clubEmail;
}
this.lblLinkName.Text = order.contactName;
this.lblEmail.Text = order.contactEmail;
this.lblTel.Text = order.contactMobile;
this.lblSex.Text = !order.contactSex.Equals("")?TravelAgent.Tool.EnumHelper.GetMemberName<TravelAgent.Tool.EnumSummary.TouristSex>(order.contactSex):"";
this.lblOrderTotalPrice.Text = order.orderPrice.ToString();
this.txtJiaJian.Value = order.subPrice.ToString();
this.txtuserPoints.Value = order.usePoints.ToString();
this.lblPayCost.Text = (order.orderPrice - order.usePoints + order.subPrice).ToString();
this.ddlPayType.SelectedValue = order.payType.ToString();
this.ddlState.SelectedValue = order.orderState.ToString();
this.txtRemark.Value = order.operRemark;
this.lblPeopleNum.Text = order.peopleNumber.ToString();
if (order.orderState == Convert.ToInt32(TravelAgent.Tool.EnumSummary.OrderState.已付款))
{
this.lblPayState.Text = "已付款";
}
else
{
this.lblPayState.Text = "未付款";
}
}
}
}
}
/// <summary>
/// 绑定状态属性
/// </summary>
private void DataBindState()
{
Dictionary<string, int> dcPay = TravelAgent.Tool.EnumHelper.GetDictionaryMemberKeyValue<TravelAgent.Tool.EnumSummary.OrderState>();//数据源
this.ddlState.DataSource = dcPay.OrderBy(d => d.Value); ;
this.ddlState.DataTextField = "Key";
this.ddlState.DataValueField = "Value";
this.ddlState.DataBind();
this.ddlState.Items.Insert(0, new ListItem("订单状态", "0"));
}
/// <summary>
/// 绑定状态属性
/// </summary>
private void DataBindPay()
{
Hashtable ht = TravelAgent.Tool.EnumHelper.GetMemberKeyValue<TravelAgent.Tool.EnumSummary.PayType>();//数据源
this.ddlPayType.DataSource = ht;
this.ddlPayType.DataTextField = "Key";
this.ddlPayType.DataValueField = "Value";
this.ddlPayType.DataBind();
this.ddlPayType.Items.Insert(0, new ListItem("支付方式", "0"));
}
}
}
| 47.469388
| 177
| 0.521496
|
[
"Apache-2.0"
] |
huahuajjh/distributor-yuyb
|
src/TravelAgent.Web/TravelAgent.Web/admin/visa/EditVisaOrder.aspx.cs
| 4,724
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Bot.Schema;
namespace QnAMakerActiveLearningBot.Helpers
{
public class CardHelper
{
/// <summary>
/// Get Hero card
/// </summary>
/// <param name="suggestionsList">List of suggested questions</param>
/// <param name="cardTitle">Title of the cards</param>
/// <param name="cardNoMatchText">No match text</param>
/// <returns></returns>
public static IMessageActivity GetHeroCard(List<string> suggestionsList, string cardTitle = "Did you mean:", string cardNoMatchText = "None of the above.")
{
var chatActivity = Activity.CreateMessageActivity();
var buttonList = new List<CardAction>();
// Add all suggestions
foreach (var suggestion in suggestionsList)
{
buttonList.Add(
new CardAction()
{
Value = suggestion,
Type = "imBack",
Title = suggestion,
});
}
// Add No match text
buttonList.Add(
new CardAction()
{
Value = cardNoMatchText,
Type = "imBack",
Title = cardNoMatchText
});
var plCard = new HeroCard()
{
Title = cardTitle,
Subtitle = string.Empty,
Buttons = buttonList
};
// Create the attachment.
var attachment = plCard.ToAttachment();
chatActivity.Attachments.Add(attachment);
return chatActivity;
}
}
}
| 30.183333
| 163
| 0.50635
|
[
"MIT"
] |
BillStrait/BotBuilder-Samples
|
experimental/csharp_dotnetcore/qnamaker-activelearning-bot/Helpers/CardHelper.cs
| 1,813
|
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.Collections.Generic;
using Xunit;
namespace System.CodeDom.Tests
{
public class CodeAttachEventStatementTests : CodeStatementTestBase<CodeAttachEventStatement>
{
[Fact]
public void Ctor_Default()
{
var attachEvent = new CodeAttachEventStatement();
Assert.Empty(attachEvent.Event.EventName);
Assert.Null(attachEvent.Event.TargetObject);
Assert.Null(attachEvent.Listener);
}
public static IEnumerable<object[]> Ctor_CodeExpression_String_CodeExpression_TestData()
{
yield return new object[] { null, null, null };
yield return new object[] { new CodePrimitiveExpression("Value1"), "EventName", new CodePrimitiveExpression("Value2") };
}
[Theory]
[MemberData(nameof(Ctor_CodeExpression_String_CodeExpression_TestData))]
public void Ctor_CodeExpression_String_CodeExpression(CodeExpression targetObject, string eventName, CodeExpression listener)
{
var attachEvent = new CodeAttachEventStatement(targetObject, eventName, listener);
Assert.Equal(targetObject, attachEvent.Event.TargetObject);
Assert.Equal(eventName ?? string.Empty, attachEvent.Event.EventName);
Assert.Equal(listener, attachEvent.Listener);
}
public static IEnumerable<object[]> CodeEventReferenceExpression_CodeExpression_TestData()
{
yield return new object[] { null, null };
yield return new object[] { new CodeEventReferenceExpression(null, null), null };
yield return new object[] { new CodeEventReferenceExpression(new CodePrimitiveExpression("Value1"), "EventName"), new CodePrimitiveExpression("Value2") };
}
[Theory]
[MemberData(nameof(CodeEventReferenceExpression_CodeExpression_TestData))]
public void Ctor_CodeEventReferenceExpression_CodeExpression(CodeEventReferenceExpression eventExpresion, CodeExpression listener)
{
var attachEvent = new CodeAttachEventStatement(eventExpresion, listener);
Assert.Equal((eventExpresion ?? new CodeEventReferenceExpression()).TargetObject, attachEvent.Event.TargetObject);
Assert.Equal((eventExpresion ?? new CodeEventReferenceExpression()).EventName, attachEvent.Event.EventName);
Assert.Equal(listener, attachEvent.Listener);
}
[Theory]
[MemberData(nameof(CodeEventReferenceExpression_CodeExpression_TestData))]
public void Event_Set_Get_ReturnsExpected(CodeEventReferenceExpression value, CodeExpression _)
{
var attachEvent = new CodeAttachEventStatement();
attachEvent.Event = value;
Assert.Equal((value ?? new CodeEventReferenceExpression()).TargetObject, attachEvent.Event.TargetObject);
Assert.Equal((value ?? new CodeEventReferenceExpression()).EventName, attachEvent.Event.EventName);
}
[Theory]
[MemberData(nameof(CodeExpression_TestData))]
public void Listener_Set_Get_ReturnsExpected(CodeExpression value)
{
var attachEvent = new CodeAttachEventStatement();
attachEvent.Listener = value;
Assert.Equal(value, attachEvent.Listener);
}
}
}
| 42.202703
| 157
| 0.787064
|
[
"MIT"
] |
2E0PGS/corefx
|
src/System.CodeDom/tests/System/CodeDom/CodeAttachEventStatementTests.cs
| 3,125
|
C#
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using NHSD.GPIT.BuyingCatalogue.E2ETests.Utils;
using NHSD.GPIT.BuyingCatalogue.E2ETests.Utils.TestBases;
using NHSD.GPIT.BuyingCatalogue.EntityFramework.Ordering.Models;
using NHSD.GPIT.BuyingCatalogue.WebApp.Areas.Order.Controllers;
using OpenQA.Selenium;
using Xunit;
namespace NHSD.GPIT.BuyingCatalogue.E2ETests.Areas.Ordering.CatalogueSolutions
{
public sealed class CatalogueSolutions
: BuyerTestBase, IClassFixture<LocalWebApplicationFactory>
{
private const string OdsCode = "03F";
private static readonly CallOffId CallOffId = new(90006, 1);
private static readonly Dictionary<string, string> Parameters =
new()
{
{ nameof(OdsCode), OdsCode },
{ nameof(CallOffId), CallOffId.ToString() },
};
public CatalogueSolutions(LocalWebApplicationFactory factory)
: base(
factory,
typeof(CatalogueSolutionsController),
nameof(CatalogueSolutionsController.Index),
Parameters)
{
}
[Fact]
public void CatalogueSolutions_AllSectionsDisplayed()
{
CommonActions.ElementIsDisplayed(Objects.Ordering.CatalogueItems.AddCatalogueSolution).Should().BeTrue();
CommonActions.ElementIsDisplayed(Objects.Ordering.CatalogueItems.AddedItemsTable).Should().BeTrue();
CommonActions.ElementIsDisplayed(Objects.Ordering.CatalogueItems.ContinueButton).Should().BeTrue();
CommonActions.GoBackLinkDisplayed().Should().BeTrue();
}
[Fact]
public void CatalogueSolutions_ClickGoBackLink_ExpectedResult()
{
CommonActions.ClickGoBackLink();
CommonActions
.PageLoadedCorrectGetIndex(
typeof(OrderController),
nameof(OrderController.Order))
.Should()
.BeTrue();
}
[Fact]
public void CatalogueSolutions_ClickAddSolution()
{
CommonActions.ClickLinkElement(Objects.Ordering.CatalogueItems.AddCatalogueSolution);
CommonActions
.PageLoadedCorrectGetIndex(
typeof(CatalogueSolutionsController),
nameof(CatalogueSolutionsController.SelectSolution))
.Should()
.BeTrue();
}
[Fact]
public void CatalogueSolutions_ClickContinue()
{
CommonActions.ClickLinkElement(Objects.Ordering.CatalogueItems.ContinueButton);
CommonActions.PageLoadedCorrectGetIndex(
typeof(OrderController),
nameof(OrderController.Order))
.Should()
.BeTrue();
}
[Fact]
public async Task CatalogueSolutions_ClickSolution_GoToEditPage()
{
using var context = GetEndToEndDbContext();
var catalogueItemName =
await context.Orders
.Include(o => o.OrderItems).ThenInclude(oi => oi.CatalogueItem)
.Where(o => o.Id == CallOffId.Id)
.Select(o => o.OrderItems[0].CatalogueItem.Name)
.SingleAsync();
CommonActions.ClickLinkElement(By.LinkText(catalogueItemName));
CommonActions.PageLoadedCorrectGetIndex(
typeof(CatalogueSolutionsController),
nameof(CatalogueSolutionsController.EditSolution))
.Should()
.BeTrue();
}
}
}
| 34.877358
| 117
| 0.62456
|
[
"MIT"
] |
nhs-digital-gp-it-futures/GPITBuyingCatalogue
|
tests/NHSD.GPIT.BuyingCatalogue.E2E.PublicBrowseTests/Areas/Ordering/CatalogueSolutions/Home/CatalogueSolutions.cs
| 3,699
|
C#
|
using System;
using System.Collections.Generic;
namespace ESFA.DC.ILR2021.DataStore.EF.Valid
{
public partial class LearnerHE
{
public LearnerHE()
{
LearnerHEFinancialSupports = new HashSet<LearnerHEFinancialSupport>();
}
public int UKPRN { get; set; }
public string LearnRefNumber { get; set; }
public string UCASPERID { get; set; }
public int? TTACCOM { get; set; }
public virtual Learner Learner { get; set; }
public virtual ICollection<LearnerHEFinancialSupport> LearnerHEFinancialSupports { get; set; }
}
}
| 27.818182
| 102
| 0.647059
|
[
"MIT"
] |
SkillsFundingAgency/DC-ILR-2021-DataStore
|
src/Database/ESFA.DC.ILR2021.DataStore.EF.Valid/LearnerHE.cs
| 614
|
C#
|
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by SpecFlow (http://www.specflow.org/).
// SpecFlow Version:1.9.0.77
// SpecFlow Generator Version:1.9.0.0
// 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>
// ------------------------------------------------------------------------------
#region Designer generated code
#pragma warning disable
namespace OrganizationRegister.AcceptanceTests.Features.Organization
{
using TechTalk.SpecFlow;
[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute()]
public partial class UpdatingOrganizationAuthorizationInformationFeature
{
private static TechTalk.SpecFlow.ITestRunner testRunner;
#line 1 "UpdatingOrganizationAuthorizationInformation.feature"
#line hidden
[Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute()]
public static void FeatureSetup(Microsoft.VisualStudio.TestTools.UnitTesting.TestContext testContext)
{
testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner();
TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "UpdatingOrganizationAuthorizationInformation", "", ProgrammingLanguage.CSharp, ((string[])(null)));
testRunner.OnFeatureStart(featureInfo);
}
[Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute()]
public static void FeatureTearDown()
{
testRunner.OnFeatureEnd();
testRunner = null;
}
[Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute()]
public virtual void TestInitialize()
{
if (((TechTalk.SpecFlow.FeatureContext.Current != null)
&& (TechTalk.SpecFlow.FeatureContext.Current.FeatureInfo.Title != "UpdatingOrganizationAuthorizationInformation")))
{
OrganizationRegister.AcceptanceTests.Features.Organization.UpdatingOrganizationAuthorizationInformationFeature.FeatureSetup(null);
}
}
[Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute()]
public virtual void ScenarioTearDown()
{
testRunner.OnScenarioEnd();
}
public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo)
{
testRunner.OnScenarioStart(scenarioInfo);
}
public virtual void ScenarioCleanup()
{
testRunner.CollectScenarioErrors();
}
public virtual void FeatureBackground()
{
#line 3
#line 4
testRunner.Given("there is an organization", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given ");
#line hidden
}
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
[Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Setting organization authorization information")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "UpdatingOrganizationAuthorizationInformation")]
public virtual void SettingOrganizationAuthorizationInformation()
{
TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Setting organization authorization information", ((string[])(null)));
#line 6
this.ScenarioSetup(scenarioInfo);
#line 3
this.FeatureBackground();
#line hidden
TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] {
"group name",
"group id",
"role id",
"second group name",
"second group id",
"second role id"});
table1.AddRow(new string[] {
"domain\\group1",
"87605358-1e1d-49f3-8172-63d00ad0f318",
"c0902227-a8dc-49b0-adde-6105bab48dec",
"domain\\group2",
"b2d4d59e-55df-45d6-bea3-57cd142ccf5a",
"6b8aed7c-e23f-4476-84ab-cccbfb224aba"});
#line 7
testRunner.When("the following authorization information is set to the organization:", ((string)(null)), table1, "When ");
#line hidden
TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] {
"group name",
"group id",
"role id",
"second group name",
"second group id",
"second role id"});
table2.AddRow(new string[] {
"domain\\group1",
"87605358-1e1d-49f3-8172-63d00ad0f318",
"c0902227-a8dc-49b0-adde-6105bab48dec",
"domain\\group2",
"b2d4d59e-55df-45d6-bea3-57cd142ccf5a",
"6b8aed7c-e23f-4476-84ab-cccbfb224aba"});
#line 10
testRunner.Then("the organization has the following authorization information:", ((string)(null)), table2, "Then ");
#line hidden
this.ScenarioCleanup();
}
[Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute()]
[Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute("Organization can have no authorization information")]
[Microsoft.VisualStudio.TestTools.UnitTesting.TestPropertyAttribute("FeatureTitle", "UpdatingOrganizationAuthorizationInformation")]
public virtual void OrganizationCanHaveNoAuthorizationInformation()
{
TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Organization can have no authorization information", ((string[])(null)));
#line 16
this.ScenarioSetup(scenarioInfo);
#line 3
this.FeatureBackground();
#line hidden
TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] {
"group name",
"group id",
"role id",
"second group name",
"second group id",
"second role id"});
table3.AddRow(new string[] {
"domain\\group1",
"87605358-1e1d-49f3-8172-63d00ad0f318",
"c0902227-a8dc-49b0-adde-6105bab48dec",
"domain\\group2",
"b2d4d59e-55df-45d6-bea3-57cd142ccf5a",
"6b8aed7c-e23f-4476-84ab-cccbfb224aba"});
#line 17
testRunner.Given("the following authorization information is set to the organization:", ((string)(null)), table3, "Given ");
#line 20
testRunner.When("authorization information of the organization is set as empty", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When ");
#line 21
testRunner.Then("the organization has no authorization information", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then ");
#line hidden
this.ScenarioCleanup();
}
}
}
#pragma warning restore
#endregion
| 46
| 237
| 0.608827
|
[
"MIT"
] |
City-of-Helsinki/organisaatiorekisteri
|
Source/OrganizationRegister.AcceptanceTests/Features/Organization/UpdatingOrganizationAuthorizationInformation.feature.cs
| 7,592
|
C#
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace JBV_Protocol_test
{
[TestClass]
public class RouterDuplicateTest
{
}
}
| 13.818182
| 52
| 0.730263
|
[
"MIT"
] |
vanBassum/.net_Library
|
TestProjects/ProtocolTesting/JBV Protocol test/RouterDuplicateTest.cs
| 154
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("SinchVerificationQs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SinchVerificationQs")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// 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")]
| 34.677419
| 84
| 0.745116
|
[
"MIT"
] |
NAXAM/sinch-verification-android-binding
|
demo/SinchVerificationQs/Properties/AssemblyInfo.cs
| 1,078
|
C#
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ChinookApp.Models;
namespace ChinookApp.Data
{
public class PlaylistTrackConfiguration : IEntityTypeConfiguration<PlaylistTrack>
{
public void Configure(EntityTypeBuilder<PlaylistTrack> builder)
{
builder.HasKey(x => new { x.PlaylistId, x.TrackId });
builder.ToTable("PlaylistTrack");
builder.HasOne(d => d.Playlist).WithMany(p => p.PlaylistTracks)
.HasForeignKey(x => x.PlaylistId)
.OnDelete(DeleteBehavior.ClientSetNull);
builder.HasOne(d => d.Track).WithMany(p => p.PlaylistTracks)
.HasForeignKey(x => x.TrackId)
.OnDelete(DeleteBehavior.ClientSetNull);
}
}
}
| 31.346154
| 85
| 0.646626
|
[
"Unlicense"
] |
bricelam/EFCore.TextTemplating
|
ChinookApp/Data/PlaylistTrackConfiguration.cs
| 817
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.