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 |
|---|---|---|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// (C) 2001 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
// Copyright 2013 Xamarin, Inc (http://www.xamarin.com)
//
// 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 System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Mono;
namespace System.Reflection
{
internal struct MonoPropertyInfo
{
public Type parent;
public Type declaring_type;
public string name;
public MethodInfo get_method;
public MethodInfo set_method;
public PropertyAttributes attrs;
}
[Flags]
internal enum PInfo
{
Attributes = 1,
GetMethod = 1 << 1,
SetMethod = 1 << 2,
ReflectedType = 1 << 3,
DeclaringType = 1 << 4,
Name = 1 << 5
}
internal delegate object GetterAdapter(object _this);
internal delegate R Getter<T, R>(T _this);
[StructLayout(LayoutKind.Sequential)]
internal sealed class RuntimePropertyInfo : PropertyInfo
{
#pragma warning disable 649
internal IntPtr klass;
internal IntPtr prop;
private MonoPropertyInfo info;
private PInfo cached;
private GetterAdapter? cached_getter;
#pragma warning restore 649
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void get_property_info(RuntimePropertyInfo prop, ref MonoPropertyInfo info,
PInfo req_info);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Type[] GetTypeModifiers(RuntimePropertyInfo prop, bool optional);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object get_default_value(RuntimePropertyInfo prop);
internal BindingFlags BindingFlags
{
get
{
CachePropertyInfo(PInfo.GetMethod | PInfo.SetMethod);
bool isPublic = info.set_method?.IsPublic == true || info.get_method?.IsPublic == true;
bool isStatic = info.set_method?.IsStatic == true || info.get_method?.IsStatic == true;
bool isInherited = DeclaringType != ReflectedType;
return FilterPreCalculate(isPublic, isInherited, isStatic);
}
}
// Copied from https://github.com/dotnet/coreclr/blob/7a24a538cd265993e5864179f51781398c28ecdf/src/System.Private.CoreLib/src/System/RtType.cs#L2022
private static BindingFlags FilterPreCalculate(bool isPublic, bool isInherited, bool isStatic)
{
BindingFlags bindingFlags = isPublic ? BindingFlags.Public : BindingFlags.NonPublic;
if (isInherited)
{
// We arrange things so the DeclaredOnly flag means "include inherited members"
bindingFlags |= BindingFlags.DeclaredOnly;
if (isStatic)
bindingFlags |= BindingFlags.Static | BindingFlags.FlattenHierarchy;
else
bindingFlags |= BindingFlags.Instance;
}
else
{
if (isStatic)
bindingFlags |= BindingFlags.Static;
else
bindingFlags |= BindingFlags.Instance;
}
return bindingFlags;
}
public override Module Module
{
get
{
return GetRuntimeModule();
}
}
internal RuntimeType GetDeclaringTypeInternal()
{
return (RuntimeType)DeclaringType;
}
internal RuntimeModule GetRuntimeModule()
{
return GetDeclaringTypeInternal().GetRuntimeModule();
}
#region Object Overrides
public override string ToString()
{
return FormatNameAndSig();
}
private string FormatNameAndSig()
{
StringBuilder sbName = new StringBuilder(PropertyType.FormatTypeName());
sbName.Append(' ');
sbName.Append(Name);
ParameterInfo[] pi = GetIndexParameters();
if (pi.Length > 0)
{
sbName.Append(" [");
RuntimeParameterInfo.FormatParameters(sbName, pi, 0);
sbName.Append(']');
}
return sbName.ToString();
}
#endregion
private void CachePropertyInfo(PInfo flags)
{
if ((cached & flags) != flags)
{
get_property_info(this, ref info, flags);
cached |= flags;
}
}
public override PropertyAttributes Attributes
{
get
{
CachePropertyInfo(PInfo.Attributes);
return info.attrs;
}
}
public override bool CanRead
{
get
{
CachePropertyInfo(PInfo.GetMethod);
return (info.get_method != null);
}
}
public override bool CanWrite
{
get
{
CachePropertyInfo(PInfo.SetMethod);
return (info.set_method != null);
}
}
public override Type PropertyType
{
get
{
CachePropertyInfo(PInfo.GetMethod | PInfo.SetMethod);
if (info.get_method != null)
{
return info.get_method.ReturnType;
}
else
{
ParameterInfo[] parameters = info.set_method.GetParametersInternal();
if (parameters.Length == 0)
throw new ArgumentException(SR.SetterHasNoParams, "indexer");
return parameters[parameters.Length - 1].ParameterType;
}
}
}
public override Type ReflectedType
{
get
{
CachePropertyInfo(PInfo.ReflectedType);
return info.parent;
}
}
public override Type DeclaringType
{
get
{
CachePropertyInfo(PInfo.DeclaringType);
return info.declaring_type;
}
}
public override string Name
{
get
{
CachePropertyInfo(PInfo.Name);
return info.name;
}
}
public override MethodInfo[] GetAccessors(bool nonPublic)
{
int nget = 0;
int nset = 0;
CachePropertyInfo(PInfo.GetMethod | PInfo.SetMethod);
if (info.set_method != null && (nonPublic || info.set_method.IsPublic))
nset = 1;
if (info.get_method != null && (nonPublic || info.get_method.IsPublic))
nget = 1;
MethodInfo[] res = new MethodInfo[nget + nset];
int n = 0;
if (nset != 0)
res[n++] = info.set_method!;
if (nget != 0)
res[n++] = info.get_method!;
return res;
}
public override MethodInfo? GetGetMethod(bool nonPublic)
{
CachePropertyInfo(PInfo.GetMethod);
if (info.get_method != null && (nonPublic || info.get_method.IsPublic))
return info.get_method;
else
return null;
}
public override ParameterInfo[] GetIndexParameters()
{
CachePropertyInfo(PInfo.GetMethod | PInfo.SetMethod);
ParameterInfo[] src;
int length;
if (info.get_method != null)
{
src = info.get_method.GetParametersInternal();
length = src.Length;
}
else if (info.set_method != null)
{
src = info.set_method.GetParametersInternal();
length = src.Length - 1;
}
else
return Array.Empty<ParameterInfo>();
var dest = new ParameterInfo[length];
for (int i = 0; i < length; ++i)
{
dest[i] = RuntimeParameterInfo.New(src[i], this);
}
return dest;
}
public override MethodInfo? GetSetMethod(bool nonPublic)
{
CachePropertyInfo(PInfo.SetMethod);
if (info.set_method != null && (nonPublic || info.set_method.IsPublic))
return info.set_method;
else
return null;
}
/*TODO verify for attribute based default values, just like ParameterInfo*/
public override object GetConstantValue()
{
return get_default_value(this);
}
public override object GetRawConstantValue()
{
return get_default_value(this);
}
// According to MSDN the inherit parameter is ignored here and
// the behavior always defaults to inherit = false
//
public override bool IsDefined(Type attributeType, bool inherit)
{
return CustomAttribute.IsDefined(this, attributeType, false);
}
public override object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, false);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, attributeType, false);
}
private delegate object? GetterAdapter(object? _this);
private delegate R Getter<T, R>(T _this);
private delegate R StaticGetter<R>();
#pragma warning disable 169
// Used via reflection
private static object? GetterAdapterFrame<T, R>(Getter<T, R> getter, object? obj)
{
return getter((T)obj!);
}
private static object? StaticGetterAdapterFrame<R>(StaticGetter<R> getter, object? obj)
{
return getter();
}
#pragma warning restore 169
/*
* The idea behing this optimization is to use a pair of delegates to simulate the same effect of doing a reflection call.
* The first delegate cast the this argument to the right type and the second does points to the target method.
*/
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:UnrecognizedReflectionPattern",
Justification = "MethodInfo used with MakeGenericMethod doesn't have DynamicallyAccessedMembers generic parameters")]
[DynamicDependency("GetterAdapterFrame`2")]
[DynamicDependency("StaticGetterAdapterFrame`1")]
private static GetterAdapter CreateGetterDelegate(MethodInfo method)
{
Type[] typeVector;
Type getterType;
object getterDelegate;
MethodInfo adapterFrame;
Type getterDelegateType;
string frameName;
if (method.IsStatic)
{
typeVector = new Type[] { method.ReturnType };
getterDelegateType = typeof(StaticGetter<>);
frameName = "StaticGetterAdapterFrame";
}
else
{
typeVector = new Type[] { method.DeclaringType!, method.ReturnType };
getterDelegateType = typeof(Getter<,>);
frameName = "GetterAdapterFrame";
}
getterType = getterDelegateType.MakeGenericType(typeVector);
getterDelegate = Delegate.CreateDelegate(getterType, method);
adapterFrame = typeof(RuntimePropertyInfo).GetMethod(frameName, BindingFlags.Static | BindingFlags.NonPublic)!;
adapterFrame = adapterFrame.MakeGenericMethod(typeVector);
return (GetterAdapter)Delegate.CreateDelegate(typeof(GetterAdapter), getterDelegate, adapterFrame, true);
}
public override object? GetValue(object? obj, object?[]? index)
{
if ((index == null || index.Length == 0) && RuntimeFeature.IsDynamicCodeSupported)
{
/*FIXME we should check if the number of arguments matches the expected one, otherwise the error message will be pretty criptic.*/
if (cached_getter == null)
{
MethodInfo? method = GetGetMethod(true);
if (method == null)
throw new ArgumentException($"Get Method not found for '{Name}'");
if (!DeclaringType.IsValueType && !PropertyType.IsByRef && !method.ContainsGenericParameters)
{
//FIXME find a way to build an invoke delegate for value types.
cached_getter = CreateGetterDelegate(method);
// The try-catch preserves the .Invoke () behaviour
try
{
return cached_getter(obj);
}
catch (Exception ex)
{
throw new TargetInvocationException(ex);
}
}
}
else
{
try
{
return cached_getter(obj);
}
catch (Exception ex)
{
throw new TargetInvocationException(ex);
}
}
}
return GetValue(obj, BindingFlags.Default, null, index, null);
}
public override object? GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture)
{
object? ret;
MethodInfo? method = GetGetMethod(true);
if (method == null)
throw new ArgumentException($"Get Method not found for '{Name}'");
if (index == null || index.Length == 0)
ret = method.Invoke(obj, invokeAttr, binder, null, culture);
else
ret = method.Invoke(obj, invokeAttr, binder, index, culture);
return ret;
}
public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture)
{
MethodInfo? method = GetSetMethod(true);
if (method == null)
throw new ArgumentException("Set Method not found for '" + Name + "'");
object?[] parms;
if (index == null || index.Length == 0)
parms = new object?[] { value };
else
{
int ilen = index.Length;
parms = new object[ilen + 1];
index.CopyTo(parms, 0);
parms[ilen] = value;
}
method.Invoke(obj, invokeAttr, binder, parms, culture);
}
public override Type[] GetOptionalCustomModifiers() => GetCustomModifiers(true);
public override Type[] GetRequiredCustomModifiers() => GetCustomModifiers(false);
private Type[] GetCustomModifiers(bool optional) => GetTypeModifiers(this, optional) ?? Type.EmptyTypes;
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return RuntimeCustomAttributeData.GetCustomAttributesInternal(this);
}
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimePropertyInfo>(other);
public override int MetadataToken
{
get
{
return get_metadata_token(this);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int get_metadata_token(RuntimePropertyInfo monoProperty);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern PropertyInfo internal_from_handle_type(IntPtr event_handle, IntPtr type_handle);
internal static PropertyInfo GetPropertyFromHandle(RuntimePropertyHandle handle, RuntimeTypeHandle reflectedType)
{
if (handle.Value == IntPtr.Zero)
throw new ArgumentException("The handle is invalid.");
PropertyInfo pi = internal_from_handle_type(handle.Value, reflectedType.Value);
if (pi == null)
throw new ArgumentException("The property handle and the type handle are incompatible.");
return pi;
}
}
}
| 35.124756 | 156 | 0.569232 | [
"MIT"
] | 333fred/runtime | src/mono/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs | 18,019 | C# |
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Json.Schema;
/// <summary>
/// Handles `multipleOf`.
/// </summary>
[SchemaKeyword(Name)]
[SchemaDraft(Draft.Draft6)]
[SchemaDraft(Draft.Draft7)]
[SchemaDraft(Draft.Draft201909)]
[SchemaDraft(Draft.Draft202012)]
[Vocabulary(Vocabularies.Validation201909Id)]
[Vocabulary(Vocabularies.Validation202012Id)]
[JsonConverter(typeof(MultipleOfKeywordJsonConverter))]
public class MultipleOfKeyword : IJsonSchemaKeyword, IEquatable<MultipleOfKeyword>
{
internal const string Name = "multipleOf";
/// <summary>
/// The expected divisor of a value.
/// </summary>
public decimal Value { get; }
/// <summary>
/// Creates a new <see cref="MultipleOfKeyword"/>.
/// </summary>
/// <param name="value">The expected divisor of a value.</param>
public MultipleOfKeyword(decimal value)
{
Value = value;
}
/// <summary>
/// Provides validation for the keyword.
/// </summary>
/// <param name="context">Contextual details for the validation process.</param>
public void Validate(ValidationContext context)
{
context.EnterKeyword(Name);
if (context.LocalInstance.ValueKind != JsonValueKind.Number)
{
context.LocalResult.Pass();
context.WrongValueKind(context.LocalInstance.ValueKind);
return;
}
var number = context.LocalInstance.GetDecimal();
if (number % Value == 0)
context.LocalResult.Pass();
else
context.LocalResult.Fail($"{number} a multiple of {Value}");
context.ExitKeyword(Name, context.LocalResult.IsValid);
}
/// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>true if the current object is equal to the <paramref name="other">other</paramref> parameter; otherwise, false.</returns>
public bool Equals(MultipleOfKeyword? other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Value == other.Value;
}
/// <summary>Determines whether the specified object is equal to the current object.</summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
public override bool Equals(object obj)
{
return Equals(obj as MultipleOfKeyword);
}
/// <summary>Serves as the default hash function.</summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode()
{
return Value.GetHashCode();
}
}
internal class MultipleOfKeywordJsonConverter : JsonConverter<MultipleOfKeyword>
{
public override MultipleOfKeyword Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.Number)
throw new JsonException("Expected number");
var number = reader.GetDecimal();
return new MultipleOfKeyword(number);
}
public override void Write(Utf8JsonWriter writer, MultipleOfKeyword value, JsonSerializerOptions options)
{
writer.WriteNumber(MultipleOfKeyword.Name, value.Value);
}
} | 31.929293 | 135 | 0.743119 | [
"MIT"
] | beachwalker/json-everything | JsonSchema/MultipleOfKeyword.cs | 3,163 | C# |
using Structure.Sketching.Tests.Formats.BaseClasses;
using System.IO;
using Xunit;
namespace Structure.Sketching.Tests.Formats.Jpeg
{
public class JpegFormat : FormatTestBase
{
public override string ExpectedDirectory => "./ExpectedResults/Formats/Jpg/";
public override string InputDirectory => "./TestImages/Formats/Jpg/";
public override string OutputDirectory => "./TestOutput/Formats/Jpg/";
public static readonly TheoryData<string> InputFileNames = new TheoryData<string> {
{"Calliphora.jpg"},
{"Floorplan.jpeg"},
{"gamma_dalai_lama_gray.jpg"},
{"rgb.jpg"},
{"maltese_puppy-wide.jpg"}
};
[Theory]
[MemberData("InputFileNames")]
public void Encode(string fileName)
{
using (var TempFile = File.OpenRead(InputDirectory + fileName))
{
var ImageFormat = new Sketching.Formats.Jpeg.JpegFormat();
var TempImage = ImageFormat.Decode(TempFile);
using (var TempFile2 = File.OpenWrite(OutputDirectory + fileName))
{
Assert.True(ImageFormat.Encode(new BinaryWriter(TempFile2), TempImage));
}
}
Assert.True(CheckFileCorrect(fileName));
}
}
} | 35.358974 | 93 | 0.583031 | [
"Apache-2.0"
] | JaCraig/Structure.Sketching | Structure.Sketching.Tests/Formats/Jpeg/JpegFormat.cs | 1,381 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.ImportExport;
using Amazon.ImportExport.Model;
namespace Amazon.PowerShell.Cmdlets.IE
{
[AWSClientCmdlet("AWS Import/Export", "IE", "2010-06-01", "ImportExport")]
public abstract partial class AmazonImportExportClientCmdlet : ServiceCmdlet
{
protected IAmazonImportExport Client { get; private set; }
protected override string _DefaultRegion
{
get
{
return "us-east-1";
}
}
protected IAmazonImportExport CreateClient(AWSCredentials credentials, RegionEndpoint region)
{
var config = new AmazonImportExportConfig { RegionEndpoint = region };
Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
this.CustomizeClientConfig(config);
var client = new AmazonImportExportClient(credentials, config);
client.BeforeRequestEvent += RequestEventHandler;
client.AfterResponseEvent += ResponseEventHandler;
return client;
}
protected override void ProcessRecord()
{
base.ProcessRecord();
Client = CreateClient(_CurrentCredentials, _RegionEndpoint);
}
}
}
| 36.966667 | 101 | 0.627142 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/ImportExport/AmazonImportExportClientCmdlet.cs | 2,218 | C# |
namespace SoManyBooksSoLittleTime.Services
{
using System.Threading.Tasks;
public interface IGoodreadsScraperService
{
Task PopulateDbWithBooksAsync(int booksCount);
}
}
| 19.6 | 54 | 0.739796 | [
"MIT"
] | RadostinaPetrova/SoManyBooksSoLittleTime | Services/SoManyBooksSoLittleTime.Services/IGoodReadsScraperService.cs | 198 | C# |
using Volo.Abp.Threading;
namespace BookStore
{
public static class BookStoreGlobalFeatureConfigurator
{
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
public static void Configure()
{
OneTimeRunner.Run(() =>
{
/* You can configure (enable/disable) global features of the used modules here.
*
* YOU CAN SAFELY DELETE THIS CLASS AND REMOVE ITS USAGES IF YOU DON'T NEED TO IT!
*
* Please refer to the documentation to lear more about the Global Features System:
* https://docs.abp.io/en/abp/latest/Global-Features
*/
});
}
}
}
| 31.416667 | 99 | 0.562334 | [
"MIT"
] | 271943794/abp-samples | BlazorPageUniTest/src/BookStore.Domain.Shared/BookStoreGlobalFeatureConfigurator.cs | 756 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using Robust.Shared.Serialization.Manager.Attributes;
namespace OpenDreamShared.Interface {
public class InterfaceDescriptor {
public List<WindowDescriptor> WindowDescriptors;
public List<MacroSetDescriptor> MacroSetDescriptors;
public Dictionary<string, MenuDescriptor> MenuDescriptors;
public InterfaceDescriptor(List<WindowDescriptor> windowDescriptors, List<MacroSetDescriptor> macroSetDescriptors, Dictionary<string, MenuDescriptor> menuDescriptors) {
WindowDescriptors = windowDescriptors;
MacroSetDescriptors = macroSetDescriptors;
MenuDescriptors = menuDescriptors;
}
}
[ImplicitDataDefinitionForInheritors]
public class ElementDescriptor {
[DataField("name")]
public string Name;
}
}
| 35.28 | 176 | 0.741497 | [
"MIT"
] | DamianX/OpenDream | OpenDreamShared/Interface/InterfaceDescriptor.cs | 884 | C# |
/*
* Copyright (c) 2020 ETH Zürich, Educational Development and Technology (LET)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
namespace SafeExamBrowser.Lockdown.Contracts
{
/// <summary>
/// Allows to control a feature of the computer, the operating system or an installed software.
/// </summary>
public interface IFeatureConfiguration
{
/// <summary>
/// The unique identifier of this feature configuration.
/// </summary>
Guid Id { get; }
/// <summary>
/// The identifier of the group of changes to which this feature configuration belongs.
/// </summary>
Guid GroupId { get; }
/// <summary>
/// Disables the feature. Returns <c>true</c> if successful, otherwise <c>false</c>.
/// </summary>
bool DisableFeature();
/// <summary>
/// Enables the feature. Returns <c>true</c> if successful, otherwise <c>false</c>.
/// </summary>
bool EnableFeature();
/// <summary>
/// Retrieves the current status of the configuration.
/// </summary>
FeatureConfigurationStatus GetStatus();
/// <summary>
/// Initializes the currently active configuration of the feature.
/// </summary>
void Initialize();
/// <summary>
/// Resets the feature to its default configuration. Returns <c>true</c> if successful, otherwise <c>false</c>.
/// </summary>
bool Reset();
/// <summary>
/// Restores the feature to its previous configuration (i.e. before it was enabled or disabled). Returns <c>true</c> if successful,
/// otherwise <c>false</c>.
/// </summary>
bool Restore();
}
}
| 28.616667 | 133 | 0.668608 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | 20162026/seb-win-refactoring | SafeExamBrowser.Lockdown.Contracts/IFeatureConfiguration.cs | 1,720 | 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("5. Third Digit is")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("5. Third Digit is")]
[assembly: AssemblyCopyright("Copyright © 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("139cb3df-c63d-4f07-99a6-42196505fb49")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.741294 | [
"MIT"
] | Roskataa/Telerik-Homework-C-Part-1 | Operators and expresions/Operators and Expressions/05. Third Digit is/Properties/AssemblyInfo.cs | 1,410 | C# |
using MinecraftMappings.Internal.Textures.Block;
namespace MinecraftMappings.Minecraft.Bedrock.Textures.Block
{
public class GlassBlack : BedrockBlockTexture
{
public GlassBlack() : base("Glass Black")
{
AddVersion("glass_black")
.MapsToJavaBlock<Java.Textures.Block.BlackStainedGlass>();
}
}
}
| 25.785714 | 74 | 0.65928 | [
"MIT"
] | null511/MinecraftMappings.NET | MinecraftMappings.NET/Minecraft/Bedrock/Textures/Block/GlassBlack.cs | 363 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using projeto_pratica_api.Data;
using projeto_pratica_api.models;
namespace projeto_pratica_api.Controllers
{
[Route("/mapa")]
[ApiController]
public class PaisesController : Controller
{
public IRepositoryMM_Paises Repo { get; }
public PaisesController(IRepositoryMM_Paises repo)
{
this.Repo = repo;
}
[HttpGet]
public async Task<IActionResult> Get()
{
try
{
var result = await this.Repo.GetAllPaisesAsync();
return Ok(result);
}
catch (System.Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
ex.Message);
}
}
[HttpGet("{codPais}")]
public async Task<IActionResult> Get(int codPais)
{
try
{
var result = await this.Repo.GetAllPaisesAsyncByCod(codPais);
return Ok(result);
}
catch (System.Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError,
ex.Message);
}
}
}
} | 27.122449 | 80 | 0.544771 | [
"MIT"
] | Platinamaster1/-_PROJECT---COTUCA | projeto_pratica_api/Controllers/PaisesController.cs | 1,329 | C# |
using ModernWpf.Controls;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
namespace DGP.Genshin.Control.Infrastructure.CachedImage
{
[TypeConverter(typeof(IconElementConverter))]
public abstract class CachedIconElementBase : FrameworkElement
{
private protected CachedIconElementBase()
{
}
#region Foreground
/// <summary>
/// Identifies the Foreground dependency property.
/// </summary>
public static readonly DependencyProperty ForegroundProperty =
TextElement.ForegroundProperty.AddOwner(
typeof(CachedIconElementBase),
new FrameworkPropertyMetadata(SystemColors.ControlTextBrush,
FrameworkPropertyMetadataOptions.Inherits,
OnForegroundPropertyChanged));
private static void OnForegroundPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((CachedIconElementBase)sender).OnForegroundPropertyChanged(args);
}
private void OnForegroundPropertyChanged(DependencyPropertyChangedEventArgs args)
{
BaseValueSource baseValueSource = DependencyPropertyHelper.GetValueSource(this, args.Property).BaseValueSource;
_isForegroundDefaultOrInherited = baseValueSource <= BaseValueSource.Inherited;
UpdateShouldInheritForegroundFromVisualParent();
}
/// <summary>
/// Gets or sets a brush that describes the foreground color.
/// </summary>
/// <returns>
/// The brush that paints the foreground of the control.
/// </returns>
[Bindable(true), Category("Appearance")]
public Brush Foreground
{
get => (Brush)GetValue(ForegroundProperty);
set => SetValue(ForegroundProperty, value);
}
#endregion
#region VisualParentForeground
private static readonly DependencyProperty VisualParentForegroundProperty =
DependencyProperty.Register(
nameof(VisualParentForeground),
typeof(Brush),
typeof(CachedIconElementBase),
new PropertyMetadata(null, OnVisualParentForegroundPropertyChanged));
private protected Brush VisualParentForeground
{
get => (Brush)GetValue(VisualParentForegroundProperty);
set => SetValue(VisualParentForegroundProperty, value);
}
private static void OnVisualParentForegroundPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((CachedIconElementBase)sender).OnVisualParentForegroundPropertyChanged(args);
}
private protected virtual void OnVisualParentForegroundPropertyChanged(DependencyPropertyChangedEventArgs args)
{
}
#endregion
private protected bool ShouldInheritForegroundFromVisualParent
{
get => _shouldInheritForegroundFromVisualParent;
private set
{
if (_shouldInheritForegroundFromVisualParent != value)
{
_shouldInheritForegroundFromVisualParent = value;
if (_shouldInheritForegroundFromVisualParent)
{
SetBinding(VisualParentForegroundProperty,
new Binding
{
Path = new PropertyPath(TextElement.ForegroundProperty),
Source = VisualParent
});
}
else
{
ClearValue(VisualParentForegroundProperty);
}
OnShouldInheritForegroundFromVisualParentChanged();
}
}
}
private protected virtual void OnShouldInheritForegroundFromVisualParentChanged()
{
}
private void UpdateShouldInheritForegroundFromVisualParent()
{
ShouldInheritForegroundFromVisualParent =
_isForegroundDefaultOrInherited &&
Parent != null &&
VisualParent != null &&
Parent != VisualParent;
}
private protected UIElementCollection Children
{
get
{
EnsureLayoutRoot();
Debug.Assert(_layoutRoot is not null);
return _layoutRoot.Children;
}
}
private protected abstract void InitializeChildren();
protected override int VisualChildrenCount
{
get => 1;
}
protected override Visual GetVisualChild(int index)
{
if (index == 0)
{
EnsureLayoutRoot();
Debug.Assert(_layoutRoot is not null);
return _layoutRoot;
}
else
{
throw new ArgumentOutOfRangeException(nameof(index));
}
}
protected override Size MeasureOverride(Size availableSize)
{
EnsureLayoutRoot();
Debug.Assert(_layoutRoot is not null);
_layoutRoot.Measure(availableSize);
return _layoutRoot.DesiredSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
EnsureLayoutRoot();
Debug.Assert(_layoutRoot is not null);
_layoutRoot.Arrange(new Rect(new Point(), finalSize));
return finalSize;
}
protected override void OnVisualParentChanged(DependencyObject oldParent)
{
base.OnVisualParentChanged(oldParent);
UpdateShouldInheritForegroundFromVisualParent();
}
private void EnsureLayoutRoot()
{
if (_layoutRoot != null)
{
return;
}
_layoutRoot = new Grid
{
Background = Brushes.Transparent,
SnapsToDevicePixels = true,
};
InitializeChildren();
AddVisualChild(_layoutRoot);
}
private Grid? _layoutRoot;
private bool _isForegroundDefaultOrInherited = true;
private bool _shouldInheritForegroundFromVisualParent;
}
}
| 32.416667 | 133 | 0.587933 | [
"MIT"
] | CzHUV/Snap.Genshin | DGP.Genshin/Control/Infrastructure/CachedImage/CachedIconElementBase.cs | 6,615 | C# |
using System;
using AVFoundation;
using Foundation;
using Photos;
using UIKit;
namespace Softeq.ImagePicker.Media.Delegates
{
public class VideoCaptureDelegate : AVCaptureFileOutputRecordingDelegate
{
private nint? _backgroundRecordingId;
private readonly Action _didStart;
private readonly Action<VideoCaptureDelegate> _didFinish;
private readonly Action<VideoCaptureDelegate, NSError> _didFail;
/// <summary>
/// set this to false if you don't wish to save video to photo library
/// </summary>
public bool ShouldSaveVideoToLibrary = true;
/// <summary>
/// true if user manually requested to cancel recording (stop without saving)
/// </summary>
public bool IsBeingCancelled = false;
/// <summary>
/// if system interrupts recording due to various reasons (empty space, phone call, background, ...)
/// </summary>
public bool RecordingWasInterrupted = false;
/// <summary>
/// non null if failed or interrupted, null if cancelled
/// </summary>
/// <param name="didStart">Did start.</param>
/// <param name="didFinish">Did finish.</param>
/// <param name="didFail">Did fail.</param>
public VideoCaptureDelegate(Action didStart, Action<VideoCaptureDelegate> didFinish,
Action<VideoCaptureDelegate, NSError> didFail)
{
_didStart = didStart;
_didFinish = didFinish;
_didFail = didFail;
if (UIDevice.CurrentDevice.IsMultitaskingSupported)
{
/*
Setup background task.
This is needed because the `capture(_:, didFinishRecordingToOutputFileAt:, fromConnections:, error:)`
callback is not received until AVCam returns to the foreground unless you request background execution time.
This also ensures that there will be time to write the file to the photo library when AVCam is backgrounded.
To conclude this background execution, endBackgroundTask(_:) is called in
`capture(_:, didFinishRecordingToOutputFileAt:, fromConnections:, error:)` after the recorded file has been saved.
*/
_backgroundRecordingId = UIApplication.SharedApplication.BeginBackgroundTask(null);
}
}
public override void DidStartRecording(AVCaptureFileOutput captureOutput, NSUrl outputFileUrl,
NSObject[] connections)
{
_didStart?.Invoke();
}
public override void FinishedRecording(AVCaptureFileOutput captureOutput, NSUrl outputFileUrl,
NSObject[] connections,
NSError error)
{
if (error != null)
{
HandleCaptureResultWithError(error, outputFileUrl);
}
else if (IsBeingCancelled)
{
CleanUp(false, outputFileUrl);
_didFinish.Invoke(this);
}
else
{
CleanUp(ShouldSaveVideoToLibrary, outputFileUrl);
_didFinish.Invoke(this);
}
}
private void SaveVideoToLibrary(NSUrl outputFileUrl)
{
var creationRequest = PHAssetCreationRequest.CreationRequestForAsset();
var videoResourceOptions = new PHAssetResourceCreationOptions {ShouldMoveFile = true};
creationRequest.AddResource(PHAssetResourceType.Video, outputFileUrl,
videoResourceOptions);
}
private void HandleCaptureResultWithError(NSError error, NSUrl outputFileUrl)
{
Console.WriteLine($"capture session: movie recording failed error: {error}");
//this can be true even if recording is stopped due to a reason (no disk space, ...) so the video can still be delivered.
var successfullyFinished =
(error.UserInfo[AVErrorKeys.RecordingSuccessfullyFinished] as NSNumber)?.BoolValue;
if (successfullyFinished == true)
{
CleanUp(ShouldSaveVideoToLibrary, outputFileUrl);
_didFail.Invoke(this, error);
}
else
{
CleanUp(false, outputFileUrl);
_didFail.Invoke(this, error);
}
}
private void CleanUp(bool saveToAssets, NSUrl outputFileUrl)
{
if (_backgroundRecordingId != null)
{
if (_backgroundRecordingId != UIApplication.BackgroundTaskInvalid)
{
UIApplication.SharedApplication.EndBackgroundTask(_backgroundRecordingId.Value);
}
_backgroundRecordingId = UIApplication.BackgroundTaskInvalid;
}
if (!saveToAssets)
{
DeleteFileIfNeeded(outputFileUrl);
return;
}
PHAssetManager.PerformChangesWithAuthorization(() => SaveVideoToLibrary(outputFileUrl),
() => DeleteFileIfNeeded(outputFileUrl), null);
}
private void DeleteFileIfNeeded(NSUrl outputFileUrl)
{
if (NSFileManager.DefaultManager.FileExists(outputFileUrl.Path))
{
return;
}
NSFileManager.DefaultManager.Remove(outputFileUrl.Path, out var nsError);
if (nsError != null)
{
Console.WriteLine($"capture session: could not remove recording at url: {outputFileUrl}");
Console.WriteLine($"capture session: error: {nsError}");
}
}
}
} | 39.146667 | 134 | 0.583447 | [
"MIT"
] | JKLumirithmic/ImagePicker-xamarin-ios | Softeq.ImagePicker/Media/Delegates/VideoCaptureDelegate.cs | 5,872 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Ecs.V2.Model
{
/// <summary>
/// 更新云服务器Body体。
/// </summary>
public class UpdateServerOption
{
/// <summary>
/// 修改后的云服务器名称。 只能由中文字符、英文字母、数字及“_”、“-”、“.”组成,且长度为[1-64]个字符。
/// </summary>
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
/// <summary>
/// 对弹性云服务器的任意描述。 不能包含“<”,“>”,且长度范围为[0-85]个字符。
/// </summary>
[JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
/// <summary>
/// 修改云服务hostname。 命令规范:长度为 [1-64] 个字符,允许使用点号(.)分隔字符成多段,每段允许使用大小写字母、数字或连字符(-),但不能连续使用点号(.)或连字符(-),不能以点号(.)或连字符(-)开头或结尾,不能出现(.-)和(-.)。
/// </summary>
[JsonProperty("hostname", NullValueHandling = NullValueHandling.Ignore)]
public string Hostname { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UpdateServerOption {\n");
sb.Append(" name: ").Append(Name).Append("\n");
sb.Append(" description: ").Append(Description).Append("\n");
sb.Append(" hostname: ").Append(Hostname).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as UpdateServerOption);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(UpdateServerOption input)
{
if (input == null)
return false;
return
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.Description == input.Description ||
(this.Description != null &&
this.Description.Equals(input.Description))
) &&
(
this.Hostname == input.Hostname ||
(this.Hostname != null &&
this.Hostname.Equals(input.Hostname))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.Description != null)
hashCode = hashCode * 59 + this.Description.GetHashCode();
if (this.Hostname != null)
hashCode = hashCode * 59 + this.Hostname.GetHashCode();
return hashCode;
}
}
}
}
| 32.173077 | 142 | 0.501793 | [
"Apache-2.0"
] | Huaweicloud-SDK/huaweicloud-sdk-net-v3 | Services/Ecs/V2/Model/UpdateServerOption.cs | 3,696 | C# |
using System;
namespace POETradeHelper.ItemSearch.Exceptions
{
public class ParserException : Exception
{
protected string ItemString { get; }
public ParserException(string itemString) : this(itemString, null, null)
{
}
public ParserException(string itemString, string message) : this(itemString, message, null)
{
}
public ParserException(string itemString, string message, Exception innerException) : base(message, innerException)
{
this.ItemString = itemString;
}
public ParserException(string[] itemStringLines) : this(itemStringLines, null, null)
{
}
public ParserException(string[] itemStringLines, string message) : this(itemStringLines, message, null)
{
}
public ParserException(string[] itemStringLines, string message, Exception innerException) : base(message, innerException)
{
this.ItemString = string.Join(Environment.NewLine, itemStringLines);
}
}
} | 30.228571 | 130 | 0.649338 | [
"Apache-2.0",
"MIT"
] | alueck/POE-TradeHelper | Source/POETradeHelper.ItemSearch/Exceptions/ParserException.cs | 1,060 | 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 WFPrint.Properties
{
/// <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 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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WFPrint.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;
}
}
}
}
| 38.486111 | 173 | 0.601949 | [
"MIT"
] | ShashangkaShekhar/Windows-FormPrinting | WFPrint/Properties/Resources.Designer.cs | 2,773 | C# |
namespace BattleshipLiteCP.Logic;
public class BattleshipCollection : IBoardCollection<ShipInfo>
{
private readonly BoardCollection<ShipInfo> _privateBoard;
public ShipInfo this[int row, int column]
{
get
{
return _privateBoard[row, column];
}
}
public ShipInfo this[Vector thisV] //when you click, it has to be a vector.
{
get
{
return _privateBoard[thisV];
}
}
public BattleshipCollection()
{
_privateBoard = new(5, 5); //because we know its 5 by 5.
}
public BattleshipCollection(IEnumerable<ShipInfo> previousList)
{
_privateBoard = new(previousList);
}
public IEnumerator<ShipInfo> GetEnumerator()
{
return _privateBoard.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _privateBoard.GetEnumerator();
}
public int GetTotalColumns()
{
return _privateBoard.GetTotalColumns();
}
public int GetTotalRows()
{
return _privateBoard.GetTotalRows();
}
} | 25.302326 | 79 | 0.625 | [
"MIT"
] | musictopia2/GamingPackXV3 | CP/Games/BattleshipLiteCP/Logic/BattleshipCollection.cs | 1,090 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IEntityRequestBuilder.cs.tt
namespace Microsoft.Graph.Ediscovery
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface INoncustodialDataSourceRequestBuilder.
/// </summary>
public partial interface INoncustodialDataSourceRequestBuilder : IDataSourceContainerRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
new INoncustodialDataSourceRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
new INoncustodialDataSourceRequest Request(IEnumerable<Microsoft.Graph.Option> options);
/// <summary>
/// Gets the request builder for DataSource.
/// </summary>
/// <returns>The <see cref="IDataSourceRequestBuilder"/>.</returns>
IDataSourceRequestBuilder DataSource { get; }
/// <summary>
/// Gets the request builder for NoncustodialDataSourceApplyHold.
/// </summary>
/// <returns>The <see cref="INoncustodialDataSourceApplyHoldRequestBuilder"/>.</returns>
INoncustodialDataSourceApplyHoldRequestBuilder ApplyHold();
/// <summary>
/// Gets the request builder for NoncustodialDataSourceRelease.
/// </summary>
/// <returns>The <see cref="INoncustodialDataSourceReleaseRequestBuilder"/>.</returns>
INoncustodialDataSourceReleaseRequestBuilder Release();
/// <summary>
/// Gets the request builder for NoncustodialDataSourceRemoveHold.
/// </summary>
/// <returns>The <see cref="INoncustodialDataSourceRemoveHoldRequestBuilder"/>.</returns>
INoncustodialDataSourceRemoveHoldRequestBuilder RemoveHold();
/// <summary>
/// Gets the request builder for NoncustodialDataSourceUpdateIndex.
/// </summary>
/// <returns>The <see cref="INoncustodialDataSourceUpdateIndexRequestBuilder"/>.</returns>
INoncustodialDataSourceUpdateIndexRequestBuilder UpdateIndex();
}
}
| 40.69697 | 153 | 0.626955 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/ediscovery/requests/INoncustodialDataSourceRequestBuilder.cs | 2,686 | C# |
using System;
using System.Threading;
namespace SystemDot.Messaging.Batching
{
public class Batch : Disposable
{
static readonly ThreadLocal<Batch> current = new ThreadLocal<Batch>();
bool completed;
public static Batch GetCurrent()
{
return current.Value;
}
static void SetCurrent(Batch toSet)
{
current.Value = toSet;
}
public static bool HasAggregateStarted()
{
return GetCurrent() != null;
}
public event Action<bool> Finished;
public Batch()
{
SetCurrent(this);
}
protected override void DisposeOfManagedResources()
{
OnFinished();
SetCurrent(null);
base.DisposeOfManagedResources();
}
void OnFinished()
{
if (this.Finished != null) this.Finished(this.completed);
}
public void Complete()
{
this.completed = true;
}
}
} | 20.509804 | 78 | 0.528681 | [
"Apache-2.0"
] | SystemDot/SystemDotServiceBus | SystemDotMessaging/Projects/SystemDot.Messaging/Batching/Batch.cs | 1,046 | C# |
using System;
using System.Collections.Generic;
namespace Blackjack
{
public class Hand
{
private readonly List<Card> _cards = new List<Card>(12);
private int _cachedTotal = 0;
public Card AddCard(Card card)
{
_cards.Add(card);
_cachedTotal = 0;
return card;
}
public void Discard(Deck deck)
{
deck.Discard(_cards);
_cards.Clear();
_cachedTotal = 0;
}
public void SplitHand(Hand secondHand)
{
if (Count != 2 || secondHand.Count != 0)
throw new InvalidOperationException();
secondHand.AddCard(_cards[1]);
_cards.RemoveAt(1);
_cachedTotal = 0;
}
public IReadOnlyList<Card> Cards => _cards;
public int Count => _cards.Count;
public bool Exists => _cards.Count > 0;
public int Total
{
get
{
if (_cachedTotal == 0)
{
var aceCount = 0;
foreach (var card in _cards)
{
_cachedTotal += card.Value;
if (card.IsAce)
aceCount++;
}
while (_cachedTotal > 21 && aceCount > 0)
{
_cachedTotal -= 10;
aceCount--;
}
}
return _cachedTotal;
}
}
public bool IsBlackjack => Total == 21 && Count == 2;
public bool IsBusted => Total > 21;
}
}
| 24.882353 | 64 | 0.429669 | [
"Unlicense"
] | AMKballer/basic-computer-games | 10 Blackjack/csharp/Hand.cs | 1,692 | C# |
namespace Gu.Wpf.NumericInput
{
using System.Runtime.CompilerServices;
using System.Windows;
/// <summary>
/// Resource keys for <see cref="NumericBox"/>
/// </summary>
public static partial class NumericBox
{
public static ResourceKey IncreaseGeometryKey { get; } = CreateKey();
public static ResourceKey DecreaseGeometryKey { get; } = CreateKey();
public static ResourceKey SpinnerButtonStyleKey { get; } = CreateKey();
public static ResourceKey SpinnerPathStyleKey { get; } = CreateKey();
public static ResourceKey ValidationErrorRedBorderTemplateKey { get; } = CreateKey();
public static ResourceKey ValidationErrorTextUnderTemplateKey { get; } = CreateKey();
public static ResourceKey ValidationErrorListTemplateKey { get; } = CreateKey();
public static ResourceKey SimpleValidationErrorTemplateKey { get; } = CreateKey();
public static ResourceKey SpinnersTemplateKey { get; } = CreateKey();
private static ComponentResourceKey CreateKey([CallerMemberName] string caller = null)
{
// ReSharper disable once AssignNullToNotNullAttribute
return new ComponentResourceKey(typeof(NumericBox), caller);
}
}
}
| 35.333333 | 94 | 0.687893 | [
"MIT"
] | forki/Gu.Wpf.NumericInput | Gu.Wpf.NumericInput/Boxes/NumericBox.Keys.cs | 1,274 | C# |
using System.IO;
namespace MatrixIO.IO.Bmff.Boxes
{
/// <summary>
/// Movie Extends Header Box ("mehd")
/// </summary>
[Box("mehd", "Movie Extends Header Box")]
public sealed class MovieExtendsHeaderBox : FullBox
{
public MovieExtendsHeaderBox()
: base() { }
public MovieExtendsHeaderBox(Stream stream)
: base(stream) { }
public ulong FragmentDuration { get; set; }
internal override ulong CalculateSize()
{
return base.CalculateSize() + (Version == 1 ? (ulong)8 : 4);
}
protected override void LoadFromStream(Stream stream)
{
base.LoadFromStream(stream);
FragmentDuration = (Version == 1) ? stream.ReadBEUInt64() : (ulong)stream.ReadBEInt32();
}
protected override void SaveToStream(Stream stream)
{
if (FragmentDuration > uint.MaxValue)
{
Version = 1;
}
base.SaveToStream(stream);
if (Version == 1)
{
stream.WriteBEUInt64(FragmentDuration);
}
else
{
stream.WriteBEUInt32((uint)FragmentDuration);
}
}
}
} | 25.36 | 100 | 0.525237 | [
"MIT"
] | NiklasArbin/bmff | MatrixIO.IO.Bmff/IO/Bmff/Boxes/MovieExtendsHeaderBox.cs | 1,270 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Funq;
using ServiceStack;
using ServiceStack.Configuration;
using Chinook.ServiceInterface;
namespace Chinook
{
public class Startup : ModularStartup
{
// 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 new void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseServiceStack(new AppHost
{
AppSettings = new NetCoreAppSettings(Configuration)
});
}
}
public class AppHost : AppHostBase
{
public AppHost() : base("Chinook", typeof(MyServices).Assembly) { }
// Configure your AppHost with the necessary configuration and dependencies your App needs
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)
});
}
}
}
| 32.18 | 122 | 0.65693 | [
"MIT"
] | alexeidzoto/demo-devexpress | stack/db/chinook/Chinook/Startup.cs | 1,609 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\mfidl.h(18377,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[Guid("c5bc37d6-75c7-46a1-a132-81b5f723c20f"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IMFMediaStream2 : IMFMediaStream
{
// IMFMediaEventGenerator
[PreserveSig]
new HRESULT GetEvent(/* [in] */ uint dwFlags, /* [out] __RPC__deref_out_opt */ out IMFMediaEvent ppEvent);
[PreserveSig]
new HRESULT BeginGetEvent(/* [in] */ IMFAsyncCallback pCallback, /* [in] */ [MarshalAs(UnmanagedType.IUnknown)] object punkState);
[PreserveSig]
new HRESULT EndGetEvent(/* [in] */ IMFAsyncResult pResult, /* [annotation][out] _Out_ */ out IMFMediaEvent ppEvent);
[PreserveSig]
new HRESULT QueueEvent(/* [in] */ uint met, /* [in] __RPC__in */ [MarshalAs(UnmanagedType.LPStruct)] Guid guidExtendedType, /* [in] */ HRESULT hrStatus, /* [unique][in] __RPC__in_opt */ [In, Out] PropVariant pvValue);
// IMFMediaStream
[PreserveSig]
new HRESULT GetMediaSource(/* [out] __RPC__deref_out_opt */ out IMFMediaSource ppMediaSource);
[PreserveSig]
new HRESULT GetStreamDescriptor(/* [out] __RPC__deref_out_opt */ out IMFStreamDescriptor ppStreamDescriptor);
[PreserveSig]
new HRESULT RequestSample(/* [in] */ [MarshalAs(UnmanagedType.IUnknown)] object pToken);
// IMFMediaStream2
[PreserveSig]
HRESULT SetStreamState(/* [annotation][in] _In_ */ _MF_STREAM_STATE value);
[PreserveSig]
HRESULT GetStreamState(/* [annotation][out] _Out_ */ out _MF_STREAM_STATE value);
}
}
| 43.682927 | 225 | 0.653825 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/IMFMediaStream2.cs | 1,793 | 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;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
namespace System.Data
{
/// <summary>
/// Represents a bindable, queryable DataView of DataRow, that can be created from from LINQ queries over DataTable
/// and from DataTable.
/// </summary>
internal sealed class LinqDataView : DataView, IBindingList, IBindingListView
{
/// <summary>
/// A Comparer that compares a Key and a Row.
/// </summary>
internal Func<object, DataRow, int>? comparerKeyRow; // comparer for DataView.Find(..
/// <summary>
/// Builds the sort expression in case multiple selector/comparers are added.
/// </summary>
internal readonly SortExpressionBuilder<DataRow>? sortExpressionBuilder;
/// <summary>
/// Constructs a LinkDataView and its parent DataView.
/// Does not create index on the DataView since filter and sort expressions are not yet provided.
/// </summary>
/// <param name="table">The input table from which LinkDataView is to be created.</param>
/// <param name="sortExpressionBuilder">The sort expression builder in case multiple selectors/comparers are added.</param>
internal LinqDataView(
DataTable table,
SortExpressionBuilder<DataRow>? sortExpressionBuilder
) : base(table)
{
Debug.Assert(table != null, "null DataTable");
this.sortExpressionBuilder =
sortExpressionBuilder ?? new SortExpressionBuilder<DataRow>();
}
/// <summary>
///
/// </summary>
/// <param name="table">Table from which to create the view</param>
/// <param name="predicate_system">User-provided predicate but in the form of System.Predicate<DataRow>
/// Predicates are being replicated in different forms so that nulls can be passed in.
/// For e.g. when user provides null predicate, base.Predicate should be set to null. I cant do that in the constructor initialization
/// if I will have to create System.Predicate delegate from Func.
/// </param>
/// <param name="comparison">The comparer function of DataRow to be used for sorting. </param>
/// <param name="comparerKeyRow">A comparer function that compares a Key value to DataRow.</param>
/// <param name="sortExpressionBuilder">Combined sort expression build using mutiple sort expressions.</param>
internal LinqDataView(
DataTable table,
Predicate<DataRow>? predicate_system,
Comparison<DataRow>? comparison,
Func<object, DataRow, int>? comparerKeyRow,
SortExpressionBuilder<DataRow>? sortExpressionBuilder
) : base(table, predicate_system, comparison, DataViewRowState.CurrentRows)
{
this.sortExpressionBuilder =
(sortExpressionBuilder == null)
? this.sortExpressionBuilder
: sortExpressionBuilder;
this.comparerKeyRow = comparerKeyRow;
}
/// <summary>
/// Gets or sets the expression used to filter which rows are viewed in the LinqDataView
/// </summary>
public override string? RowFilter
{
get
{
if (base.RowPredicate == null) // using string based filter or no filter
{
return base.RowFilter;
}
else // using expression based filter
{
return null;
}
}
set
{
if (value == null)
{
base.RowPredicate = null;
base.RowFilter = string.Empty; // INDEX rebuild twice
}
else
{
base.RowFilter = value;
base.RowPredicate = null;
}
}
}
#region Find
/// <summary>
/// Searches the index and finds a single row where the sort-key matches the input key
/// </summary>
/// <param name="key">Value of the key to find</param>
/// <returns>Index of the first match of input key</returns>
internal override int FindByKey(object? key)
{
Debug.Assert(base.Sort != null);
Debug.Assert(
!(!string.IsNullOrEmpty(base.Sort) && base.SortComparison != null),
"string and expression based sort cannot both be set"
);
if (!string.IsNullOrEmpty(base.Sort)) // use find for DV's sort string
{
return base.FindByKey(key);
}
else if (base.SortComparison == null) // neither string or expr set
{
// This is the exception message from DataView that we want to use
throw ExceptionBuilder.IndexKeyLength(0, 0);
}
else // find for expression based sort
{
if (sortExpressionBuilder!.Count != 1)
throw DataSetUtil.InvalidOperation(
SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)
);
Index.ComparisonBySelector<object, DataRow> compareDelg =
new Index.ComparisonBySelector<object, DataRow>(comparerKeyRow!);
List<object?> keyList = new List<object?>();
keyList.Add(key);
Range range = FindRecords<object, DataRow>(compareDelg, keyList);
return (range.Count == 0) ? -1 : range.Min;
}
}
/// <summary>
/// Since LinkDataView does not support multiple selectors/comparers, it does not make sense for
/// them to Find using multiple keys.
/// This overriden method prevents users calling multi-key find on dataview.
/// </summary>
internal override int FindByKey(object?[] key)
{
// must have string or expression based sort specified
if (base.SortComparison == null && string.IsNullOrEmpty(base.Sort))
{
// This is the exception message from DataView that we want to use
throw ExceptionBuilder.IndexKeyLength(0, 0);
}
else if (base.SortComparison != null && key.Length != sortExpressionBuilder!.Count)
{
throw DataSetUtil.InvalidOperation(
SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)
);
}
if (base.SortComparison == null)
{
// using string to sort
return base.FindByKey(key);
}
else
{
Index.ComparisonBySelector<object, DataRow> compareDelg =
new Index.ComparisonBySelector<object, DataRow>(comparerKeyRow!);
List<object?> keyList = new List<object?>();
foreach (object? singleKey in key)
{
keyList.Add(singleKey);
}
Range range = FindRecords<object, DataRow>(compareDelg, keyList);
return (range.Count == 0) ? -1 : range.Min;
}
}
/// <summary>
/// Searches the index and finds rows where the sort-key matches the input key.
/// Since LinkDataView does not support multiple selectors/comparers, it does not make sense for
/// them to Find using multiple keys. This overriden method prevents users calling multi-key find on dataview.
/// </summary>
internal override DataRowView[] FindRowsByKey(object?[] key)
{
// must have string or expression based sort specified
if (base.SortComparison == null && string.IsNullOrEmpty(base.Sort))
{
// This is the exception message from DataView that we want to use
throw ExceptionBuilder.IndexKeyLength(0, 0);
}
else if (base.SortComparison != null && key.Length != sortExpressionBuilder!.Count)
{
throw DataSetUtil.InvalidOperation(
SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)
);
}
if (base.SortComparison == null) // using string to sort
{
return base.FindRowsByKey(key);
}
else
{
Range range = FindRecords<object, DataRow>(
new Index.ComparisonBySelector<object, DataRow>(comparerKeyRow!),
new List<object?>(key)
);
return base.GetDataRowViewFromRange(range);
}
}
#endregion
#region Misc Overrides
/// <summary>
/// Overriding DataView's SetIndex to prevent users from setting RowState filter to anything other
/// than CurrentRows.
/// </summary>
internal override void SetIndex(
string newSort,
DataViewRowState newRowStates,
IFilter? newRowFilter
)
{
// Throw only if expressions (filter or sort) are used and rowstate is not current rows
if (
(base.SortComparison != null || base.RowPredicate != null)
&& newRowStates != DataViewRowState.CurrentRows
)
{
throw DataSetUtil.Argument(SR.LDVRowStateError);
}
else
{
base.SetIndex(newSort, newRowStates, newRowFilter);
}
}
#endregion
#region IBindingList
// TODO: Enable after System.ComponentModel.TypeConverter is annotated
#nullable disable
/// <summary>
/// Clears both expression-based and DataView's string-based sorting.
/// </summary>
void IBindingList.RemoveSort()
{
base.Sort = string.Empty;
base.SortComparison = null;
}
/// <summary>
/// Overrides IBindingList's SortProperty so that it returns null if expression based sort
/// is used in the LinkDataView, otherwise it defers the result to DataView
/// </summary>
PropertyDescriptor IBindingList.SortProperty
{
get { return (base.SortComparison == null) ? base.GetSortProperty() : null; }
}
/// <summary>
/// Overrides IBindingList's SortDescriptions so that it returns null if expression based sort
/// is used in the LinkDataView, otherwise it defers the result to DataView
/// </summary>
ListSortDescriptionCollection IBindingListView.SortDescriptions
{
get
{
if (base.SortComparison == null)
{
return base.GetSortDescriptions();
}
else
{
return new ListSortDescriptionCollection();
}
}
}
/// <summary>
/// Tells whether the LinqDataView is sorted or not
/// </summary>
bool IBindingList.IsSorted
{
get
{ // Sorted if either expression based sort or string based sort is set
return !(base.SortComparison == null && base.Sort.Length == 0);
}
}
#nullable enable
#endregion
}
}
| 39.019802 | 142 | 0.558741 | [
"MIT"
] | belav/runtime | src/libraries/System.Data.Common/src/System/Data/LinqDataView.cs | 11,823 | 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.Automation.V20151031
{
/// <summary>
/// Definition of the automation account type.
/// </summary>
[AzureNativeResourceType("azure-native:automation/v20151031:AutomationAccount")]
public partial class AutomationAccount : Pulumi.CustomResource
{
/// <summary>
/// Gets the creation time.
/// </summary>
[Output("creationTime")]
public Output<string> CreationTime { get; private set; } = null!;
/// <summary>
/// Gets or sets the description.
/// </summary>
[Output("description")]
public Output<string?> Description { get; private set; } = null!;
/// <summary>
/// Gets or sets the etag of the resource.
/// </summary>
[Output("etag")]
public Output<string?> Etag { get; private set; } = null!;
/// <summary>
/// Gets or sets the last modified by.
/// </summary>
[Output("lastModifiedBy")]
public Output<string?> LastModifiedBy { get; private set; } = null!;
/// <summary>
/// Gets the last modified time.
/// </summary>
[Output("lastModifiedTime")]
public Output<string> LastModifiedTime { get; private set; } = null!;
/// <summary>
/// The Azure Region where the resource lives
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// The name of the resource
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Gets or sets the SKU of account.
/// </summary>
[Output("sku")]
public Output<Outputs.SkuResponse?> Sku { get; private set; } = null!;
/// <summary>
/// Gets status of account.
/// </summary>
[Output("state")]
public Output<string> State { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// The type of the resource.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a AutomationAccount 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 AutomationAccount(string name, AutomationAccountArgs args, CustomResourceOptions? options = null)
: base("azure-native:automation/v20151031:AutomationAccount", name, args ?? new AutomationAccountArgs(), MakeResourceOptions(options, ""))
{
}
private AutomationAccount(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:automation/v20151031:AutomationAccount", 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:automation/v20151031:AutomationAccount"},
new Pulumi.Alias { Type = "azure-native:automation:AutomationAccount"},
new Pulumi.Alias { Type = "azure-nextgen:automation:AutomationAccount"},
new Pulumi.Alias { Type = "azure-native:automation/v20190601:AutomationAccount"},
new Pulumi.Alias { Type = "azure-nextgen:automation/v20190601:AutomationAccount"},
new Pulumi.Alias { Type = "azure-native:automation/v20200113preview:AutomationAccount"},
new Pulumi.Alias { Type = "azure-nextgen:automation/v20200113preview:AutomationAccount"},
},
};
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 AutomationAccount 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 AutomationAccount Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new AutomationAccount(name, id, options);
}
}
public sealed class AutomationAccountArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the automation account.
/// </summary>
[Input("automationAccountName")]
public Input<string>? AutomationAccountName { get; set; }
/// <summary>
/// Gets or sets the location of the resource.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// Gets or sets name of the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Name of an Azure Resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// Gets or sets account SKU.
/// </summary>
[Input("sku")]
public Input<Inputs.SkuArgs>? Sku { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Gets or sets the tags attached to the resource.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public AutomationAccountArgs()
{
}
}
}
| 37.639785 | 150 | 0.578203 | [
"Apache-2.0"
] | sebtelko/pulumi-azure-native | sdk/dotnet/Automation/V20151031/AutomationAccount.cs | 7,001 | C# |
using UnityEngine;
using UnityEngine.Events;
public class ProjectileBase : MonoBehaviour
{
public GameObject owner { get; private set; }
public Vector3 initialPosition { get; private set; }
public Vector3 initialDirection { get; private set; }
public Vector3 inheritedMuzzleVelocity { get; private set; }
public float initialCharge { get; private set; }
public UnityAction onShoot;
public void Shoot(WeaponController controller)
{
owner = controller.owner;
initialPosition = transform.position;
initialDirection = transform.forward;
inheritedMuzzleVelocity = controller.muzzleWorldVelocity;
initialCharge = controller.currentCharge;
if (onShoot != null)
{
onShoot.Invoke();
}
}
}
| 29.428571 | 66 | 0.657767 | [
"MIT"
] | IPFPS/ipfps | Assets/FPS/Scripts/ProjectileBase.cs | 826 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006-2019, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.490)
// Version 5.490.0.0 www.ComponentFactory.com
// *****************************************************************************
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Redirect requests for image/text colors to remap.
/// </summary>
public class ButtonSpecRemapByContentCache : ButtonSpecRemapByContentBase
{
#region Instance Fields
private IPaletteContent _paletteContent;
private PaletteState _paletteState;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ButtonSpecRemapByContentCache class.
/// </summary>
/// <param name="target">Initial palette target for redirection.</param>
/// <param name="buttonSpec">Reference to button specification.</param>
public ButtonSpecRemapByContentCache(IPalette target,
ButtonSpec buttonSpec)
: base(target, buttonSpec)
{
}
#endregion
#region SetPaletteContent
/// <summary>
/// Set the palette content to use for remapping.
/// </summary>
/// <param name="paletteContent">Palette for requesting foreground colors.</param>
public void SetPaletteContent(IPaletteContent paletteContent)
{
_paletteContent = paletteContent;
}
#endregion
#region SetPaletteState
/// <summary>
/// Set the palette state of the remapping element.
/// </summary>
/// <param name="paletteState">Palette state.</param>
public void SetPaletteState(PaletteState paletteState)
{
_paletteState = paletteState;
}
#endregion
#region PaletteContent
/// <summary>
/// Gets the palette content to use for remapping.
/// </summary>
public override IPaletteContent PaletteContent => _paletteContent;
#endregion
#region PaletteState
/// <summary>
/// Gets the state of the remapping area
/// </summary>
public override PaletteState PaletteState => _paletteState;
#endregion
}
}
| 37.210526 | 157 | 0.599717 | [
"BSD-3-Clause"
] | Smurf-IV/Krypton-Toolkit-Suite-NET-Core | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/ButtonSpec/ButtonSpecRemapByContentCache.cs | 2,831 | C# |
// -----------------------------------------------------------------------
// <copyright file="IListPriceProvider.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.Azure.CCME.Assessment.Managers.ListPriceProviders
{
public interface IListPriceProvider
{
Task<IEnumerable<ListPriceMeter>> GetMetersAsync(
IEnumerable<string> subscriptionIds,
ISet<string> meterIds);
}
}
| 33.631579 | 75 | 0.561815 | [
"MIT"
] | Azure/ccme | src/shared/CostEstimationManager/ListPriceProviders/IListPriceProvider.cs | 641 | C# |
using System;
using System.Collections.Generic;
namespace PastebinMachine.AutoUpdate.CryptoTool.ResponseClasses
{
// Token: 0x02000007 RID: 7
public class KeyStructure
{
// Token: 0x04000011 RID: 17
public string e;
// Token: 0x04000012 RID: 18
public string n;
// Token: 0x04000013 RID: 19
public KeyStructure.KeyAUDBStructure audb;
// Token: 0x04000014 RID: 20
public KeyStructure.KeyMetadata metadata;
// Token: 0x02000008 RID: 8
public class KeyAUDBStructure
{
// Token: 0x04000015 RID: 21
public List<ModStructure> mods;
}
// Token: 0x02000009 RID: 9
public class KeyMetadata
{
// Token: 0x04000016 RID: 22
public string name;
}
}
}
| 19.222222 | 63 | 0.709538 | [
"BSD-3-Clause"
] | aaay-aaay/AUDBTool | ResponseClasses/KeyStructure.cs | 692 | C# |
/*
* 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.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Ecs.Transform;
using Aliyun.Acs.Ecs.Transform.V20140526;
namespace Aliyun.Acs.Ecs.Model.V20140526
{
public class DetachDiskRequest : RpcAcsRequest<DetachDiskResponse>
{
public DetachDiskRequest()
: base("Ecs", "2014-05-26", "DetachDisk", "ecs", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
}
private long? resourceOwnerId;
private string diskId;
private bool? deleteWithInstance;
private string resourceOwnerAccount;
private string ownerAccount;
private long? ownerId;
private string instanceId;
public long? ResourceOwnerId
{
get
{
return resourceOwnerId;
}
set
{
resourceOwnerId = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString());
}
}
public string DiskId
{
get
{
return diskId;
}
set
{
diskId = value;
DictionaryUtil.Add(QueryParameters, "DiskId", value);
}
}
public bool? DeleteWithInstance
{
get
{
return deleteWithInstance;
}
set
{
deleteWithInstance = value;
DictionaryUtil.Add(QueryParameters, "DeleteWithInstance", value.ToString());
}
}
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public string OwnerAccount
{
get
{
return ownerAccount;
}
set
{
ownerAccount = value;
DictionaryUtil.Add(QueryParameters, "OwnerAccount", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string InstanceId
{
get
{
return instanceId;
}
set
{
instanceId = value;
DictionaryUtil.Add(QueryParameters, "InstanceId", value);
}
}
public override DetachDiskResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DetachDiskResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 23.339869 | 134 | 0.655559 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-ecs/Ecs/Model/V20140526/DetachDiskRequest.cs | 3,571 | C# |
using System;
namespace SqlDataProvider.Data
{
public class TotemHonorTemplateInfo
{
public int ID;
public int Type;
public int NeedMoney;
public int AddHonor;
public TotemHonorTemplateInfo()
{
}
}
} | 13.095238 | 39 | 0.578182 | [
"MIT"
] | HuyTruong19x/DDTank4.1 | Source Server/SqlDataProvider/SqlDataProvider/Data/TotemHonorTemplateInfo.cs | 277 | 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Razor;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
using Moq;
using Xunit;
namespace Microsoft.VisualStudio.Editor.Razor
{
public class DefaultRazorEditorFactoryServiceTest
{
private IContentType RazorCoreContentType { get; } = Mock.Of<IContentType>(c => c.IsOfType(RazorLanguage.CoreContentType) == true);
private IContentType NonRazorCoreContentType { get; } = Mock.Of<IContentType>(c => c.IsOfType(It.IsAny<string>()) == false);
[Fact]
public void TryGetDocumentTracker_ForRazorTextBuffer_ReturnsTrue()
{
// Arrange
var expectedDocumentTracker = Mock.Of<VisualStudioDocumentTracker>();
var factoryService = CreateFactoryService(expectedDocumentTracker);
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryGetDocumentTracker(textBuffer, out var documentTracker);
// Assert
Assert.True(result);
Assert.Same(expectedDocumentTracker, documentTracker);
}
[Fact]
public void TryGetDocumentTracker_NonRazorBuffer_ReturnsFalse()
{
// Arrange
var factoryService = CreateFactoryService();
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == NonRazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryGetDocumentTracker(textBuffer, out var documentTracker);
// Assert
Assert.False(result);
Assert.Null(documentTracker);
}
[Fact]
public void TryInitializeTextBuffer_WorkspaceAccessorCanNotAccessWorkspace_ReturnsFalse()
{
// Arrange
Workspace workspace = null;
var workspaceAccessor = new Mock<VisualStudioWorkspaceAccessor>();
workspaceAccessor.Setup(provider => provider.TryGetWorkspace(It.IsAny<ITextBuffer>(), out workspace))
.Returns(false);
var factoryService = new DefaultRazorEditorFactoryService(workspaceAccessor.Object);
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryInitializeTextBuffer(textBuffer);
// Assert
Assert.False(result);
}
[Fact]
public void TryInitializeTextBuffer_StoresTracker_ReturnsTrue()
{
// Arrange
var expectedDocumentTracker = Mock.Of<VisualStudioDocumentTracker>();
var factoryService = CreateFactoryService(expectedDocumentTracker);
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryInitializeTextBuffer(textBuffer);
// Assert
Assert.True(result);
Assert.True(textBuffer.Properties.TryGetProperty(typeof(VisualStudioDocumentTracker), out VisualStudioDocumentTracker documentTracker));
Assert.Same(expectedDocumentTracker, documentTracker);
}
[Fact]
public void TryInitializeTextBuffer_OnlyStoresTrackerOnTextBufferOnce_ReturnsTrue()
{
// Arrange
var factoryService = CreateFactoryService();
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
factoryService.TryInitializeTextBuffer(textBuffer);
var expectedDocumentTracker = textBuffer.Properties[typeof(VisualStudioDocumentTracker)];
// Create a second factory service so it generates a different tracker
factoryService = CreateFactoryService();
// Act
var result = factoryService.TryInitializeTextBuffer(textBuffer);
// Assert
Assert.True(result);
Assert.True(textBuffer.Properties.TryGetProperty(typeof(VisualStudioDocumentTracker), out VisualStudioDocumentTracker documentTracker));
Assert.Same(expectedDocumentTracker, documentTracker);
}
[Fact]
public void TryGetParser_ForRazorTextBuffer_ReturnsTrue()
{
// Arrange
var expectedParser = Mock.Of<VisualStudioRazorParser>();
var factoryService = CreateFactoryService(parser: expectedParser);
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryGetParser(textBuffer, out var parser);
// Assert
Assert.True(result);
Assert.Same(expectedParser, parser);
}
[Fact]
public void TryGetParser_NonRazorBuffer_ReturnsFalse()
{
// Arrange
var factoryService = CreateFactoryService();
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == NonRazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryGetParser(textBuffer, out var parser);
// Assert
Assert.False(result);
Assert.Null(parser);
}
[Fact]
public void TryInitializeTextBuffer_StoresParser_ReturnsTrue()
{
// Arrange
var expectedParser = Mock.Of<VisualStudioRazorParser>();
var factoryService = CreateFactoryService(parser: expectedParser);
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryInitializeTextBuffer(textBuffer);
// Assert
Assert.True(result);
Assert.True(textBuffer.Properties.TryGetProperty(typeof(VisualStudioRazorParser), out VisualStudioRazorParser parser));
Assert.Same(expectedParser, parser);
}
[Fact]
public void TryInitializeTextBuffer_OnlyStoresParserOnTextBufferOnce_ReturnsTrue()
{
// Arrange
var factoryService = CreateFactoryService();
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
factoryService.TryInitializeTextBuffer(textBuffer);
var expectedParser = textBuffer.Properties[typeof(VisualStudioRazorParser)];
// Create a second factory service so it generates a different parser
factoryService = CreateFactoryService();
// Act
var result = factoryService.TryInitializeTextBuffer(textBuffer);
// Assert
Assert.True(result);
Assert.True(textBuffer.Properties.TryGetProperty(typeof(VisualStudioRazorParser), out VisualStudioRazorParser parser));
Assert.Same(expectedParser, parser);
}
[Fact]
public void TryGetSmartIndenter_ForRazorTextBuffer_ReturnsTrue()
{
// Arrange
var expectedSmartIndenter = Mock.Of<BraceSmartIndenter>();
var factoryService = CreateFactoryService(smartIndenter: expectedSmartIndenter);
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryGetSmartIndenter(textBuffer, out var smartIndenter);
// Assert
Assert.True(result);
Assert.Same(expectedSmartIndenter, smartIndenter);
}
[Fact]
public void TryGetSmartIndenter_NonRazorBuffer_ReturnsFalse()
{
// Arrange
var factoryService = CreateFactoryService();
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == NonRazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryGetSmartIndenter(textBuffer, out var smartIndenter);
// Assert
Assert.False(result);
Assert.Null(smartIndenter);
}
[Fact]
public void TryInitializeTextBuffer_StoresSmartIndenter_ReturnsTrue()
{
// Arrange
var expectedSmartIndenter = Mock.Of<BraceSmartIndenter>();
var factoryService = CreateFactoryService(smartIndenter: expectedSmartIndenter);
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
// Act
var result = factoryService.TryInitializeTextBuffer(textBuffer);
// Assert
Assert.True(result);
Assert.True(textBuffer.Properties.TryGetProperty(typeof(BraceSmartIndenter), out BraceSmartIndenter smartIndenter));
Assert.Same(expectedSmartIndenter, smartIndenter);
}
[Fact]
public void TryInitializeTextBuffer_OnlyStoresSmartIndenterOnTextBufferOnce_ReturnsTrue()
{
// Arrange
var factoryService = CreateFactoryService();
var textBuffer = Mock.Of<ITextBuffer>(b => b.ContentType == RazorCoreContentType && b.Properties == new PropertyCollection());
factoryService.TryInitializeTextBuffer(textBuffer);
var expectedSmartIndenter = textBuffer.Properties[typeof(BraceSmartIndenter)];
// Create a second factory service so it generates a different smart indenter
factoryService = CreateFactoryService();
// Act
var result = factoryService.TryInitializeTextBuffer(textBuffer);
// Assert
Assert.True(result);
Assert.True(textBuffer.Properties.TryGetProperty(typeof(BraceSmartIndenter), out BraceSmartIndenter smartIndenter));
Assert.Same(expectedSmartIndenter, smartIndenter);
}
private static DefaultRazorEditorFactoryService CreateFactoryService(
VisualStudioDocumentTracker documentTracker = null,
VisualStudioRazorParser parser = null,
BraceSmartIndenter smartIndenter = null)
{
documentTracker = documentTracker ?? Mock.Of<VisualStudioDocumentTracker>();
parser = parser ?? Mock.Of<VisualStudioRazorParser>();
smartIndenter = smartIndenter ?? Mock.Of<BraceSmartIndenter>();
var documentTrackerFactory = Mock.Of<VisualStudioDocumentTrackerFactory>(f => f.Create(It.IsAny<ITextBuffer>()) == documentTracker);
var parserFactory = Mock.Of<VisualStudioRazorParserFactory>(f => f.Create(It.IsAny<VisualStudioDocumentTracker>()) == parser);
var smartIndenterFactory = Mock.Of<BraceSmartIndenterFactory>(f => f.Create(It.IsAny<VisualStudioDocumentTracker>()) == smartIndenter);
var services = TestServices.Create(new ILanguageService[]
{
documentTrackerFactory,
parserFactory,
smartIndenterFactory
});
var workspace = TestWorkspace.Create(services);
var workspaceAccessor = new Mock<VisualStudioWorkspaceAccessor>();
workspaceAccessor.Setup(p => p.TryGetWorkspace(It.IsAny<ITextBuffer>(), out workspace))
.Returns(true);
var factoryService = new DefaultRazorEditorFactoryService(workspaceAccessor.Object);
return factoryService;
}
}
}
| 43.521739 | 148 | 0.652348 | [
"Apache-2.0"
] | AmadeusW/Razor | test/Microsoft.VisualStudio.Editor.Razor.Test/DefaultRazorEditorFactoryServiceTest.cs | 12,014 | C# |
using System;
using Root.Coding.Code.Enums.E01D.Json;
namespace Root.Coding.Code.Models.E01D.Json
{
public class JsonContract
{
public JsonReadType InternalReadType { get; set; }
public bool IsNullable { get; set; }
public bool IsConvertable { get; set; }
public bool IsEnum { get; set; }
public Type NonNullableUnderlyingType { get; set; }
public JsonContractType ContractType { get; set; }
public bool IsReadOnlyOrFixedSize { get; set; }
public bool IsSealed { get; set; }
public bool IsInstantiable { get; set; }
/// <summary>
/// Gets the underlying type for the contract.
/// </summary>
/// <value>The underlying type for the contract.</value>
public Type UnderlyingType { get; set; }
}
}
| 30.481481 | 64 | 0.622114 | [
"Apache-2.0"
] | E01D/Base | src/E01D.Base.Json.Models/Coding/Code/Models/E01D/Json/JsonContract.cs | 825 | C# |
using System;
using System.Collections;
using System.Threading.Tasks;
using BDFramework.ScreenView;
using BDFramework.Sql;
using UnityEngine;
using BDFramework.UI;
using Game.Data;
using LitJson;
using UnityEngine.UI;
using BDFramework;
using BDFramework.DataListener;
using BDFramework.ResourceMgr;
using BDFramework.VersionContrller;
using Boo.Lang;
using Code.Game;
using Code.Game.demo_EventManager;
using Code.Game.demo6_UFlux;
/// <summary>
/// 这个是ui的标签,
/// index
/// resource 目录
/// </summary>
[UI((int) WinEnum.Win_Main, "Windows/window_demoMain")]
public class Window_DemoMain : AWindow
{
[TransformPath("text_hotfixState")]
private Text text_hotfixState;
[TransformPath("btn_1")]
private Button btn_01;
[TransformPath("btn_4")]
private Button btn_04;
[TransformPath("btn_5")]
private Button btn_05;
[TransformPath("btn_6")]
private Button btn_06;
[TransformPath("btn_7")]
private Button btn_07;
[TransformPath("btn_8")]
private Button btn_08;
[TransformPath("btn_9")]
private Button btn_09;
//[]
public Window_DemoMain(string path) : base(path)
{
}
public enum DataListenerEnum
{
test,
}
public override void Init()
{
base.Init();
//增加覆盖测试
var service = DataListenerServer.Create(nameof(DataListenerEnum));
service.AddListener(DataListenerEnum.test, (o) =>
{
Debug.Log(o.ToString());
});
//demo1: screenview 切换
//代码:
//Game@hotfix/demo1
this.btn_01.onClick.AddListener(() =>
{
ScreenViewManager.Inst.MainLayer.BeginNavTo(ScreenViewEnum.Demo1);
});
//demo4 : uflux窗口
//代码:
this.btn_04.onClick.AddListener(() =>
{
BDFramework.UFlux.UIManager.Inst.LoadWindow(UFluxWindowEnum.UFluxDemoMain);
BDFramework.UFlux.UIManager.Inst.ShowWindow(UFluxWindowEnum.UFluxDemoMain);
});
//demo5: sqlite 查询
this.btn_05.onClick.AddListener(() =>
{
//单条件查询
Debug.Log("普通查询:");
var ds = SqliteHelper.DB.GetTableRuntime().Where("id = 1").ToSearch<Hero>();
ds = SqliteHelper.DB.GetTableRuntime().Where("id = {0}",1).ToSearch<Hero>();
foreach (var d in ds) Debug.Log(JsonMapper.ToJson(d));
//多条件查询
Debug.Log("多条件查询:");
ds = SqliteHelper.DB.GetTableRuntime().Where("id > 1").Where("and id < 3").ToSearch<Hero>();
foreach (var d in ds) Debug.Log(JsonMapper.ToJson(d));
//批量查询
Debug.Log("Where or 批量查询:");
ds = SqliteHelper.DB.GetTableRuntime().WhereAnd("id", "=", 1, 2).ToSearch<Hero>();
foreach (var d in ds) Debug.Log(JsonMapper.ToJson(d));
//批量查询
Debug.Log("Where and 批量查询:");
ds = SqliteHelper.DB.GetTableRuntime().WhereOr("id", "=", 2, 3).ToSearch<Hero>();
foreach (var d in ds) Debug.Log(JsonMapper.ToJson(d));
});
//demo6:资源加载
this.btn_06.onClick.AddListener(() =>
{
//1.同步加载
var go = BResources.Load<GameObject>("Test/Cube");
GameObject.Instantiate(go).name = "load";
//2.异步加载单个
var id = BResources.AsyncLoad<GameObject>("Windows/window_demo1", (o) => { });
//3.异步加载多个
var list = new System.Collections.Generic.List<string>() {"Windows/window_demo1", "Windows/window_demo2"};
BResources.AsyncLoad(list,
(i, i2) => { Debug.Log(string.Format("进度 {0} / {1}", i, i2)); },
(map) =>
{
BDebug.Log("加载全部完成,资源列表:");
foreach (var r in map)
{
BDebug.Log(string.Format("--> {0} : {1}", r.Key, r.Value.name));
GameObject.Instantiate(r.Value);
}
});
});
//代码:
//Game@hotfix/demo_Manager_AutoRegister_And_Event
this.btn_07.onClick.AddListener(() =>
{
var path = Application.persistentDataPath;
VersionContorller.Start(UpdateMode.Repair, "http://127.0.0.1", path,
(i, j) => { Debug.LogFormat("资源更新进度:{0}/{1}", i, j); },
(error) => { Debug.LogError("错误:" + error); });
});
//发送消息机制
this.btn_08.onClick.AddListener(() => { DemoEventManager.Inst.Do(DemoEventEnum.TestEvent2); });
//图集
this.btn_09.onClick.AddListener(() =>
{
UIManager.Inst.CloseWindow(WinEnum.Win_Main);
UIManager.Inst.LoadWindows((int) WinEnum.Win_Demo5_Atlas);
UIManager.Inst.ShowWindow((int) WinEnum.Win_Demo5_Atlas);
});
}
public override void Close()
{
base.Close();
}
public override void Open(WindowData data = null)
{
base.Open();
}
public override void Destroy()
{
base.Destroy();
}
} | 28.768362 | 118 | 0.560291 | [
"Apache-2.0"
] | ZetLiu/BDFramework.Core | Assets/Code/Game@hotfix/Window_DemoMain.cs | 5,334 | C# |
using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using Ayehu.Sdk.ActivityCreation.Interfaces;
using Ayehu.Sdk.ActivityCreation.Extension;
using Microsoft.Graph;
using Microsoft.Identity.Client;
using Microsoft.Graph.Auth;
namespace Ayehu.Sdk.ActivityCreation
{
public class OfficeRemoveUserLicense : IActivity
{
/// <summary>
/// APPLICATION (CLIENT) ID
/// </summary>
public string appId;
/// <summary>
/// Directory (tenant) ID
/// </summary>
public string tenantId;
/// <summary>
/// Client secret
/// </summary>
/// <remarks>
/// A secret string that the application uses to prove its identity when requesting a token.
/// Also can be referred to as application password.
/// </remarks>
public string secret;
/// <summary>
/// User's email to create the rule
/// </summary>
public string userEmail;
public ICustomActivityResult Execute()
{
GraphServiceClient client = new GraphServiceClient("https://graph.microsoft.com/v1.0", GetProvider());
var user = client.Users[userEmail];
Guid? skuId = GetLicense(client).SkuId;
if (user.Request().GetAsync().Result.UserPrincipalName != null)
{
var license = user.LicenseDetails.Request().GetAsync().Result.Where(l => l.SkuId == skuId).FirstOrDefault();
if (license != null)
user.AssignLicense(new List<AssignedLicense>(), new List<Guid> { license.SkuId.Value }).Request().PostAsync().Wait();
else
throw new Exception("User doesn't have any license assigned");
}
return this.GenerateActivityResult(GetActivityResult);
}
/// <summary>
/// Get the authentication provider to be used for API calls
/// </summary>
/// <returns><code>ClientCredentialProvider</code></returns>
private ClientCredentialProvider GetProvider()
{
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(appId)
.WithTenantId(tenantId)
.WithClientSecret(secret)
.Build();
return new ClientCredentialProvider(confidentialClientApplication);
}
private SubscribedSku GetLicense(GraphServiceClient client)
{
var skuResult = client.SubscribedSkus.Request().GetAsync().Result;
return skuResult[0];
}
private DataTable GetActivityResult
{
get
{
DataTable dt = new DataTable("resultSet");
dt.Columns.Add("Result");
dt.Rows.Add("Success");
return dt;
}
}
}
}
| 32.086957 | 137 | 0.584011 | [
"MIT"
] | Ayehu/custom-activities | Office365/OfficeRemoveUserLicense/OfficeRemoveUserLicense.cs | 2,952 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IEntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface IOnPremisesConditionalAccessSettingsRequest.
/// </summary>
public partial interface IOnPremisesConditionalAccessSettingsRequest : IBaseRequest
{
/// <summary>
/// Creates the specified OnPremisesConditionalAccessSettings using POST.
/// </summary>
/// <param name="onPremisesConditionalAccessSettingsToCreate">The OnPremisesConditionalAccessSettings to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created OnPremisesConditionalAccessSettings.</returns>
System.Threading.Tasks.Task<OnPremisesConditionalAccessSettings> CreateAsync(OnPremisesConditionalAccessSettings onPremisesConditionalAccessSettingsToCreate, CancellationToken cancellationToken = default);
/// <summary>
/// Creates the specified OnPremisesConditionalAccessSettings using POST and returns a <see cref="GraphResponse{OnPremisesConditionalAccessSettings}"/> object.
/// </summary>
/// <param name="onPremisesConditionalAccessSettingsToCreate">The OnPremisesConditionalAccessSettings to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{OnPremisesConditionalAccessSettings}"/> object of the request.</returns>
System.Threading.Tasks.Task<GraphResponse<OnPremisesConditionalAccessSettings>> CreateResponseAsync(OnPremisesConditionalAccessSettings onPremisesConditionalAccessSettingsToCreate, CancellationToken cancellationToken = default);
/// <summary>
/// Deletes the specified OnPremisesConditionalAccessSettings.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Deletes the specified OnPremisesConditionalAccessSettings and returns a <see cref="GraphResponse"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task of <see cref="GraphResponse"/> to await.</returns>
System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Gets the specified OnPremisesConditionalAccessSettings.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The OnPremisesConditionalAccessSettings.</returns>
System.Threading.Tasks.Task<OnPremisesConditionalAccessSettings> GetAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Gets the specified OnPremisesConditionalAccessSettings and returns a <see cref="GraphResponse{OnPremisesConditionalAccessSettings}"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{OnPremisesConditionalAccessSettings}"/> object of the request.</returns>
System.Threading.Tasks.Task<GraphResponse<OnPremisesConditionalAccessSettings>> GetResponseAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Updates the specified OnPremisesConditionalAccessSettings using PATCH.
/// </summary>
/// <param name="onPremisesConditionalAccessSettingsToUpdate">The OnPremisesConditionalAccessSettings to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The updated OnPremisesConditionalAccessSettings.</returns>
System.Threading.Tasks.Task<OnPremisesConditionalAccessSettings> UpdateAsync(OnPremisesConditionalAccessSettings onPremisesConditionalAccessSettingsToUpdate, CancellationToken cancellationToken = default);
/// <summary>
/// Updates the specified OnPremisesConditionalAccessSettings using PATCH and returns a <see cref="GraphResponse{OnPremisesConditionalAccessSettings}"/> object.
/// </summary>
/// <param name="onPremisesConditionalAccessSettingsToUpdate">The OnPremisesConditionalAccessSettings to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The <see cref="GraphResponse{OnPremisesConditionalAccessSettings}"/> object of the request.</returns>
System.Threading.Tasks.Task<GraphResponse<OnPremisesConditionalAccessSettings>> UpdateResponseAsync(OnPremisesConditionalAccessSettings onPremisesConditionalAccessSettingsToUpdate, CancellationToken cancellationToken = default);
/// <summary>
/// Updates the specified OnPremisesConditionalAccessSettings using PUT.
/// </summary>
/// <param name="onPremisesConditionalAccessSettingsToUpdate">The OnPremisesConditionalAccessSettings object to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task<OnPremisesConditionalAccessSettings> PutAsync(OnPremisesConditionalAccessSettings onPremisesConditionalAccessSettingsToUpdate, CancellationToken cancellationToken = default);
/// <summary>
/// Updates the specified OnPremisesConditionalAccessSettings using PUT and returns a <see cref="GraphResponse{OnPremisesConditionalAccessSettings}"/> object.
/// </summary>
/// <param name="onPremisesConditionalAccessSettingsToUpdate">The OnPremisesConditionalAccessSettings object to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task of <see cref="GraphResponse{OnPremisesConditionalAccessSettings}"/> to await.</returns>
System.Threading.Tasks.Task<GraphResponse<OnPremisesConditionalAccessSettings>> PutResponseAsync(OnPremisesConditionalAccessSettings onPremisesConditionalAccessSettingsToUpdate, CancellationToken cancellationToken = default);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesConditionalAccessSettingsRequest Expand(string value);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesConditionalAccessSettingsRequest Expand(Expression<Func<OnPremisesConditionalAccessSettings, object>> expandExpression);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesConditionalAccessSettingsRequest Select(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
IOnPremisesConditionalAccessSettingsRequest Select(Expression<Func<OnPremisesConditionalAccessSettings, object>> selectExpression);
}
}
| 66.900763 | 236 | 0.715883 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IOnPremisesConditionalAccessSettingsRequest.cs | 8,764 | C# |
using Rabbitual.Configuration;
using Topshelf;
namespace Rabbitual.ConsoleHost
{
public static class Host
{
public static void Run(bool inMemory)
{
var c = Bootstrapper.Bootstrap(true);
//run service using TopShelf
HostFactory.Run(x =>
{
x.Service<App>(s =>
{
s.ConstructUsing(name => c.GetInstance<App>());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.EnableServiceRecovery(r =>
{
r.RestartService(0);
//number of days until the error count resets
r.SetResetPeriod(1);
});
x.StartAutomatically(); //...when installed
x.RunAsLocalSystem();
x.SetDescription("Rabbitual Demo");
x.SetDisplayName("Rabbitual Demo");
x.SetServiceName("Rabbitual.Demo");
});
System.Console.ReadLine();
}
}
}
| 26.738095 | 67 | 0.463045 | [
"MIT"
] | BjartN/Rabbitual | src/Rabbitual.ConsoleHost/Host.cs | 1,125 | 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.Collections.Generic;
using System.Reflection;
namespace ApiCheck
{
internal class AssemblyNameComparer : IEqualityComparer<AssemblyName>
{
public static readonly IEqualityComparer<AssemblyName> OrdinalIgnoreCase = new AssemblyNameComparer();
public bool Equals(AssemblyName x, AssemblyName y)
{
// Ignore case because that's what Assembly.Load does.
return string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase) &&
string.Equals(x.CultureName ?? string.Empty, y.CultureName ?? string.Empty, StringComparison.Ordinal);
}
public int GetHashCode(AssemblyName obj)
{
var hashCode = 0;
if (obj.Name != null)
{
hashCode ^= obj.Name.GetHashCode();
}
hashCode ^= (obj.CultureName ?? string.Empty).GetHashCode();
return hashCode;
}
}
}
| 33.352941 | 118 | 0.641093 | [
"Apache-2.0"
] | dotnet-maestro-bot/BuildTools | src/ApiCheck.Console/Loader/AssemblyNameComparer.cs | 1,136 | C# |
// Deflater.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// This is the Deflater class. The deflater class compresses input
/// with the deflate algorithm described in RFC 1951. It has several
/// compression levels and three different strategies described below.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of deflate and setInput.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class Deflater
{
#region Deflater Documentation
/*
* The Deflater can do the following state transitions:
*
* (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---.
* / | (2) (5) |
* / v (5) |
* (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3)
* \ | (3) | ,--------'
* | | | (3) /
* v v (5) v v
* (1) -> BUSY_STATE ----> FINISHING_STATE
* | (6)
* v
* FINISHED_STATE
* \_____________________________________/
* | (7)
* v
* CLOSED_STATE
*
* (1) If we should produce a header we start in INIT_STATE, otherwise
* we start in BUSY_STATE.
* (2) A dictionary may be set only when we are in INIT_STATE, then
* we change the state as indicated.
* (3) Whether a dictionary is set or not, on the first call of deflate
* we change to BUSY_STATE.
* (4) -- intentionally left blank -- :)
* (5) FINISHING_STATE is entered, when flush() is called to indicate that
* there is no more INPUT. There are also states indicating, that
* the header wasn't written yet.
* (6) FINISHED_STATE is entered, when everything has been flushed to the
* internal pending output buffer.
* (7) At any time (7)
*
*/
#endregion
#region Public Constants
/// <summary>
/// The best and slowest compression level. This tries to find very
/// long and distant string repetitions.
/// </summary>
public const int BEST_COMPRESSION = 9;
/// <summary>
/// The worst but fastest compression level.
/// </summary>
public const int BEST_SPEED = 1;
/// <summary>
/// The default compression level.
/// </summary>
public const int DEFAULT_COMPRESSION = -1;
/// <summary>
/// This level won't compress at all but output uncompressed blocks.
/// </summary>
public const int NO_COMPRESSION = 0;
/// <summary>
/// The compression method. This is the only method supported so far.
/// There is no need to use this constant at all.
/// </summary>
public const int DEFLATED = 8;
#endregion
#region Local Constants
private const int IS_SETDICT = 0x01;
private const int IS_FLUSHING = 0x04;
private const int IS_FINISHING = 0x08;
private const int INIT_STATE = 0x00;
private const int SETDICT_STATE = 0x01;
// private static int INIT_FINISHING_STATE = 0x08;
// private static int SETDICT_FINISHING_STATE = 0x09;
private const int BUSY_STATE = 0x10;
private const int FLUSHING_STATE = 0x14;
private const int FINISHING_STATE = 0x1c;
private const int FINISHED_STATE = 0x1e;
private const int CLOSED_STATE = 0x7f;
#endregion
#region Constructors
/// <summary>
/// Creates a new deflater with default compression level.
/// </summary>
public Deflater() : this(DEFAULT_COMPRESSION, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// </summary>
/// <param name="level">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION, or DEFAULT_COMPRESSION.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int level) : this(level, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// </summary>
/// <param name="level">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION.
/// </param>
/// <param name="noZlibHeaderOrFooter">
/// true, if we should suppress the Zlib/RFC1950 header at the
/// beginning and the adler checksum at the end of the output. This is
/// useful for the GZIP/PKZIP formats.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int level, bool noZlibHeaderOrFooter)
{
if (level == DEFAULT_COMPRESSION) {
level = 6;
} else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) {
throw new ArgumentOutOfRangeException("level");
}
pending = new DeflaterPending();
engine = new DeflaterEngine(pending);
this.noZlibHeaderOrFooter = noZlibHeaderOrFooter;
SetStrategy(DeflateStrategy.Default);
SetLevel(level);
Reset();
}
#endregion
/// <summary>
/// Resets the deflater. The deflater acts afterwards as if it was
/// just created with the same compression level and strategy as it
/// had before.
/// </summary>
public void Reset()
{
state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE);
totalOut = 0;
pending.Reset();
engine.Reset();
}
/// <summary>
/// Gets the current adler checksum of the data that was processed so far.
/// </summary>
public int Adler {
get {
return engine.Adler;
}
}
/// <summary>
/// Gets the number of input bytes processed so far.
/// </summary>
public long TotalIn {
get {
return engine.TotalIn;
}
}
/// <summary>
/// Gets the number of output bytes so far.
/// </summary>
public long TotalOut {
get {
return totalOut;
}
}
/// <summary>
/// Flushes the current input block. Further calls to deflate() will
/// produce enough output to inflate everything in the current input
/// block. This is not part of Sun's JDK so I have made it package
/// private. It is used by DeflaterOutputStream to implement
/// flush().
/// </summary>
public void Flush()
{
state |= IS_FLUSHING;
}
/// <summary>
/// Finishes the deflater with the current input block. It is an error
/// to give more input after this method was called. This method must
/// be called to force all bytes to be flushed.
/// </summary>
public void Finish()
{
state |= (IS_FLUSHING | IS_FINISHING);
}
/// <summary>
/// Returns true if the stream was finished and no more output bytes
/// are available.
/// </summary>
public bool IsFinished {
get {
return (state == FINISHED_STATE) && pending.IsFlushed;
}
}
/// <summary>
/// Returns true, if the input buffer is empty.
/// You should then call setInput().
/// NOTE: This method can also return true when the stream
/// was finished.
/// </summary>
public bool IsNeedingInput {
get {
return engine.NeedsInput();
}
}
/// <summary>
/// Sets the data which should be compressed next. This should be only
/// called when needsInput indicates that more input is needed.
/// If you call setInput when needsInput() returns false, the
/// previous input that is still pending will be thrown away.
/// The given byte array should not be changed, before needsInput() returns
/// true again.
/// This call is equivalent to <code>setInput(input, 0, input.length)</code>.
/// </summary>
/// <param name="input">
/// the buffer containing the input data.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if the buffer was finished() or ended().
/// </exception>
public void SetInput(byte[] input)
{
SetInput(input, 0, input.Length);
}
/// <summary>
/// Sets the data which should be compressed next. This should be
/// only called when needsInput indicates that more input is needed.
/// The given byte array should not be changed, before needsInput() returns
/// true again.
/// </summary>
/// <param name="input">
/// the buffer containing the input data.
/// </param>
/// <param name="offset">
/// the start of the data.
/// </param>
/// <param name="count">
/// the number of data bytes of input.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if the buffer was Finish()ed or if previous input is still pending.
/// </exception>
public void SetInput(byte[] input, int offset, int count)
{
if ((state & IS_FINISHING) != 0) {
throw new InvalidOperationException("Finish() already called");
}
engine.SetInput(input, offset, count);
}
/// <summary>
/// Sets the compression level. There is no guarantee of the exact
/// position of the change, but if you call this when needsInput is
/// true the change of compression level will occur somewhere near
/// before the end of the so far given input.
/// </summary>
/// <param name="level">
/// the new compression level.
/// </param>
public void SetLevel(int level)
{
if (level == DEFAULT_COMPRESSION) {
level = 6;
} else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) {
throw new ArgumentOutOfRangeException("level");
}
if (this.level != level) {
this.level = level;
engine.SetLevel(level);
}
}
/// <summary>
/// Get current compression level
/// </summary>
/// <returns>Returns the current compression level</returns>
public int GetLevel() {
return level;
}
/// <summary>
/// Sets the compression strategy. Strategy is one of
/// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact
/// position where the strategy is changed, the same as for
/// SetLevel() applies.
/// </summary>
/// <param name="strategy">
/// The new compression strategy.
/// </param>
public void SetStrategy(DeflateStrategy strategy)
{
engine.Strategy = strategy;
}
/// <summary>
/// Deflates the current input block with to the given array.
/// </summary>
/// <param name="output">
/// The buffer where compressed data is stored
/// </param>
/// <returns>
/// The number of compressed bytes added to the output, or 0 if either
/// IsNeedingInput() or IsFinished returns true or length is zero.
/// </returns>
public int Deflate(byte[] output)
{
return Deflate(output, 0, output.Length);
}
/// <summary>
/// Deflates the current input block to the given array.
/// </summary>
/// <param name="output">
/// Buffer to store the compressed data.
/// </param>
/// <param name="offset">
/// Offset into the output array.
/// </param>
/// <param name="length">
/// The maximum number of bytes that may be stored.
/// </param>
/// <returns>
/// The number of compressed bytes added to the output, or 0 if either
/// needsInput() or finished() returns true or length is zero.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// If Finish() was previously called.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// If offset or length don't match the array length.
/// </exception>
public int Deflate(byte[] output, int offset, int length)
{
int origLength = length;
if (state == CLOSED_STATE) {
throw new InvalidOperationException("Deflater closed");
}
if (state < BUSY_STATE) {
// output header
int header = (DEFLATED +
((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8;
int level_flags = (level - 1) >> 1;
if (level_flags < 0 || level_flags > 3) {
level_flags = 3;
}
header |= level_flags << 6;
if ((state & IS_SETDICT) != 0) {
// Dictionary was set
header |= DeflaterConstants.PRESET_DICT;
}
header += 31 - (header % 31);
pending.WriteShortMSB(header);
if ((state & IS_SETDICT) != 0) {
int chksum = engine.Adler;
engine.ResetAdler();
pending.WriteShortMSB(chksum >> 16);
pending.WriteShortMSB(chksum & 0xffff);
}
state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING));
}
for (;;) {
int count = pending.Flush(output, offset, length);
offset += count;
totalOut += count;
length -= count;
if (length == 0 || state == FINISHED_STATE) {
break;
}
if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) {
if (state == BUSY_STATE) {
// We need more input now
return origLength - length;
} else if (state == FLUSHING_STATE) {
if (level != NO_COMPRESSION) {
/* We have to supply some lookahead. 8 bit lookahead
* is needed by the zlib inflater, and we must fill
* the next byte, so that all bits are flushed.
*/
int neededbits = 8 + ((-pending.BitCount) & 7);
while (neededbits > 0) {
/* write a static tree block consisting solely of
* an EOF:
*/
pending.WriteBits(2, 10);
neededbits -= 10;
}
}
state = BUSY_STATE;
} else if (state == FINISHING_STATE) {
pending.AlignToByte();
// Compressed data is complete. Write footer information if required.
if (!noZlibHeaderOrFooter) {
int adler = engine.Adler;
pending.WriteShortMSB(adler >> 16);
pending.WriteShortMSB(adler & 0xffff);
}
state = FINISHED_STATE;
}
}
}
return origLength - length;
}
/// <summary>
/// Sets the dictionary which should be used in the deflate process.
/// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>.
/// </summary>
/// <param name="dictionary">
/// the dictionary.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if SetInput () or Deflate () were already called or another dictionary was already set.
/// </exception>
public void SetDictionary(byte[] dictionary)
{
SetDictionary(dictionary, 0, dictionary.Length);
}
/// <summary>
/// Sets the dictionary which should be used in the deflate process.
/// The dictionary is a byte array containing strings that are
/// likely to occur in the data which should be compressed. The
/// dictionary is not stored in the compressed output, only a
/// checksum. To decompress the output you need to supply the same
/// dictionary again.
/// </summary>
/// <param name="dictionary">
/// The dictionary data
/// </param>
/// <param name="index">
/// The index where dictionary information commences.
/// </param>
/// <param name="count">
/// The number of bytes in the dictionary.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// If SetInput () or Deflate() were already called or another dictionary was already set.
/// </exception>
public void SetDictionary(byte[] dictionary, int index, int count)
{
if (state != INIT_STATE) {
throw new InvalidOperationException();
}
state = SETDICT_STATE;
engine.SetDictionary(dictionary, index, count);
}
#region Instance Fields
/// <summary>
/// Compression level.
/// </summary>
int level;
/// <summary>
/// If true no Zlib/RFC1950 headers or footers are generated
/// </summary>
bool noZlibHeaderOrFooter;
/// <summary>
/// The current state.
/// </summary>
int state;
/// <summary>
/// The total bytes of output written.
/// </summary>
long totalOut;
/// <summary>
/// The pending output.
/// </summary>
DeflaterPending pending;
/// <summary>
/// The deflater engine.
/// </summary>
DeflaterEngine engine;
#endregion
}
}
| 39.758065 | 101 | 0.50764 | [
"MIT"
] | Acidburn0zzz/flashdevelop | External/Tools/AppMan/ZipLib/Zip/Compression/Deflater.cs | 21,628 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Menu : MonoBehaviour {
public bool loading = false;
public void Start()
{
loading = false;
}
public void Update()
{
if (!loading)
{
if (Input.GetButtonDown("Fire1") || Input.GetButtonDown("Fire2"))
{
LoadScene("Paul");
return;
}
}
}
public void LoadScene(string sceneName)
{
//PlayClick();
if (string.IsNullOrEmpty(sceneName))
{
Debug.LogErrorFormat("LoadScene({0}): scene name not specified", sceneName);
}
else if (!Application.CanStreamedLevelBeLoaded(sceneName))
{
Debug.LogErrorFormat("LoadScene({0}): scene {0} not found", sceneName);
}
else
{
Debug.LogFormat("LoadScene({0})", sceneName);
Time.timeScale = 1.0f;
SceneManager.LoadScene(sceneName);
}
}
}
| 22.851064 | 88 | 0.543762 | [
"Apache-2.0"
] | paulsmithkc/GravityWells | Assets/Scripts/Menu.cs | 1,076 | C# |
//! \namespace NanoByte.Common.Storage
//! \brief File system access and serialization.
| 30 | 49 | 0.744444 | [
"MIT"
] | nano-byte/common | src/Common/Storage/_Namespace.cs | 90 | C# |
using Bonobo.Git.Server.App_GlobalResources;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace Bonobo.Git.Server.Data
{
public enum RepositoryPushMode
{
[Display(ResourceType = typeof(Resources), Name = "No")]
No = 0,
[Display(ResourceType = typeof(Resources), Name = "Yes")]
Yes,
[Display(ResourceType = typeof(Resources), Name = "Global")]
Global,
}
public partial class Repository
{
private ICollection<Team> _teams;
private ICollection<User> _administrators;
private ICollection<User> _users;
public Guid Id { get; set; }
public string Name { get; set; }
public string Group { get; set; }
public string Description { get; set; }
public bool Anonymous { get; set; }
public byte[] Logo { get; set; }
public RepositoryPushMode AllowAnonymousPush { get; set; }
public virtual ICollection<Team> Teams
{
get
{
return _teams ?? (_teams = new List<Team>());
}
set
{
_teams = value;
}
}
public virtual ICollection<User> Administrators
{
get
{
return _administrators ?? (_administrators = new List<User>());
}
set
{
_administrators = value;
}
}
public virtual ICollection<User> Users
{
get
{
return _users ?? (_users = new List<User>());
}
set
{
_users = value;
}
}
public Repository()
{
LinksUseGlobal = true;
}
public bool AuditPushUser { get; set; }
public string LinksRegex { get; set; }
public string LinksUrl { get; set; }
public bool LinksUseGlobal { get; set; }
/// <summary>
/// Correct a repository name have the same case as it has in the database
/// If the repo is not in the database, then the name is returned unchanged
/// </summary>
public static string NormalizeRepositoryName(string incomingRepositoryName, IRepositoryRepository repositoryRepository)
{
// In the most common case, we're just going to find the repo straight off
// This is fastest if it succeeds, but might be case-sensitive
var knownRepos = repositoryRepository.GetRepository(incomingRepositoryName);
if (knownRepos != null)
{
return knownRepos.Name;
}
// We might have a real repo, but it wasn't returned by GetRepository, because that's not
// guaranteed to be case insensitive (very difficult to assure this with EF, because it's the back
// end which matters, not EF itself)
// We'll try and check all repos in a slow but safe fashion
knownRepos =
repositoryRepository.GetAllRepositories()
.FirstOrDefault(
repo => repo.Name.Equals(incomingRepositoryName, StringComparison.OrdinalIgnoreCase));
if (knownRepos != null)
{
// We've found it now
return knownRepos.Name;
}
// We can't find this repo - it's probably invalid, but it's not
// our job to worry about that
return incomingRepositoryName;
}
}
}
| 31.413793 | 127 | 0.547201 | [
"MIT"
] | 16it/Bonobo-Git-Server | Bonobo.Git.Server/Data/Repository.cs | 3,644 | C# |
using System.Threading.Tasks;
using ExamKing.Application.Mappers;
namespace ExamKing.WebApp.Admin
{
/// <summary>
/// 权限管理器
/// </summary>
public interface IAuthorizationManager
{
/// <summary>
/// 获取管理员实体
/// </summary>
/// <returns></returns>
Task<AdminDto> GetAdmin();
/// <summary>
/// 检查授权
/// </summary>
/// <param name="resourceId"></param>
/// <returns></returns>
bool CheckSecurity(string resourceId);
}
} | 22 | 46 | 0.535985 | [
"MIT"
] | pig0224/ExamKing | ExamKing.WebApp.Admin/Security/Managers/IAuthorizationManager.cs | 560 | C# |
using P03.WildFarm.Contracts;
namespace P03.WildFarm.Classes.Animals.Mammals
{
public abstract class Feline : Mammal, IFeline
{
protected Feline(string name, double weight, string livingRegion, string breed)
:base(name, weight, livingRegion)
{
Breed = breed;
}
public string Breed { get; private set; }
public override string ToString()
{
return $"{this.GetType().Name} [{this.Name}, {this.Breed}, {this.Weight}, {this.LivingRegion}, {this.FoodEaten}]";
}
}
} | 28.4 | 126 | 0.600352 | [
"MIT"
] | vankatalp360/C-OOP-Basics | POLYMORPHISM/Exercise/Polymorphism - Exercise/P03.WildFarm/Classes/Animals/Mammals/Feline.cs | 570 | C# |
namespace AngleSharp.Css.Tests.Functions
{
using AngleSharp.Css.Dom;
using AngleSharp.Dom;
using NUnit.Framework;
using System.Linq;
using static CssConstructionFunctions;
[TestFixture]
public class CssDocumentFunctionTests
{
[Test]
public void CssDocumentRuleSingleUrlFunction()
{
var snippet = "@document url(http://www.w3.org/) { }";
var rule = ParseRule(snippet) as ICssDocumentRule;
Assert.IsNotNull(rule);
Assert.AreEqual(CssRuleType.Document, rule.Type);
Assert.AreEqual(1, rule.Conditions.Count());
var condition = rule.Conditions.First();
Assert.AreEqual("url", condition.Name);
Assert.AreEqual("http://www.w3.org/", condition.Data);
Assert.IsFalse(condition.Matches(Url.Create("https://www.w3.org/")));
Assert.IsTrue(condition.Matches(Url.Create("http://www.w3.org")));
}
[Test]
public void CssDocumentRuleSingleUrlPrefixFunction()
{
var snippet = "@document url-prefix('http://www.w3.org/Style/') { }";
var rule = ParseRule(snippet) as ICssDocumentRule;
Assert.IsNotNull(rule);
Assert.AreEqual(CssRuleType.Document, rule.Type);
Assert.AreEqual(1, rule.Conditions.Count());
var condition = rule.Conditions.First();
Assert.AreEqual("url-prefix", condition.Name);
Assert.AreEqual("http://www.w3.org/Style/", condition.Data);
Assert.IsFalse(condition.Matches(Url.Create("https://www.w3.org/Style/")));
Assert.IsTrue(condition.Matches(Url.Create("http://www.w3.org/Style/foo/bar")));
}
[Test]
public void CssDocumentRuleSingleDomainFunction()
{
var snippet = "@document domain('mozilla.org') { }";
var rule = ParseRule(snippet) as ICssDocumentRule;
Assert.IsNotNull(rule);
Assert.AreEqual(CssRuleType.Document, rule.Type);
Assert.AreEqual(1, rule.Conditions.Count());
var condition = rule.Conditions.First();
Assert.AreEqual("domain", condition.Name);
Assert.AreEqual("mozilla.org", condition.Data);
Assert.IsFalse(condition.Matches(Url.Create("https://www.w3.org/")));
Assert.IsTrue(condition.Matches(Url.Create("http://mozilla.org")));
Assert.IsTrue(condition.Matches(Url.Create("http://www.mozilla.org")));
Assert.IsTrue(condition.Matches(Url.Create("http://foo.mozilla.org")));
}
[Test]
public void CssDocumentRuleSingleRegexpFunction()
{
var snippet = "@document regexp(\"https:.*\") { }";
var rule = ParseRule(snippet) as ICssDocumentRule;
Assert.IsNotNull(rule);
Assert.AreEqual(CssRuleType.Document, rule.Type);
Assert.AreEqual(1, rule.Conditions.Count());
var condition = rule.Conditions.First();
Assert.AreEqual("regexp", condition.Name);
Assert.AreEqual("https:.*", condition.Data);
Assert.IsFalse(condition.Matches(Url.Create("http://www.w3.org")));
Assert.IsTrue(condition.Matches(Url.Create("https://www.w3.org/")));
}
[Test]
public void CssDocumentRuleMultipleFunctions()
{
var snippet = "@document url(http://www.w3.org/), url-prefix('http://www.w3.org/Style/'), domain('mozilla.org'), regexp(\"https:.*\") { }";
var rule = ParseRule(snippet) as CssDocumentRule;
Assert.IsNotNull(rule);
Assert.AreEqual(CssRuleType.Document, rule.Type);
Assert.AreEqual(4, rule.Conditions.Count());
Assert.IsTrue(rule.IsValid(Url.Create("https://www.w3.org/")));
Assert.IsTrue(rule.IsValid(Url.Create("http://www.w3.org/")));
Assert.IsTrue(rule.IsValid(Url.Create("http://www.w3.org/Style/bar")));
Assert.IsTrue(rule.IsValid(Url.Create("https://test.mozilla.org/foo")));
Assert.IsFalse(rule.IsValid(Url.Create("http://localhost")));
}
}
}
| 46.333333 | 151 | 0.601199 | [
"MIT"
] | AngleSharp/AngleSharp.Css | src/AngleSharp.Css.Tests/Functions/CssDocumentFunction.cs | 4,172 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using AnZwDev.ALTools.Core;
namespace AnZwDev.ALTools.Workspace
{
public class ALProjectProperties
{
#region Public properties
public string Id { get; set; }
public string Name { get; set; }
public string Publisher { get; set; }
public VersionNumber Version { get; set; }
public VersionNumber Runtime { get; set; }
public List<ALProjectIdRange> Ranges { get; set; }
public List<ALProjectReference> InternalsVisibleTo { get; set; }
#endregion
public ALProjectProperties()
{
this.Ranges = new List<ALProjectIdRange>();
}
public ALProjectIdRange AddIdRange(long fromId, long toId)
{
ALProjectIdRange idRange = new ALProjectIdRange(fromId, toId);
this.Ranges.Add(idRange);
return idRange;
}
}
}
| 24.675 | 74 | 0.627153 | [
"MIT"
] | anzwdev/az-al-dev-tools-server | AZALDevToolsServer/Shared.AnZwDev.ALTools/Workspace/ALProjectProperties.cs | 989 | C# |
using System.Collections.Generic;
namespace CadastroSeries.Interfaces
{
public interface IRepositorio<T>
{
List<T> Lista();
T RetornaPorId(int id);
void Insere(T entidade);
void Exclui(int id);
void Atualiza(int id, T entidade);
int ProximoId();
}
} | 17.368421 | 42 | 0.575758 | [
"MIT"
] | Silva-Gabriel/Digital-Innovation-One | CadastroSeries/Interfaces/IRepositorio.cs | 330 | C# |
using System;
using System.Linq;
using CodeGen.JsonTypes;
namespace CodeGen.Generators.UnitsNetGen
{
/// <summary>
/// Generates base class for each quantity test class, with stubs for testing conversion functions and error tolerances that the developer must complete to fix compile errors.
/// </summary>
/// <example>
/// <list type="bullet">
/// <item><description>UnitsNet.Tests\GeneratedCode\AccelerationTestsBase.g.cs</description></item>
/// <item><description>UnitsNet.Tests\GeneratedCode\LengthTestsBase.g.cs</description></item>
/// </list>
/// </example>
internal class UnitTestBaseClassGenerator : GeneratorBase
{
/// <summary>
/// The quantity to generate test base class for.
/// </summary>
private readonly Quantity _quantity;
/// <summary>
/// Base unit for this quantity, such as Meter for quantity Length.
/// </summary>
private readonly Unit _baseUnit;
/// <summary>
/// Example: "LengthUnit"
/// </summary>
private readonly string _unitEnumName;
/// <summary>
/// Example: " m" for Length quantity with leading whitespace or "" for Ratio quantity where base unit does not have an abbreviation.
/// </summary>
private readonly string _baseUnitEnglishAbbreviation;
/// <summary>
/// Example: "LengthUnit.Meter".
/// </summary>
private readonly string _baseUnitFullName;
/// <summary>
/// Constructors for decimal-backed quantities require decimal numbers as input, so add the "m" suffix to numbers when constructing those quantities.
/// </summary>
private readonly string _numberSuffix;
public UnitTestBaseClassGenerator(Quantity quantity)
{
_quantity = quantity;
_baseUnit = quantity.Units.FirstOrDefault(u => u.SingularName == _quantity.BaseUnit) ??
throw new ArgumentException($"No unit found with SingularName equal to BaseUnit [{_quantity.BaseUnit}]. This unit must be defined.",
nameof(quantity));
_unitEnumName = $"{quantity.Name}Unit";
_baseUnitEnglishAbbreviation = GetEnglishAbbreviation(_baseUnit);
_baseUnitFullName = $"{_unitEnumName}.{_baseUnit.SingularName}";
_numberSuffix = quantity.BaseType == "decimal" ? "m" : "";
}
private string GetUnitFullName(Unit unit) => $"{_unitEnumName}.{unit.SingularName}";
/// <summary>
/// Gets the first en-US abbreviation for the unit -or- empty string if none is defined.
/// If a unit abbreviation exists, a leading whitespace is added to separate the number and the abbreviation like "1 m".
/// </summary>
private static string GetEnglishAbbreviation(Unit unit)
{
var unitAbbreviation = unit.Localization.First(l => l.Culture == "en-US").Abbreviations.FirstOrDefault();
return string.IsNullOrEmpty(unitAbbreviation) ? "" : $" {unitAbbreviation}";
}
public override string Generate()
{
var baseUnitVariableName = _baseUnit.SingularName.ToLowerInvariant();
Writer.WL(GeneratedFileHeader);
Writer.WL($@"
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using UnitsNet.Tests.TestsBase;
using UnitsNet.Units;
using Xunit;
// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else?
#pragma warning disable 1718
// ReSharper disable once CheckNamespace
namespace UnitsNet.Tests
{{
/// <summary>
/// Test of {_quantity.Name}.
/// </summary>
// ReSharper disable once PartialTypeWithSinglePart
public abstract partial class {_quantity.Name}TestsBase : QuantityTestsBase
{{");
foreach (var unit in _quantity.Units)
{
if (unit.SkipConversionGeneration)
continue;
Writer.WL($@"
protected abstract double {unit.PluralName}InOne{_baseUnit.SingularName} {{ get; }}");
}
Writer.WL("");
Writer.WL($@"
// ReSharper disable VirtualMemberNeverOverriden.Global");
foreach (var unit in _quantity.Units)
{
if (unit.SkipConversionGeneration)
continue;
Writer.WL($@"
protected virtual double {unit.PluralName}Tolerance {{ get {{ return 1e-5; }} }}");
}
Writer.WL($@"
// ReSharper restore VirtualMemberNeverOverriden.Global
protected (double UnitsInBaseUnit, double Tolerence) GetConversionFactor({_unitEnumName} unit)
{{
return unit switch
{{");
foreach(var unit in _quantity.Units) Writer.WL($@"
{GetUnitFullName(unit)} => ({unit.PluralName}InOne{_baseUnit.SingularName}, {unit.PluralName}Tolerance),");
Writer.WL($@"
_ => throw new NotSupportedException()
}};
}}
public static IEnumerable<object[]> UnitTypes = new List<object[]>
{{");
foreach(var unit in _quantity.Units)
{
Writer.WL($@"
new object[] {{ {GetUnitFullName(unit)} }},");
}
Writer.WL($@"
}};
[Fact]
public void Ctor_WithUndefinedUnit_ThrowsArgumentException()
{{
Assert.Throws<ArgumentException>(() => new {_quantity.Name}(({_quantity.BaseType})0.0, {_unitEnumName}.Undefined));
}}
[Fact]
public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit()
{{
var quantity = new {_quantity.Name}();
Assert.Equal(0, quantity.Value);");
if (_quantity.BaseType == "decimal") Writer.WL($@"
Assert.Equal(0m, ((IDecimalQuantity)quantity).Value);");
Writer.WL($@"
Assert.Equal({_baseUnitFullName}, quantity.Unit);
}}
");
if (_quantity.BaseType == "double") Writer.WL($@"
[Fact]
public void Ctor_WithInfinityValue_ThrowsArgumentException()
{{
Assert.Throws<ArgumentException>(() => new {_quantity.Name}(double.PositiveInfinity, {_baseUnitFullName}));
Assert.Throws<ArgumentException>(() => new {_quantity.Name}(double.NegativeInfinity, {_baseUnitFullName}));
}}
[Fact]
public void Ctor_WithNaNValue_ThrowsArgumentException()
{{
Assert.Throws<ArgumentException>(() => new {_quantity.Name}(double.NaN, {_baseUnitFullName}));
}}
"); Writer.WL($@"
[Fact]
public void Ctor_NullAsUnitSystem_ThrowsArgumentNullException()
{{
Assert.Throws<ArgumentNullException>(() => new {_quantity.Name}(value: 1, unitSystem: null));
}}
[Fact]
public void Ctor_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported()
{{
Func<object> TestCode = () => new {_quantity.Name}(value: 1, unitSystem: UnitSystem.SI);
if (SupportsSIUnitSystem)
{{
var quantity = ({_quantity.Name}) TestCode();
Assert.Equal(1, quantity.Value);
}}
else
{{
Assert.Throws<ArgumentException>(TestCode);
}}
}}
[Fact]
public void {_quantity.Name}_QuantityInfo_ReturnsQuantityInfoDescribingQuantity()
{{
var quantity = new {_quantity.Name}(1, {_baseUnitFullName});
QuantityInfo<{_unitEnumName}> quantityInfo = quantity.QuantityInfo;
Assert.Equal({_quantity.Name}.Zero, quantityInfo.Zero);
Assert.Equal(""{_quantity.Name}"", quantityInfo.Name);
Assert.Equal(QuantityType.{_quantity.Name}, quantityInfo.QuantityType);
var units = EnumUtils.GetEnumValues<{_unitEnumName}>().Except(new[] {{{_unitEnumName}.Undefined}}).ToArray();
var unitNames = units.Select(x => x.ToString());
// Obsolete members
Assert.Equal(units, quantityInfo.Units);
Assert.Equal(unitNames, quantityInfo.UnitNames);
}}
[Fact]
public void {_baseUnit.SingularName}To{_quantity.Name}Units()
{{
{_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);");
foreach(var unit in _quantity.Units) Writer.WL($@"
AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, {baseUnitVariableName}.{unit.PluralName}, {unit.PluralName}Tolerance);");
Writer.WL($@"
}}
[Fact]
public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit()
{{");
int i = 0;
foreach(var unit in _quantity.Units)
{
var quantityVariable = $"quantity{i++:D2}";
Writer.WL($@"
var {quantityVariable} = {_quantity.Name}.From(1, {GetUnitFullName(unit)});
AssertEx.EqualTolerance(1, {quantityVariable}.{unit.PluralName}, {unit.PluralName}Tolerance);
Assert.Equal({GetUnitFullName(unit)}, {quantityVariable}.Unit);
");
}
Writer.WL($@"
}}
");
if (_quantity.BaseType == "double") Writer.WL($@"
[Fact]
public void From{_baseUnit.PluralName}_WithInfinityValue_ThrowsArgumentException()
{{
Assert.Throws<ArgumentException>(() => {_quantity.Name}.From{_baseUnit.PluralName}(double.PositiveInfinity));
Assert.Throws<ArgumentException>(() => {_quantity.Name}.From{_baseUnit.PluralName}(double.NegativeInfinity));
}}
[Fact]
public void From{_baseUnit.PluralName}_WithNanValue_ThrowsArgumentException()
{{
Assert.Throws<ArgumentException>(() => {_quantity.Name}.From{_baseUnit.PluralName}(double.NaN));
}}
"); Writer.WL($@"
[Fact]
public void As()
{{
var {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);");
foreach(var unit in _quantity.Units) Writer.WL($@"
AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, {baseUnitVariableName}.As({GetUnitFullName(unit)}), {unit.PluralName}Tolerance);");
Writer.WL($@"
}}
[Fact]
public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported()
{{
var quantity = new {_quantity.Name}(value: 1, unit: {_quantity.Name}.BaseUnit);
Func<object> AsWithSIUnitSystem = () => quantity.As(UnitSystem.SI);
if (SupportsSIUnitSystem)
{{
var value = (double) AsWithSIUnitSystem();
Assert.Equal(1, value);
}}
else
{{
Assert.Throws<ArgumentException>(AsWithSIUnitSystem);
}}
}}
[Fact]
public void Parse()
{{");
foreach(var unit in _quantity.Units.Where(u => string.IsNullOrEmpty(u.ObsoleteText)))
foreach(var localization in unit.Localization)
foreach(var abbreviation in localization.Abbreviations)
{
Writer.WL($@"
try
{{
var parsed = {_quantity.Name}.Parse(""1 {abbreviation}"", CultureInfo.GetCultureInfo(""{localization.Culture}""));
AssertEx.EqualTolerance(1, parsed.{unit.PluralName}, {unit.PluralName}Tolerance);
Assert.Equal({GetUnitFullName(unit)}, parsed.Unit);
}} catch (AmbiguousUnitParseException) {{ /* Some units have the same abbreviations */ }}
");
}
Writer.WL($@"
}}
[Fact]
public void TryParse()
{{");
foreach(var unit in _quantity.Units.Where(u => string.IsNullOrEmpty(u.ObsoleteText)))
foreach(var localization in unit.Localization)
foreach(var abbreviation in localization.Abbreviations)
{
// Skip units with ambiguous abbreviations, since there is no exception to describe this is why TryParse failed.
if (IsAmbiguousAbbreviation(localization, abbreviation)) continue;
Writer.WL($@"
{{
Assert.True({_quantity.Name}.TryParse(""1 {abbreviation}"", CultureInfo.GetCultureInfo(""{localization.Culture}""), out var parsed));
AssertEx.EqualTolerance(1, parsed.{unit.PluralName}, {unit.PluralName}Tolerance);
Assert.Equal({GetUnitFullName(unit)}, parsed.Unit);
}}
");
}
Writer.WL($@"
}}
[Fact]
public void ParseUnit()
{{");
foreach(var unit in _quantity.Units.Where(u => string.IsNullOrEmpty(u.ObsoleteText)))
foreach(var localization in unit.Localization)
foreach(var abbreviation in localization.Abbreviations)
{
Writer.WL($@"
try
{{
var parsedUnit = {_quantity.Name}.ParseUnit(""{abbreviation}"", CultureInfo.GetCultureInfo(""{localization.Culture}""));
Assert.Equal({GetUnitFullName(unit)}, parsedUnit);
}} catch (AmbiguousUnitParseException) {{ /* Some units have the same abbreviations */ }}
");
}
Writer.WL($@"
}}
[Fact]
public void TryParseUnit()
{{");
foreach(var unit in _quantity.Units.Where(u => string.IsNullOrEmpty(u.ObsoleteText)))
foreach(var localization in unit.Localization)
foreach(var abbreviation in localization.Abbreviations)
{
// Skip units with ambiguous abbreviations, since there is no exception to describe this is why TryParse failed.
if (IsAmbiguousAbbreviation(localization, abbreviation)) continue;
Writer.WL($@"
{{
Assert.True({_quantity.Name}.TryParseUnit(""{abbreviation}"", CultureInfo.GetCultureInfo(""{localization.Culture}""), out var parsedUnit));
Assert.Equal({GetUnitFullName(unit)}, parsedUnit);
}}
");
}
Writer.WL($@"
}}
[Theory]
[MemberData(nameof(UnitTypes))]
public void ToUnit({_unitEnumName} unit)
{{
var inBaseUnits = {_quantity.Name}.From(1.0, {_quantity.Name}.BaseUnit);
var converted = inBaseUnits.ToUnit(unit);
var conversionFactor = GetConversionFactor(unit);
AssertEx.EqualTolerance(conversionFactor.UnitsInBaseUnit, (double)converted.Value, conversionFactor.Tolerence);
Assert.Equal(unit, converted.Unit);
}}
[Theory]
[MemberData(nameof(UnitTypes))]
public void ToUnit_WithSameUnits_AreEqual({_unitEnumName} unit)
{{
var quantity = {_quantity.Name}.From(3.0, unit);
var toUnitWithSameUnit = quantity.ToUnit(unit);
Assert.Equal(quantity, toUnitWithSameUnit);
}}
[Theory]
[MemberData(nameof(UnitTypes))]
public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit({_unitEnumName} unit)
{{
// See if there is a unit available that is not the base unit.
var fromUnit = {_quantity.Name}.Units.FirstOrDefault(u => u != {_quantity.Name}.BaseUnit && u != {_unitEnumName}.Undefined);
// If there is only one unit for the quantity, we must use the base unit.
if (fromUnit == {_unitEnumName}.Undefined)
fromUnit = {_quantity.Name}.BaseUnit;
var quantity = {_quantity.Name}.From(3.0, fromUnit);
var converted = quantity.ToUnit(unit);
Assert.Equal(converted.Unit, unit);
}}
[Fact]
public void ConversionRoundTrip()
{{
{_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);");
foreach (var unit in _quantity.Units) Writer.WL($@"
AssertEx.EqualTolerance(1, {_quantity.Name}.From{unit.PluralName}({baseUnitVariableName}.{unit.PluralName}).{_baseUnit.PluralName}, {unit.PluralName}Tolerance);");
Writer.WL($@"
}}
");
if (_quantity.Logarithmic)
{
var unit = _quantity.Units.Last();
Writer.WL($@"
[Fact]
public void LogarithmicArithmeticOperators()
{{
{_quantity.Name} v = {_quantity.Name}.From{_baseUnit.PluralName}(40);
AssertEx.EqualTolerance(-40, -v.{_baseUnit.PluralName}, {unit.PluralName}Tolerance);
AssertLogarithmicAddition();
AssertLogarithmicSubtraction();
AssertEx.EqualTolerance(50, (v*10).{_baseUnit.PluralName}, {unit.PluralName}Tolerance);
AssertEx.EqualTolerance(50, (10*v).{_baseUnit.PluralName}, {unit.PluralName}Tolerance);
AssertEx.EqualTolerance(35, (v/5).{_baseUnit.PluralName}, {unit.PluralName}Tolerance);
AssertEx.EqualTolerance(35, v/{_quantity.Name}.From{_baseUnit.PluralName}(5), {unit.PluralName}Tolerance);
}}
protected abstract void AssertLogarithmicAddition();
protected abstract void AssertLogarithmicSubtraction();
");
}
else if (_quantity.GenerateArithmetic)
{
Writer.WL($@"
[Fact]
public void ArithmeticOperators()
{{
{_quantity.Name} v = {_quantity.Name}.From{_baseUnit.PluralName}(1);
AssertEx.EqualTolerance(-1, -v.{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance);
AssertEx.EqualTolerance(2, ({_quantity.Name}.From{_baseUnit.PluralName}(3)-v).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance);
AssertEx.EqualTolerance(2, (v + v).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance);
AssertEx.EqualTolerance(10, (v*10).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance);
AssertEx.EqualTolerance(10, (10*v).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance);
AssertEx.EqualTolerance(2, ({_quantity.Name}.From{_baseUnit.PluralName}(10)/5).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance);
AssertEx.EqualTolerance(2, {_quantity.Name}.From{_baseUnit.PluralName}(10)/{_quantity.Name}.From{_baseUnit.PluralName}(5), {_baseUnit.PluralName}Tolerance);
}}
");
}
else
{
Writer.WL("");
}
Writer.WL($@"
[Fact]
public void ComparisonOperators()
{{
{_quantity.Name} one{_baseUnit.SingularName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);
{_quantity.Name} two{_baseUnit.PluralName} = {_quantity.Name}.From{_baseUnit.PluralName}(2);
Assert.True(one{_baseUnit.SingularName} < two{_baseUnit.PluralName});
Assert.True(one{_baseUnit.SingularName} <= two{_baseUnit.PluralName});
Assert.True(two{_baseUnit.PluralName} > one{_baseUnit.SingularName});
Assert.True(two{_baseUnit.PluralName} >= one{_baseUnit.SingularName});
Assert.False(one{_baseUnit.SingularName} > two{_baseUnit.PluralName});
Assert.False(one{_baseUnit.SingularName} >= two{_baseUnit.PluralName});
Assert.False(two{_baseUnit.PluralName} < one{_baseUnit.SingularName});
Assert.False(two{_baseUnit.PluralName} <= one{_baseUnit.SingularName});
}}
[Fact]
public void CompareToIsImplemented()
{{
{_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);
Assert.Equal(0, {baseUnitVariableName}.CompareTo({baseUnitVariableName}));
Assert.True({baseUnitVariableName}.CompareTo({_quantity.Name}.Zero) > 0);
Assert.True({_quantity.Name}.Zero.CompareTo({baseUnitVariableName}) < 0);
}}
[Fact]
public void CompareToThrowsOnTypeMismatch()
{{
{_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);
Assert.Throws<ArgumentException>(() => {baseUnitVariableName}.CompareTo(new object()));
}}
[Fact]
public void CompareToThrowsOnNull()
{{
{_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);
Assert.Throws<ArgumentNullException>(() => {baseUnitVariableName}.CompareTo(null));
}}
[Fact]
public void EqualityOperators()
{{
var a = {_quantity.Name}.From{_baseUnit.PluralName}(1);
var b = {_quantity.Name}.From{_baseUnit.PluralName}(2);
#pragma warning disable CS8073
// ReSharper disable EqualExpressionComparison
Assert.True(a == a);
Assert.False(a != a);
Assert.True(a != b);
Assert.False(a == b);
Assert.False(a == null);
Assert.False(null == a);
// ReSharper restore EqualExpressionComparison
#pragma warning restore CS8073
}}
[Fact]
public void Equals_SameType_IsImplemented()
{{
var a = {_quantity.Name}.From{_baseUnit.PluralName}(1);
var b = {_quantity.Name}.From{_baseUnit.PluralName}(2);
Assert.True(a.Equals(a));
Assert.False(a.Equals(b));
}}
[Fact]
public void Equals_QuantityAsObject_IsImplemented()
{{
object a = {_quantity.Name}.From{_baseUnit.PluralName}(1);
object b = {_quantity.Name}.From{_baseUnit.PluralName}(2);
Assert.True(a.Equals(a));
Assert.False(a.Equals(b));
Assert.False(a.Equals((object)null));
}}
[Fact]
public void Equals_RelativeTolerance_IsImplemented()
{{
var v = {_quantity.Name}.From{_baseUnit.PluralName}(1);
Assert.True(v.Equals({_quantity.Name}.From{_baseUnit.PluralName}(1), {_baseUnit.PluralName}Tolerance, ComparisonType.Relative));
Assert.False(v.Equals({_quantity.Name}.Zero, {_baseUnit.PluralName}Tolerance, ComparisonType.Relative));
}}
[Fact]
public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException()
{{
var v = {_quantity.Name}.From{_baseUnit.PluralName}(1);
Assert.Throws<ArgumentOutOfRangeException>(() => v.Equals({_quantity.Name}.From{_baseUnit.PluralName}(1), -1, ComparisonType.Relative));
}}
[Fact]
public void EqualsReturnsFalseOnTypeMismatch()
{{
{_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);
Assert.False({baseUnitVariableName}.Equals(new object()));
}}
[Fact]
public void EqualsReturnsFalseOnNull()
{{
{_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);
Assert.False({baseUnitVariableName}.Equals(null));
}}
[Fact]
public void UnitsDoesNotContainUndefined()
{{
Assert.DoesNotContain({_unitEnumName}.Undefined, {_quantity.Name}.Units);
}}
[Fact]
public void HasAtLeastOneAbbreviationSpecified()
{{
var units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>();
foreach(var unit in units)
{{
if (unit == {_unitEnumName}.Undefined)
continue;
var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit);
}}
}}
[Fact]
public void BaseDimensionsShouldNeverBeNull()
{{
Assert.False({_quantity.Name}.BaseDimensions is null);
}}
[Fact]
public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture()
{{
var prevCulture = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(""en-US"");
try {{");
foreach (var unit in _quantity.Units)
{
Writer.WL($@"
Assert.Equal(""1{GetEnglishAbbreviation(unit)}"", new {_quantity.Name}(1, {GetUnitFullName(unit)}).ToString());");
}
Writer.WL($@"
}}
finally
{{
Thread.CurrentThread.CurrentUICulture = prevCulture;
}}
}}
[Fact]
public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCultureSinceThereAreNoMappings()
{{
// Chose this culture, because we don't currently have any abbreviations mapped for that culture and we expect the en-US to be used as fallback.
var swedishCulture = CultureInfo.GetCultureInfo(""sv-SE"");
");
foreach (var unit in _quantity.Units)
{
Writer.WL($@"
Assert.Equal(""1{GetEnglishAbbreviation(unit)}"", new {_quantity.Name}(1, {GetUnitFullName(unit)}).ToString(swedishCulture));");
}
Writer.WL($@"
}}
[Fact]
public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture()
{{
var oldCulture = CultureInfo.CurrentUICulture;
try
{{
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
Assert.Equal(""0.1{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s1""));
Assert.Equal(""0.12{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s2""));
Assert.Equal(""0.123{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s3""));
Assert.Equal(""0.1235{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s4""));
}}
finally
{{
CultureInfo.CurrentUICulture = oldCulture;
}}
}}
[Fact]
public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixForGivenCulture()
{{
var culture = CultureInfo.InvariantCulture;
Assert.Equal(""0.1{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s1"", culture));
Assert.Equal(""0.12{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s2"", culture));
Assert.Equal(""0.123{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s3"", culture));
Assert.Equal(""0.1235{_baseUnitEnglishAbbreviation}"", new {_quantity.Name}(0.123456{_numberSuffix}, {_baseUnitFullName}).ToString(""s4"", culture));
}}
[Fact]
public void ToString_NullFormat_ThrowsArgumentNullException()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Throws<ArgumentNullException>(() => quantity.ToString(null, null, null));
}}
[Fact]
public void ToString_NullArgs_ThrowsArgumentNullException()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Throws<ArgumentNullException>(() => quantity.ToString(null, ""g"", null));
}}
[Fact]
public void ToString_NullProvider_EqualsCurrentUICulture()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal(quantity.ToString(CultureInfo.CurrentUICulture, ""g""), quantity.ToString(null, ""g""));
}}
[Fact]
public void Convert_ToBool_ThrowsInvalidCastException()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Throws<InvalidCastException>(() => Convert.ToBoolean(quantity));
}}
[Fact]
public void Convert_ToByte_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity));
}}
[Fact]
public void Convert_ToChar_ThrowsInvalidCastException()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Throws<InvalidCastException>(() => Convert.ToChar(quantity));
}}
[Fact]
public void Convert_ToDateTime_ThrowsInvalidCastException()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Throws<InvalidCastException>(() => Convert.ToDateTime(quantity));
}}
[Fact]
public void Convert_ToDecimal_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity));
}}
[Fact]
public void Convert_ToDouble_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity));
}}
[Fact]
public void Convert_ToInt16_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity));
}}
[Fact]
public void Convert_ToInt32_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity));
}}
[Fact]
public void Convert_ToInt64_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity));
}}
[Fact]
public void Convert_ToSByte_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity));
}}
[Fact]
public void Convert_ToSingle_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity));
}}
[Fact]
public void Convert_ToString_EqualsToString()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal(quantity.ToString(), Convert.ToString(quantity));
}}
[Fact]
public void Convert_ToUInt16_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity));
}}
[Fact]
public void Convert_ToUInt32_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity));
}}
[Fact]
public void Convert_ToUInt64_EqualsValueAsSameType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity));
}}
[Fact]
public void Convert_ChangeType_SelfType_EqualsSelf()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal(quantity, Convert.ChangeType(quantity, typeof({_quantity.Name})));
}}
[Fact]
public void Convert_ChangeType_UnitType_EqualsUnit()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof({_unitEnumName})));
}}
[Fact]
public void Convert_ChangeType_QuantityType_EqualsQuantityType()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal(QuantityType.{_quantity.Name}, Convert.ChangeType(quantity, typeof(QuantityType)));
}}
[Fact]
public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal({_quantity.Name}.Info, Convert.ChangeType(quantity, typeof(QuantityInfo)));
}}
[Fact]
public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal({_quantity.Name}.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions)));
}}
[Fact]
public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Throws<InvalidCastException>(() => Convert.ChangeType(quantity, typeof(QuantityFormatter)));
}}
[Fact]
public void GetHashCode_Equals()
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0);
Assert.Equal(new {{{_quantity.Name}.Info.Name, quantity.Value, quantity.Unit}}.GetHashCode(), quantity.GetHashCode());
}}
");
if (_quantity.GenerateArithmetic)
{
Writer.WL($@"
[Theory]
[InlineData(1.0)]
[InlineData(-1.0)]
public void NegationOperator_ReturnsQuantity_WithNegatedValue(double value)
{{
var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(value);
Assert.Equal({_quantity.Name}.From{_baseUnit.PluralName}(-value), -quantity);
}}");
}
Writer.WL($@"
}}
}}");
return Writer.ToString();
}
private bool IsAmbiguousAbbreviation(Localization localization, string abbreviation)
{
return _quantity.Units.Count(u =>
u.Localization.SingleOrDefault(l => l.Culture == localization.Culture) is { } otherUnitLocalization &&
otherUnitLocalization.Abbreviations.Contains(abbreviation, StringComparer.OrdinalIgnoreCase)) > 1;
}
}
}
| 40.703271 | 179 | 0.604673 | [
"MIT-feh"
] | AndreasLeeb/UnitsNet | CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs | 34,844 | C# |
using SportsStore.WebUI.Infrastructure.Abstract;
using SportsStore.WebUI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SportsStore.WebUI.Controllers
{
public class AccountController : Controller
{
private IAuthProvider authProvider;
public AccountController(IAuthProvider authProviderParam)
{
authProvider = authProviderParam;
}
// GET: Account
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (authProvider.Authenticate(model.UserName, model.Password))
{
return Redirect(returnUrl ?? Url.Action("Index", "Admin"));
} else
{
ModelState.AddModelError("", "Incorrect username or password");
return View();
}
}
return View();
}
}
} | 27.071429 | 83 | 0.562005 | [
"MIT"
] | hwebz/pro-aspnet-mvc-5-fifth-edition | SportsStore/SportsStore.WebUI/Controllers/AccountController.cs | 1,139 | C# |
using System.Reflection;
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("TddAnalyzer.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TddAnalyzer.Test")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | 38.1875 | 84 | 0.739771 | [
"MIT"
] | andrecarlucci/tddanalyzer | TddAnalyzer/TddAnalyzer.Test/Properties/AssemblyInfo.cs | 1,225 | C# |
using System;
using System.Collections.Generic;
namespace GitVersion.VersionCalculation
{
/// <summary>
/// Version is from NextVersion (the configuration value), unless the current commit is tagged.
/// BaseVersionSource is null.
/// Does not increment.
/// </summary>
public class ConfigNextVersionVersionStrategy : VersionStrategyBase
{
public ConfigNextVersionVersionStrategy(Lazy<GitVersionContext> versionContext) : base(versionContext)
{
}
public override IEnumerable<BaseVersion> GetVersions()
{
if (string.IsNullOrEmpty(Context.Configuration.NextVersion) || Context.IsCurrentCommitTagged)
yield break;
var semanticVersion = SemanticVersion.Parse(Context.Configuration.NextVersion, Context.Configuration.GitTagPrefix);
yield return new BaseVersion("NextVersion in GitVersion configuration file", false, semanticVersion, null, null);
}
}
}
| 37.730769 | 127 | 0.702345 | [
"MIT"
] | AlexGoris-KasparSolutions/GitVersion | src/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs | 981 | C# |
namespace ClassLib069
{
public class Class069
{
public static string Property => "ClassLib069";
}
}
| 15 | 55 | 0.633333 | [
"MIT"
] | 333fred/performance | src/scenarios/weblarge2.0/src/ClassLib069/Class069.cs | 120 | C# |
// <copyright file="IQuestion.cs" company="Ocean">
// Copyright (c) Ocean. All rights reserved.
// </copyright>
namespace Questions.LeetCode.No16.ThreeSumClosest
{
using Questions.Interfaces;
/// <summary>
/// The LeetCode No.16 question: Three Sum Closest.
/// </summary>
public interface IQuestion : IBaseQuestion
{
/// <summary>
/// Gets the sum of triplets which is closest to target.
/// </summary>
/// <param name="nums">The number array.</param>
/// <param name="target">The target.</param>
/// <returns>The closest sum of triplet.</returns>
int ThreeSumClosest(int[] nums, int target);
}
}
| 29.782609 | 64 | 0.616058 | [
"MIT"
] | OceanSJY/data-structures-and-algorithms-training | csharpsrc/Questions/LeetCode/No16.ThreeSumClosest/IQuestion.cs | 687 | C# |
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace Antja.Authentication.HMAC
{
public static class HMACUtilities
{
public static string GetSignaturePrefix(HMACHashFunctions hashFunction)
{
return $"sha{(int)hashFunction}=";
}
public static byte[] ComputeHash(HMACHashFunctions hashFunction, string secret, byte[] buffer)
{
return hashFunction switch
{
HMACHashFunctions.SHA1 => new HMACSHA1(Encoding.ASCII.GetBytes(secret)).ComputeHash(buffer),
HMACHashFunctions.SHA256 => new HMACSHA256(Encoding.ASCII.GetBytes(secret)).ComputeHash(buffer),
HMACHashFunctions.SHA512 => new HMACSHA512(Encoding.ASCII.GetBytes(secret)).ComputeHash(buffer),
_ => throw new ArgumentOutOfRangeException(nameof(hashFunction), hashFunction, "Hash function not supported")
};
}
public static string ToHexString(IReadOnlyCollection<byte> bytes)
{
var builder = new StringBuilder(bytes.Count * 2);
foreach (var b in bytes)
{
builder.AppendFormat("{0:x2}", b);
}
return builder.ToString();
}
}
}
| 33.564103 | 125 | 0.627196 | [
"MIT"
] | antja0/hmac-authentication | HMACAuthentication/HMACUtilities.cs | 1,311 | C# |
using System;
using System.Collections.Generic;
using ZodiacCiphers.Ciphers;
namespace ZodiacCiphers.Keys
{
public class Key408 : Key<S>
{
public static IReadOnlyDictionary<char, S[]> Map { get; } = CreateMap();
public static IReadOnlyDictionary<S, char> Index { get; } = IndexMap();
public override char[] Decode(Cipher<S> cipher)
{
var symbols = cipher.Symbols;
var decoded = new char[symbols.Length];
var i = 0;
foreach (var symbol in symbols)
{
decoded[i] = Index.ContainsKey(symbol)
? Index[symbol]
: '?';
i++;
}
return decoded;
}
public override Cipher<S> Encode(string text, int width)
{
text = text.Replace(" ", "").ToUpperInvariant();
var cipher = new AnonCipher<S>();
var encoded = new S[text.Length];
for (int i = 0; i < text.Length; i++)
{
var ch = text[i];
var symbol = Map.ContainsKey(ch)
? Map[ch][0]
: S.Unknown;
encoded[i] = symbol;
}
cipher.SetSymbols(encoded, width);
return cipher;
}
private static Dictionary<S, char> IndexMap()
{
var index = new Dictionary<S, char>();
foreach (var entry in Map)
{
foreach (var symbol in entry.Value)
{
index[symbol] = entry.Key;
}
}
return index;
}
private static Dictionary<char, S[]> CreateMap()
{
return new Dictionary<char, S[]> {
{ 'A', new []{ S.G, S.S, S.LBackwards, S.TriangleFilled } },
{ 'B', new []{ S.ArrowDown } },
{ 'C', new []{ S.EBackwards } },
{ 'D', new []{ S.FBackwards, S.Zodiac } },
{ 'E', new []{ S.Z, S.PBackwards, S.W, S.Plus, S.N, S.E, S.CircleTarget } },
{ 'F', new []{ S.J, S.Q } },
{ 'G', new []{ S.R } },
{ 'H', new []{ S.M, S.CircleLineHoriz } },
{ 'I', new []{ S.TriangleEmpty, S.P, S.U, S.KBackwards } },
{ 'K', new []{ S.ForwardSlash } },
{ 'L', new []{ S.SquareOpenTopLeft, S.B, S.SquareFilled } },
{ 'M', new []{ S.QBackwards } },
{ 'N', new []{ S.O, S.ArrowUp, S.D, S.CircleLineVert } },
{ 'O', new []{ S.X, S.DogNose, S.T, S.DBackwards } },
{ 'P', new []{ S.Pi } },
{ 'R', new []{ S.TUpsideDown, S.RBackwards, S.BackwardSlash } },
{ 'S', new []{ S.F, S.SquareTarget, S.K, S.TriangleTarget } },
{ 'T', new []{ S.H, S.I, S.CircleFilled, S.L } },
{ 'U', new []{ S.Y } },
{ 'V', new []{ S.CBackwards } },
{ 'W', new []{ S.A } },
{ 'X', new []{ S.JBackwards } },
{ 'Y', new []{ S.SquareEmpty } },
};
}
}
}
| 35.797753 | 92 | 0.415568 | [
"MIT"
] | creyke/ZodiacCiphers | ZodiacCiphers/Keys/Key408.cs | 3,188 | C# |
/********************************************************************************
* IServiceProviderBasicExtensions.cs *
* *
* Author: Denes Solti *
********************************************************************************/
using System;
namespace Solti.Utils.DI.Interfaces
{
/// <summary>
/// Defines basic extensions for the <see cref="IServiceProvider"/> interface.
/// </summary>
public static class IServiceProviderBasicExtensions
{
/// <summary>
/// Gets the service instance associated with the given interface.
/// </summary>
public static TInterface? GetService<TInterface>(this IServiceProvider self) where TInterface : class
{
if (self is null)
throw new ArgumentNullException(nameof(self));
return (TInterface?) self.GetService(typeof(TInterface));
}
}
} | 41 | 109 | 0.434334 | [
"MIT"
] | Sholtee/injector | SRC/Interfaces/Extensions/IServiceProviderBasicExtensions.cs | 1,066 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace SZDC.Data.Migrations
{
public partial class Init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Railways",
columns: table => new
{
RailwayNumber = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Railways", x => x.RailwayNumber);
});
migrationBuilder.CreateTable(
name: "StaticTrainEvent",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
Hours = table.Column<int>(nullable: false),
Minutes = table.Column<int>(nullable: false),
HasMoreThan30Seconds = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_StaticTrainEvent", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Station",
columns: table => new
{
Name = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Station", x => x.Name);
});
migrationBuilder.CreateTable(
name: "Track",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
Number = table.Column<string>(nullable: true),
TrackType = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Track", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Trains",
columns: table => new
{
TrainNumber = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
TrainType = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Trains", x => x.TrainNumber);
});
migrationBuilder.CreateTable(
name: "StationStop",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
StationName = table.Column<string>(nullable: true),
ArrivalId = table.Column<long>(nullable: true),
DepartureId = table.Column<long>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_StationStop", x => x.Id);
table.ForeignKey(
name: "FK_StationStop_StaticTrainEvent_ArrivalId",
column: x => x.ArrivalId,
principalTable: "StaticTrainEvent",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_StationStop_StaticTrainEvent_DepartureId",
column: x => x.DepartureId,
principalTable: "StaticTrainEvent",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_StationStop_Station_StationName",
column: x => x.StationName,
principalTable: "Station",
principalColumn: "Name",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "OrderedTrack",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
TrackId = table.Column<long>(nullable: false),
Order = table.Column<int>(nullable: false),
StationName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_OrderedTrack", x => x.Id);
table.ForeignKey(
name: "FK_OrderedTrack_Station_StationName",
column: x => x.StationName,
principalTable: "Station",
principalColumn: "Name",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_OrderedTrack_Track_TrackId",
column: x => x.TrackId,
principalTable: "Track",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "RailwaySection",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
RailwayNumber = table.Column<string>(nullable: true),
TrainNumber = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_RailwaySection", x => x.Id);
table.ForeignKey(
name: "FK_RailwaySection_Railways_RailwayNumber",
column: x => x.RailwayNumber,
principalTable: "Railways",
principalColumn: "RailwayNumber",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_RailwaySection_Trains_TrainNumber",
column: x => x.TrainNumber,
principalTable: "Trains",
principalColumn: "TrainNumber",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "StationStopOrder",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
StationStopId = table.Column<long>(nullable: false),
Order = table.Column<int>(nullable: false),
TrainNumber = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_StationStopOrder", x => x.Id);
table.ForeignKey(
name: "FK_StationStopOrder_StationStop_StationStopId",
column: x => x.StationStopId,
principalTable: "StationStop",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_StationStopOrder_Trains_TrainNumber",
column: x => x.TrainNumber,
principalTable: "Trains",
principalColumn: "TrainNumber",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "RailwaySectionStation",
columns: table => new
{
Id = table.Column<long>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
StationName = table.Column<string>(nullable: false),
KilometersInSegment = table.Column<double>(nullable: false),
KilometersString = table.Column<string>(nullable: true),
StationOrder = table.Column<int>(nullable: false),
RailwaySectionId = table.Column<long>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_RailwaySectionStation", x => x.Id);
table.ForeignKey(
name: "FK_RailwaySectionStation_RailwaySection_RailwaySectionId",
column: x => x.RailwaySectionId,
principalTable: "RailwaySection",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_RailwaySectionStation_Station_StationName",
column: x => x.StationName,
principalTable: "Station",
principalColumn: "Name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_OrderedTrack_StationName",
table: "OrderedTrack",
column: "StationName");
migrationBuilder.CreateIndex(
name: "IX_OrderedTrack_TrackId",
table: "OrderedTrack",
column: "TrackId");
migrationBuilder.CreateIndex(
name: "IX_RailwaySection_RailwayNumber",
table: "RailwaySection",
column: "RailwayNumber");
migrationBuilder.CreateIndex(
name: "IX_RailwaySection_TrainNumber",
table: "RailwaySection",
column: "TrainNumber");
migrationBuilder.CreateIndex(
name: "IX_RailwaySectionStation_RailwaySectionId",
table: "RailwaySectionStation",
column: "RailwaySectionId");
migrationBuilder.CreateIndex(
name: "IX_RailwaySectionStation_StationName",
table: "RailwaySectionStation",
column: "StationName");
migrationBuilder.CreateIndex(
name: "IX_StationStop_ArrivalId",
table: "StationStop",
column: "ArrivalId");
migrationBuilder.CreateIndex(
name: "IX_StationStop_DepartureId",
table: "StationStop",
column: "DepartureId");
migrationBuilder.CreateIndex(
name: "IX_StationStop_StationName",
table: "StationStop",
column: "StationName");
migrationBuilder.CreateIndex(
name: "IX_StationStopOrder_StationStopId",
table: "StationStopOrder",
column: "StationStopId");
migrationBuilder.CreateIndex(
name: "IX_StationStopOrder_TrainNumber",
table: "StationStopOrder",
column: "TrainNumber");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "OrderedTrack");
migrationBuilder.DropTable(
name: "RailwaySectionStation");
migrationBuilder.DropTable(
name: "StationStopOrder");
migrationBuilder.DropTable(
name: "Track");
migrationBuilder.DropTable(
name: "RailwaySection");
migrationBuilder.DropTable(
name: "StationStop");
migrationBuilder.DropTable(
name: "Railways");
migrationBuilder.DropTable(
name: "Trains");
migrationBuilder.DropTable(
name: "StaticTrainEvent");
migrationBuilder.DropTable(
name: "Station");
}
}
}
| 42.169935 | 114 | 0.491785 | [
"MIT"
] | Sykoj/GTTG | solution/SZDC.Data/Migrations/20190511211754_Init.cs | 12,906 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d11.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace TerraFX.Interop.DirectX.UnitTests;
/// <summary>Provides validation of the <see cref="D3D11_VIDEO_COLOR" /> struct.</summary>
[SupportedOSPlatform("windows8.0")]
public static unsafe partial class D3D11_VIDEO_COLORTests
{
/// <summary>Validates that the <see cref="D3D11_VIDEO_COLOR" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<D3D11_VIDEO_COLOR>(), Is.EqualTo(sizeof(D3D11_VIDEO_COLOR)));
}
/// <summary>Validates that the <see cref="D3D11_VIDEO_COLOR" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(D3D11_VIDEO_COLOR).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="D3D11_VIDEO_COLOR" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(D3D11_VIDEO_COLOR), Is.EqualTo(16));
}
}
| 37.351351 | 145 | 0.723589 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/DirectX/um/d3d11/D3D11_VIDEO_COLORTests.cs | 1,384 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using McMaster.Extensions.CommandLineUtils;
using McMaster.Extensions.CommandLineUtils.Validation;
namespace DnsPush.Core.OptionValidators
{
public class SldLengthValidator : IOptionValidator
{
public ValidationResult GetValidationResult(CommandOption option, ValidationContext context)
{
// This validator only runs if there is a value
if (!option.HasValue()) return ValidationResult.Success;
var val = option.Value();
if (val.Length < 1)
{
return new ValidationResult($"The value for --{option.LongName} must not be empty");
}
if (val.Length > 70)
{
return new ValidationResult($"The value for --{option.LongName} must be 70 characters in length or less");
}
return ValidationResult.Success;
}
}
} | 33.892857 | 122 | 0.634352 | [
"MIT"
] | x3haloed/dnspush | src/DnsPush.Core/OptionValidators/SldLengthValidator.cs | 949 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Mediachase.Ibn.Data;
using Mediachase.Ibn.Data.Meta.Management;
using Mediachase.IBN.Database;
//using Mediachase.IbnNext;
using Mediachase.Ibn.Data.Services;
using Mediachase.IbnNext.TimeTracking;
using Mediachase.IBN.Business.SpreadSheet;
//using Mediachase.IbnNext.Activity;
using Mediachase.Ibn.Data.Meta;
//using Mediachase.IbnNext.Events;
namespace Mediachase.IBN.Business
{
public class TimeTracking
{
#region GetListTimeTrackingItemsForAdd
/// <summary>
/// ObjectId, ObjectTypeId, ObjectName, BlockTypeInstanceId
/// </summary>
/// <returns></returns>
public static IDataReader GetListTimeTrackingItemsForAdd(int blockTypeInstanceId, DateTime startDate, int userId)
{
return DbTimeTracking.GetListTimeTrackingItemsForAdd(blockTypeInstanceId, startDate, userId);
}
public static DataTable GetListTimeTrackingItemsForAdd_DataTable(int blockTypeInstanceId, DateTime startDate, int userId)
{
return DbTimeTracking.GetListTimeTrackingItemsForAdd_DataTable(blockTypeInstanceId, startDate, userId);
}
#endregion
#region GetWeekStart
public static DateTime GetWeekStart(DateTime dt)
{
dt = dt.Date;
int dow = (int)dt.DayOfWeek;
int fdow = PortalConfig.PortalFirstDayOfWeek;
fdow = (fdow == 7) ? 0 : fdow;
int diff = dow - fdow;
DateTime result;
if (diff < 0)
result = dt.AddDays(-(7 + diff));
else
result = dt.AddDays(-diff);
if (result.Year < dt.Year)
result = new DateTime(dt.Year, 1, 1);
return result;
}
#endregion
#region GetRealWeekStart
public static DateTime GetRealWeekStart(DateTime dt)
{
dt = dt.Date;
int dow = (int)dt.DayOfWeek;
int fdow = PortalConfig.PortalFirstDayOfWeek;
fdow = (fdow == 7) ? 0 : fdow;
int diff = dow - fdow;
DateTime result;
if (diff < 0)
result = dt.AddDays(-(7 + diff));
else
result = dt.AddDays(-diff);
return result;
}
#endregion
#region GetWeekEnd
public static DateTime GetWeekEnd(DateTime dt)
{
int dow = (int)dt.DayOfWeek;
int fdow = PortalConfig.PortalFirstDayOfWeek;
fdow = (fdow == 7) ? 0 : fdow;
int diff = dow - fdow;
DateTime result;
if (diff < 0)
result = dt.AddDays(-(7 + diff));
else
result = dt.AddDays(-diff);
result = result.AddDays(6);
if (result.Year > dt.Year)
result = new DateTime(dt.Year, 12, 31);
return result;
}
#endregion
#region GetRealWeekEnd
public static DateTime GetRealWeekEnd(DateTime dt)
{
int dow = (int)dt.DayOfWeek;
int fdow = PortalConfig.PortalFirstDayOfWeek;
fdow = (fdow == 7) ? 0 : fdow;
int diff = dow - fdow;
DateTime result;
if (diff < 0)
result = dt.AddDays(-(7 + diff));
else
result = dt.AddDays(-diff);
result = result.AddDays(6);
return result;
}
#endregion
#region GetDayNum
public static int GetDayNum(DateTime dt)
{
DateTime RealWeekStart = GetRealWeekStart(dt);
TimeSpan ts = dt.Subtract(RealWeekStart);
return ts.Days + 1;
}
#endregion
#region CanUpdate
public static bool CanUpdate(DateTime startDate, int projectId)
{
bool retval = false;
if (Configuration.TimeTrackingModule)
{
startDate = GetWeekStart(startDate);
// O.R. [2008-07-25]
TimeTrackingBlockTypeInstance inst = null;
using (SkipSecurityCheckScope scope = Mediachase.Ibn.Data.Services.Security.SkipSecurityCheck())
{
inst = TimeTrackingManager.GetBlockTypeInstanceByProject(projectId);
}
if (inst != null)
{
TimeTrackingBlock[] blocks = TimeTrackingBlock.List(
FilterElement.EqualElement("OwnerId", Security.CurrentUser.UserID),
FilterElement.EqualElement("BlockTypeInstanceId", inst.PrimaryKeyId.Value),
FilterElement.EqualElement("StartDate", startDate)
);
if (blocks.Length > 0) // Block exists
{
TimeTrackingBlock block = blocks[0];
SecurityService ss = block.GetService<SecurityService>();
retval = ss.CheckUserRight(TimeTrackingManager.Right_Write);
}
else // Block doesn't exist
{
SecurityService ss = inst.GetService<SecurityService>();
retval = ss.CheckUserRight(TimeTrackingManager.Right_AddMyTTBlock) || ss.CheckUserRight(TimeTrackingManager.Right_AddAnyTTBlock);
}
}
}
return retval;
}
#endregion
#region ResetObjectId
// Resets ObjectId and ObjectTypeId in cls_TimeSheetEntry
public static void ResetObjectId(int objectTypeId, int objectId)
{
DbTimeTracking.ResetObjectId(objectTypeId, objectId);
}
#endregion
#region GetListTimeTrackingItemsForFinances
/// <summary>
/// TimeTrackingEntryId, UserId, ObjectTypeId, ObjectId, Title,
/// Day1, Day2, Day3, Day4, Day5, Day6, Day7, Total, TotalApproved, Rate, Cost, TaskTime
/// </summary>
/// <returns></returns>
public static IDataReader GetListTimeTrackingItemsForFinances(int blockTypeInstanceId, DateTime startDate, int userId)
{
return DbTimeTracking.GetListTimeTrackingItemsForFinances(blockTypeInstanceId, startDate, userId);
}
public static DataTable GetListTimeTrackingItemsForFinances_DataTable(int blockTypeInstanceId, DateTime startDate, int userId)
{
return DbTimeTracking.GetListTimeTrackingItemsForFinances_DataTable(blockTypeInstanceId, startDate, userId);
}
#endregion
#region RegisterFinances
public static void RegisterFinances(TimeTrackingBlock block, string rowId, DateTime regDate)
{
if (!Configuration.TimeTrackingModule)
throw new Mediachase.Ibn.LicenseRestrictionException();
if ((bool)block.Properties["AreFinancesRegistered"].Value)
throw new NotSupportedException("Finances are already registered.");
if (!TimeTrackingBlock.CheckUserRight(block, TimeTrackingManager.Right_RegFinances))
throw new Mediachase.Ibn.AccessDeniedException();
/// TimeTrackingEntryId, UserId, ObjectTypeId, ObjectId, Title,
/// Day1, Day2, Day3, Day4, Day5, Day6, Day7, Total, TotalApproved, Rate, Cost
DataTable dt = GetListTimeTrackingItemsForFinances_DataTable(block.BlockTypeInstanceId, block.StartDate, block.OwnerId);
using (DbTransaction tran = DbTransaction.Begin())
{
// O.R. [2008-07-29]: We don't need to check the "Write" right for Entry and Block
using (SkipSecurityCheckScope scope = Mediachase.Ibn.Data.Services.Security.SkipSecurityCheck())
{
foreach (DataRow row in dt.Rows)
{
// O.R. [2008-07-28]: Rate and TotalApproved may contain null values, so we need do assign them
TimeTrackingEntry entry = MetaObjectActivator.CreateInstance<TimeTrackingEntry>(TimeTrackingEntry.GetAssignedMetaClass(), (int)row["TimeTrackingEntryId"]);
entry.Properties["Rate"].Value = row["Rate"];
entry.Properties["TotalApproved"].Value = row["TotalApproved"];
entry.Save();
double cost = (double)row["Cost"];
if (cost == 0d)
continue;
// O.R. [2008-07-24] Now we use ProjectId
/* ObjectTypes objectType = ObjectTypes.Timesheet;
int objectId = (int)row["TimeTrackingEntryId"];
*/
ObjectTypes objectType = ObjectTypes.Project;
int objectId = block.ProjectId.Value;
if (row["ObjectTypeId"] != DBNull.Value && row["ObjectId"] != DBNull.Value)
{
objectType = (ObjectTypes)row["ObjectTypeId"];
objectId = (int)row["ObjectId"];
}
// row["TotalApproved"] alwas has not null value
ActualFinances.Create(objectId, objectType, regDate, rowId, cost, row["Title"].ToString(), block.PrimaryKeyId.Value, (double)row["TotalApproved"], (int)block.OwnerId);
}
block.Properties["AreFinancesRegistered"].Value = true;
block.Save();
}
// Recalculate TotalMinutes and TotalApproved
RecalculateProjectAndObjects(block);
tran.Commit();
}
}
#endregion
#region UnRegisterFinances
public static void UnRegisterFinances(TimeTrackingBlock block)
{
if (!Configuration.TimeTrackingModule)
throw new Mediachase.Ibn.LicenseRestrictionException();
if (!(bool)block.Properties["AreFinancesRegistered"].Value)
throw new NotSupportedException("Finances are not registered.");
if (!TimeTrackingBlock.CheckUserRight(block, TimeTrackingManager.Right_UnRegFinances))
throw new Mediachase.Ibn.AccessDeniedException();
using (DbTransaction tran = DbTransaction.Begin())
{
ActualFinances.DeleteByBlockId(block.PrimaryKeyId.Value);
// O.R. [2008-07-29]: We don't need to check the "Write" right for Block
using (SkipSecurityCheckScope scope = Mediachase.Ibn.Data.Services.Security.SkipSecurityCheck())
{
block.Properties["AreFinancesRegistered"].Value = false;
block.Save();
}
// Recalculate TotalMinutes and TotalApproved
RecalculateProjectAndObjects(block);
tran.Commit();
}
}
#endregion
#region RecalculateProjectTaskTime
/// <summary>
/// This method calls if the TaskTime value of Event, Task, ToDo, Incident or Document was changed.
/// It also calls after deleting the Event, Task, ToDo, Incident or Document.
/// </summary>
/// <param name="projectId"></param>
public static void RecalculateProjectTaskTime(int projectId)
{
DbTimeTracking.RecalculateProjectTaskTime(projectId);
}
#endregion
#region RecalculateObjectAndProject
/// <summary>
/// Recalculates the object TotalMinutes and TotalApproved.
/// </summary>
/// <param name="objectId">The object id.</param>
/// <param name="objectTypeId">The object type id.</param>
/// <param name="projectId">The project id.</param>
private static void RecalculateObjectAndProject(int? objectId, int? objectTypeId, int projectId)
{
using (DbTransaction tran = DbTransaction.Begin())
{
if (objectId.HasValue && objectTypeId.HasValue)
{
DbTimeTracking.RecalculateObject(objectId.Value, objectTypeId.Value, projectId);
}
if (projectId > 0)
DbTimeTracking.RecalculateProject(projectId);
tran.Commit();
}
}
#endregion
#region RecalculateProjectAndObjects
/// <summary>
/// Recalculates the project and objects TotalMinutes and TotalApproved.
/// </summary>
/// <param name="block">The block.</param>
private static void RecalculateProjectAndObjects(TimeTrackingBlock block)
{
int projectId = GetProjectIdByTimeTrackingBlock(block);
if (projectId > 0)
{
TimeTrackingEntry[] entryList = TimeTrackingEntry.List(
FilterElement.EqualElement("ParentBlockId", block.PrimaryKeyId.Value),
FilterElement.IsNotNullElement("ObjectId"),
FilterElement.IsNotNullElement("ObjectTypeId"));
foreach (TimeTrackingEntry entry in entryList)
{
DbTimeTracking.RecalculateObject((int)entry.Properties["ObjectId"].Value, (int)entry.Properties["ObjectTypeId"].Value, block.ProjectId.Value);
}
DbTimeTracking.RecalculateProject(projectId);
}
}
#endregion
#region GetCurrentAndPrevStateIdByTimeTrackingBlock
private static void GetCurrentAndPrevStateIdByTimeTrackingBlock(TimeTrackingBlock block, out int curStateId, out int prevStateId)
{
curStateId = -1;
prevStateId = -1;
StateMachineService stateMachine = block.GetService<StateMachineService>();
if (stateMachine == null || stateMachine.StateMachine.States.Count == 0 || stateMachine.CurrentState == null)
return;
EventService eventService = block.GetService<EventService>();
if (eventService != null)
{
// Detects that state is changed, find moFromStateName, toStateName
MetaObject[] events = eventService.LoadEvents(TriggerContext.Current.TransactionId);
StateMachineEventServiceArgs args = StateMachine.GetStateChangedEventArgs(events);
if (args != null)
{
curStateId = StateMachineManager.GetState(TimeTrackingBlock.GetAssignedMetaClass(), args.CurrentState.Name).PrimaryKeyId.Value;
prevStateId = StateMachineManager.GetState(TimeTrackingBlock.GetAssignedMetaClass(), args.PrevState.Name).PrimaryKeyId.Value;
}
}
}
#endregion
#region GetFinalStateIdByTimeTrackingBlock
private static int GetFinalStateIdByTimeTrackingBlock(TimeTrackingBlock block)
{
StateMachineService stateMachine = block.GetService<StateMachineService>();
if (stateMachine == null || stateMachine.StateMachine.States.Count == 0)
return -1;
State finalState = stateMachine.StateMachine.States[stateMachine.StateMachine.States.Count - 1];
MetaObject stateObject = StateMachineManager.GetState(TimeTrackingBlock.GetAssignedMetaClass(), finalState.Name);
return stateObject.PrimaryKeyId.Value;
}
#endregion
#region GetProjectIdByTimeTrackingBlock
private static int GetProjectIdByTimeTrackingBlock(TimeTrackingBlock block)
{
return block.Properties["ProjectId"].Value != null ? (int)(PrimaryKeyId)block.Properties["ProjectId"].Value : -1;
//TimeTrackingBlockTypeInstance instance = new TimeTrackingBlockTypeInstance(block.BlockTypeInstanceId);
//return base.Properties["ProjectId"].Value != null ? (int)base.Properties["ProjectId"].Value : -1;
}
#endregion
#region TriggerAction
/// <summary>
/// Recalculates the project TotalMinutes and TotalApproved.
/// </summary>
[TriggerAction("RecalculateProject", "Recalculates project fields by tracking block")]
public static void RecalculateProject()
{
if (TriggerContext.Current == null)
throw new ArgumentException("TriggerContext.Current == null");
TimeTrackingBlock block = TriggerContext.Current.Parameter.MetaObject as TimeTrackingBlock;
if (block == null)
return;
RecalculateProjectAndObjects(block);
}
/// <summary>
/// Recalculates the object TotalMinutes and TotalApproved..
/// </summary>
[TriggerAction("RecalculateObject", "Recalculates object fields by tracking entry")]
public static void RecalculateObject()
{
if (TriggerContext.Current == null)
throw new ArgumentException("TriggerContext.Current == null");
TimeTrackingEntry entry = TriggerContext.Current.Parameter.MetaObject as TimeTrackingEntry;
if (entry == null)
return;
TimeTrackingBlock block = MetaObjectActivator.CreateInstance<TimeTrackingBlock>(TimeTrackingBlock.GetAssignedMetaClass(), entry.ParentBlockId);
int projectId = GetProjectIdByTimeTrackingBlock(block);
//TimeTracking.RecalculateObject(int? objectId, int? objectTypeId, int projectId)
//надо вызывать при создании TimeTrackingEntry (с хотя бы одним ненулевым Day1, Day2..., Day7)
//при изменении TimeTrackingEntry (когда изменился хотя бы один Day1, Day2..., Day7) и
// при удалении TimeTrackingEntry (с хотя бы одним ненулевым Day1, Day2..., Day7)
// Comment conition because can n't detects that all DayX set to zero
if (TriggerContext.Current.Parameter.State == MetaObjectState.Created && (entry.Day1 != 0 || entry.Day2 != 0 || entry.Day3 != 0 ||
entry.Day4 != 0 || entry.Day5 != 0 || entry.Day6 != 0 || entry.Day7 != 0) ||
TriggerContext.Current.Parameter.State != MetaObjectState.Created)
{
RecalculateObjectAndProject(entry.Properties["ObjectId"].GetValue<int?>(),
entry.Properties["ObjectTypeId"].GetValue<int?>(),
projectId);
}
}
public static void RegisterTriggers()
{
TriggerManager.AddTrigger(TimeTrackingBlock.GetAssignedMetaClass(),
new Trigger("RecalculateProjectByTimeTrackingBlock",
"Recalculates project fields by time tracking block", false,false, true, string.Empty, "RecalculateProject"));
TriggerManager.AddTrigger(TimeTrackingEntry.GetAssignedMetaClass(),
new Trigger("RecalculateObjectByTimeTrackingEntry",
"Recalculates project fields by time tracking block", true, true, true, string.Empty, "RecalculateObject"));
}
#endregion
#region GetWeekItemsForUser
/// <summary>
/// Gets the week items for current user.
/// </summary>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <returns></returns>
public static WeekItemInfo[] GetWeekItemsForCurrentUser(DateTime from, DateTime to)
{
return GetWeekItemsForUser(from, to, Security.CurrentUser.UserID);
}
/// <summary>
/// Gets the time tracking block min start date.
/// </summary>
/// <returns></returns>
public static DateTime GetTimeTrackingBlockMinStartDate()
{
return GetTimeTrackingBlockMinStartDate(Security.CurrentUser.UserID);
}
/// <summary>
/// Gets the min start date.
/// </summary>
/// <param name="userId">The user id.</param>
/// <returns></returns>
public static DateTime GetTimeTrackingBlockMinStartDate(int userId)
{
TimeTrackingBlock[] userBlocks = TimeTrackingBlock.List(
new FilterElementCollection(FilterElement.EqualElement("OwnerId", userId)),
new SortingElementCollection(SortingElement.Ascending("StartDate")), 0, 1);
if (userBlocks.Length > 0)
return userBlocks[0].StartDate;
return DateTime.Now.AddDays(-210);
}
/// <summary>
/// Gets the week items for user.
/// </summary>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <param name="userId">The user id.</param>
/// <returns></returns>
public static WeekItemInfo[] GetWeekItemsForUser(DateTime from, DateTime to, int userId)
{
List<WeekItemInfo> retVal = new List<WeekItemInfo>();
// Load User TT blocks
TimeTrackingBlock[] userBlocks = TimeTrackingBlock.List(FilterElement.EqualElement("OwnerId", userId),
new IntervalFilterElement("StartDate", from, to));
// Sort Block By Start Date
Array.Sort<TimeTrackingBlock>(userBlocks, CompareTimeTrackingBlockByStartDate);
// Create Week Item Info list
DateTime currentWeekStart = GetRealWeekStart(from);
// TODO: Current
while (currentWeekStart < to)
{
// Calculate aggregated status of all blocks
WeekItemStatus status = CalculateWeekStatusByBlocks(currentWeekStart, userBlocks);
WeekItemInfo item = new WeekItemInfo(currentWeekStart,
Iso8601WeekNumber.GetWeekNumber(currentWeekStart.AddDays(3)),
status);
CalculateDayTotal(currentWeekStart, item, userBlocks);
retVal.Add(item);
// Go to next week
currentWeekStart = currentWeekStart.AddDays(7);
}
return retVal.ToArray();
}
/// <summary>
/// Compares the time tracking block by start date.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns></returns>
private static int CompareTimeTrackingBlockByStartDate(TimeTrackingBlock x, TimeTrackingBlock y)
{
if (x == null)
throw new ArgumentNullException("x");
if (y == null)
throw new ArgumentNullException("y");
return x.StartDate.CompareTo(y.StartDate);
}
/// <summary>
/// Calculates the week status by blocks.
/// </summary>
/// <param name="currentWeekStart">The current week start.</param>
/// <param name="userBlocks">The user blocks.</param>
/// <returns></returns>
private static WeekItemStatus CalculateWeekStatusByBlocks(DateTime currentWeekStart, TimeTrackingBlock[] userBlocks)
{
DateTime currentWeekEnd = currentWeekStart.AddDays(7);
WeekItemStatus status = WeekItemStatus.NotCompleted;
foreach (TimeTrackingBlock block in userBlocks)
{
// Process if block.StartDate IN [currentWeekStart, currentWeekStart)
if (block.StartDate < currentWeekStart)
continue;
if (block.StartDate >= currentWeekEnd)
break;
if ((bool)block["IsRejected"] && block.mc_State == "Initial")
{
// At least one block rejected
status = WeekItemStatus.Rejected;
break;
}
switch (block.mc_State)
{
case "Initial": // Initial - At least one block not sent to approve
if (status == WeekItemStatus.NotCompleted ||
(int)status > (int)WeekItemStatus.InProcess)
status = WeekItemStatus.InProcess;
break;
case "Final": // Final - All blocks approved
if (status == WeekItemStatus.NotCompleted)
status = WeekItemStatus.Approved;
break;
default:
if (status == WeekItemStatus.NotCompleted ||
(int)status > (int)WeekItemStatus.Submitted)
status = WeekItemStatus.Submitted;
break;
}
}
return status;
}
private static void CalculateDayTotal(DateTime currentWeekStart, WeekItemInfo item, TimeTrackingBlock[] userBlocks)
{
DateTime currentWeekEnd = currentWeekStart.AddDays(7);
foreach (TimeTrackingBlock block in userBlocks)
{
// Process if block.StartDate IN [currentWeekStart, currentWeekStart)
if (block.StartDate < currentWeekStart)
continue;
if (block.StartDate >= currentWeekEnd)
continue;
item.Day1 += block.Day1;
item.Day2 += block.Day2;
item.Day3 += block.Day3;
item.Day4 += block.Day4;
item.Day5 += block.Day5;
item.Day6 += block.Day6;
item.Day7 += block.Day7;
}
}
#endregion
}
}
| 33.2944 | 173 | 0.716036 | [
"MIT"
] | InstantBusinessNetwork/IBN | Source/Server/Business/TimeTracking.cs | 20,924 | C# |
using System;
namespace Decos.Data.Auditing.Tests
{
internal class DummyIdentity : IIdentity
{
public string Id => "5d3a92a3-0849-4617-9e28-484b1f642596";
public string Name => "Test user";
}
} | 20.363636 | 67 | 0.65625 | [
"MIT"
] | DecosInformationSolutions/DbContextAuditing | Decos.Data.Auditing.Tests/DummyIdentity.cs | 226 | C# |
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
using XLugia.Lib.XLog.Lib;
namespace XLugia.Lib.XLog.Base
{
internal class FileController
{
private static FileController _instance = new FileController();
public static FileController getIns() { return _instance; }
public bool isFileExists(string filePath)
{
try
{
return File.Exists(filePath);
}
catch (Exception ex)
{
SimpleLogController.writeErrorLog(ex, "FileController isFileExists");
return false;
}
}
public bool createFile(string filePath, string content)
{
try
{
if (isFileExists(filePath))
{
return false;
}
DirectoryController.getIns().createDirectory(getDirectoryName(filePath));
using (FileStream fs = File.Create(filePath))
{
//byte[] info = new UTF8Encoding(true).GetBytes(content);
//info = Encoding.Convert(Encoding.UTF8, Encoding.Default, info);
byte[] info = System.Text.Encoding.Default.GetBytes(content);
fs.Write(info, 0, info.Length);
fs.Close();
info = null;
}
return true;
}
catch (Exception ex)
{
SimpleLogController.writeErrorLog(ex, "FileController createFile");
return false;
}
}
public bool saveFile(string dirPath, string fileName, string content)
{
try
{
dirPath = DirectoryController.getIns().repairDirPath(dirPath);
return saveFile(dirPath + fileName, content);
}
catch (Exception ex)
{
SimpleLogController.writeErrorLog(ex, "FileController saveFile");
return false;
}
}
public bool saveFile(string filePath, string content)
{
try
{
if (!isFileExists(filePath))
{
return createFile(filePath, content);
}
using (FileStream fs = File.Open(filePath, FileMode.Append))
{
//byte[] info = new UTF8Encoding(true).GetBytes(content);
//info = Encoding.Convert(Encoding.UTF8, Encoding.Default, info);
byte[] info = System.Text.Encoding.Default.GetBytes(content);
fs.Write(info, 0, info.Length);
fs.Close();
info = null;
}
return true;
}
catch (Exception ex)
{
SimpleLogController.writeErrorLog(ex, "FileController saveFile");
return false;
}
}
public string getDirectoryName(string filePath)
{
try
{
return Path.GetDirectoryName(filePath);
}
catch (Exception ex)
{
SimpleLogController.writeErrorLog(ex, "FileController getDirectoryName");
return "";
}
}
}
}
| 31.794643 | 90 | 0.471497 | [
"MIT"
] | Lugia123/XLugia.XLog | Source/XLog/Base/FileController.cs | 3,563 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Ookgewoon.Web.Models.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Ookgewoon.Web.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class LogoutModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LogoutModel> _logger;
public LogoutModel(SignInManager<ApplicationUser> signInManager, ILogger<LogoutModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
public void OnGet()
{
}
public async Task<IActionResult> OnPost(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
if (returnUrl != null)
{
return LocalRedirect(returnUrl);
}
else
{
return RedirectToPage("/Account/Login");
}
}
}
} | 28.227273 | 101 | 0.641707 | [
"MIT"
] | olcay/glowing-argon | CreativeTim.Argon.DotNetCore.Free/Areas/Identity/Pages/Account/Logout.cshtml.cs | 1,244 | C# |
namespace Example1
{
public partial class Schedule
{
/// <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.listEvents = new System.Windows.Forms.ListView();
this.clbTodo = new System.Windows.Forms.CheckedListBox();
this.cbMonth = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// listEvents
//
this.listEvents.Location = new System.Drawing.Point(12, 66);
this.listEvents.Name = "listEvents";
this.listEvents.Size = new System.Drawing.Size(270, 394);
this.listEvents.TabIndex = 1;
this.listEvents.UseCompatibleStateImageBehavior = false;
this.listEvents.View = System.Windows.Forms.View.List;
//
// clbTodo
//
this.clbTodo.FormattingEnabled = true;
this.clbTodo.Location = new System.Drawing.Point(288, 66);
this.clbTodo.Name = "clbTodo";
this.clbTodo.Size = new System.Drawing.Size(262, 394);
this.clbTodo.TabIndex = 2;
//
// cbMonth
//
this.cbMonth.FormattingEnabled = true;
this.cbMonth.Items.AddRange(new object[] {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"});
this.cbMonth.Location = new System.Drawing.Point(12, 19);
this.cbMonth.Name = "cbMonth";
this.cbMonth.Size = new System.Drawing.Size(129, 22);
this.cbMonth.TabIndex = 3;
this.cbMonth.SelectedIndexChanged += new System.EventHandler(this.cbMonth_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 5);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 14);
this.label1.TabIndex = 4;
this.label1.Text = "Choose A Month";
//
// label2
//
this.label2.Font = new System.Drawing.Font("Lucida Sans", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(9, 49);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(273, 14);
this.label2.TabIndex = 4;
this.label2.Text = "This Month\'s Events";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label3
//
this.label3.Font = new System.Drawing.Font("Lucida Sans", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(285, 51);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(266, 14);
this.label3.TabIndex = 4;
this.label3.Text = "This Month\'s Todo List";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// Schedule
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 14F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(563, 472);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.cbMonth);
this.Controls.Add(this.clbTodo);
this.Controls.Add(this.listEvents);
this.Font = new System.Drawing.Font("Lucida Sans", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "Schedule";
this.Text = "Schedule";
this.Load += new System.EventHandler(this.Schedule_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListView listEvents;
private System.Windows.Forms.CheckedListBox clbTodo;
private System.Windows.Forms.ComboBox cbMonth;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
}
}
| 41.601449 | 157 | 0.546943 | [
"BSD-3-Clause"
] | 3rdandUrban-dev/Nuxleus | linux-distro/package/nuxleus/Source/Vendor/dday-ical/Examples/C#/Example1/Schedule.Designer.cs | 5,741 | C# |
static class Guard
{
public static void FileExists(string path, string argumentName)
{
AgainstNullOrEmpty(path, argumentName);
if (!File.Exists(path))
{
throw new ArgumentException($"File not found. Path: {path}", argumentName);
}
}
static char[] invalidFileChars = Path.GetInvalidFileNameChars();
public static void BadFileNameNullable(string? name, string argumentName)
{
if (name is null)
{
return;
}
BadFileName(name, argumentName);
}
public static void BadFileName(string name, string argumentName)
{
AgainstNullOrEmpty(name, argumentName);
foreach (var invalidChar in invalidFileChars)
{
if (name.IndexOf(invalidChar) == -1)
{
continue;
}
throw new ArgumentException($"Invalid character for file name. Value: {name}. Char:{invalidChar}", argumentName);
}
}
static char[] invalidPathChars = Path.GetInvalidPathChars()
.Concat(invalidFileChars.Except(new[] {'/', '\\', ':'}))
.Distinct()
.ToArray();
public static void BadDirectoryName(string? name, string argumentName)
{
if (name is null)
{
return;
}
AgainstEmpty(name, argumentName);
foreach (var invalidChar in invalidPathChars)
{
if (name.IndexOf(invalidChar) == -1)
{
continue;
}
throw new ArgumentException($"Invalid character for directory. Value: {name}. Char:{invalidChar}", argumentName);
}
}
public static void AgainstNullable(Type type, string argumentName)
{
var typeFromNullable = Nullable.GetUnderlyingType(type);
if (typeFromNullable != null)
{
throw new ArgumentException("Nullable types not supported", argumentName);
}
}
public static void AgainstNullOrEmpty(string value, string argumentName)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentNullException(argumentName);
}
}
public static void AgainstBadSourceFile(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentNullException(
"sourceFile",
"This can be caused by using Verify<dynamic>, which is not supported by c#. Instead call use Verify<object>.");
}
}
public static void AgainstEmpty(string? value, string argumentName)
{
if (value is null)
{
return;
}
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentNullException(argumentName);
}
}
public static void AgainstNullOrEmpty(object?[] value, string argumentName)
{
if (value is null)
{
throw new ArgumentNullException(argumentName);
}
if (value.Length == 0)
{
throw new ArgumentNullException(argumentName, "Argument cannot be empty.");
}
}
public static void AgainstNullOrEmpty<T>(T[] value, string argumentName)
{
if (value is null)
{
throw new ArgumentNullException(argumentName);
}
if (value.Length == 0)
{
throw new ArgumentNullException(argumentName, "Argument cannot be empty.");
}
}
public static void AgainstBadExtension(string value, string argumentName)
{
AgainstNullOrEmpty(value, argumentName);
if (value.StartsWith("."))
{
throw new ArgumentException("Must not start with a period ('.').", argumentName);
}
}
} | 28.224638 | 128 | 0.559435 | [
"MIT"
] | distantcam/Verify | src/Verify/Guard.cs | 3,760 | C# |
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceDefinitions.Reading
{
[UsedImplicitly(ImplicitUseTargetFlags.Members)]
public sealed class UniverseDbContext : DbContext
{
public DbSet<Star> Stars => Set<Star>();
public DbSet<Planet> Planets => Set<Planet>();
public DbSet<Moon> Moons => Set<Moon>();
public UniverseDbContext(DbContextOptions<UniverseDbContext> options)
: base(options)
{
}
}
}
| 28.842105 | 77 | 0.689781 | [
"MIT"
] | Anton-Kulinich/JsonApiDotNetCore | test/JsonApiDotNetCoreTests/IntegrationTests/ResourceDefinitions/Reading/UniverseDbContext.cs | 548 | C# |
namespace SoftUni.Data
{
using Microsoft.EntityFrameworkCore;
using SoftUni.Models;
public class SoftUniContext : DbContext
{
public SoftUniContext()
{
}
public SoftUniContext(DbContextOptions<SoftUniContext> options)
: base(options)
{
}
public DbSet<Address> Addresses { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<EmployeeProject> EmployeesProjects { get; set; }
public DbSet<Project> Projects { get; set; }
public DbSet<Town> Towns { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(Configuration.ConnectionString);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.0-rtm-35687");
modelBuilder.Entity<Address>(entity =>
{
entity.HasKey(e => e.AddressId);
entity.Property(e => e.AddressId).HasColumnName("AddressID");
entity.Property(e => e.AddressText)
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.TownId).HasColumnName("TownID");
entity.HasOne(d => d.Town)
.WithMany(p => p.Addresses)
.HasForeignKey(d => d.TownId)
.HasConstraintName("FK_Addresses_Towns");
});
modelBuilder.Entity<Department>(entity =>
{
entity.HasKey(e => e.DepartmentId);
entity.Property(e => e.DepartmentId).HasColumnName("DepartmentID");
entity.Property(e => e.ManagerId).HasColumnName("ManagerID");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
entity.HasOne(d => d.Manager)
.WithMany(p => p.Departments)
.HasForeignKey(d => d.ManagerId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Departments_Employees");
});
modelBuilder.Entity<Employee>(entity =>
{
entity.HasKey(e => e.EmployeeId);
entity.Property(e => e.EmployeeId).HasColumnName("EmployeeID");
entity.Property(e => e.AddressId).HasColumnName("AddressID");
entity.Property(e => e.DepartmentId).HasColumnName("DepartmentID");
entity.Property(e => e.FirstName)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.HireDate).HasColumnType("smalldatetime");
entity.Property(e => e.JobTitle)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.LastName)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.ManagerId).HasColumnName("ManagerID");
entity.Property(e => e.MiddleName)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Salary).HasColumnType("decimal(15, 4)");
entity.HasOne(d => d.Address)
.WithMany(p => p.Employees)
.HasForeignKey(d => d.AddressId)
.HasConstraintName("FK_Employees_Addresses");
entity.HasOne(d => d.Department)
.WithMany(p => p.Employees)
.HasForeignKey(d => d.DepartmentId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Employees_Departments");
entity.HasOne(d => d.Manager)
.WithMany(p => p.InverseManager)
.HasForeignKey(d => d.ManagerId)
.HasConstraintName("FK_Employees_Employees");
});
modelBuilder.Entity<EmployeeProject>(entity =>
{
entity.HasKey(e => new { e.EmployeeId, e.ProjectId });
entity.Property(e => e.EmployeeId).HasColumnName("EmployeeID");
entity.Property(e => e.ProjectId).HasColumnName("ProjectID");
entity.HasOne(d => d.Employee)
.WithMany(p => p.EmployeesProjects)
.HasForeignKey(d => d.EmployeeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_EmployeesProjects_Employees");
entity.HasOne(d => d.Project)
.WithMany(p => p.EmployeesProjects)
.HasForeignKey(d => d.ProjectId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_EmployeesProjects_Projects");
});
modelBuilder.Entity<Project>(entity =>
{
entity.HasKey(e => e.ProjectId);
entity.Property(e => e.ProjectId).HasColumnName("ProjectID");
entity.Property(e => e.Description).HasColumnType("ntext");
entity.Property(e => e.EndDate).HasColumnType("smalldatetime");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.StartDate).HasColumnType("smalldatetime");
});
modelBuilder.Entity<Town>(entity =>
{
entity.HasKey(e => e.TownId);
entity.Property(e => e.TownId).HasColumnName("TownID");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false);
});
}
}
}
| 34.059459 | 85 | 0.508967 | [
"MIT"
] | SonicTheCat/Databases-Advanced---Entity-Framework | 03.IntroductionToEntityFramework/AllExercises/Data/SoftUniContext.cs | 6,303 | C# |
using System;
using UnityEngine;
/**
* Internal Representation of a Tween<br>
* <br>
* This class represents all of the optional parameters you can pass to a method (it also represents the internal representation of the tween).<br><br>
* <strong id='optional'>Optional Parameters</strong> are passed at the end of every method:<br>
* <br>
* <i>Example:</i><br>
* LeanTween.moveX( gameObject, 1f, 1f).setEase( <a href="LeanTweenType.html">LeanTweenType</a>.easeInQuad ).setDelay(1f);<br>
* <br>
* You can pass the optional parameters in any order, and chain on as many as you wish.<br>
* You can also <strong>pass parameters at a later time</strong> by saving a reference to what is returned.<br>
* <br>
* Retrieve a <strong>unique id</strong> for the tween by using the "id" property. You can pass this to LeanTween.pause, LeanTween.resume, LeanTween.cancel, LeanTween.isTweening methods<br>
* <br>
* <h4>Example:</h4>
* int id = LeanTween.moveX(gameObject, 1f, 3f).id;<br>
* <div style="color:gray"> // pause a specific tween</div>
* LeanTween.pause(id);<br>
* <div style="color:gray"> // resume later</div>
* LeanTween.resume(id);<br>
* <div style="color:gray"> // check if it is tweening before kicking of a new tween</div>
* if( LeanTween.isTweening( id ) ){<br>
* LeanTween.cancel( id );<br>
* LeanTween.moveZ(gameObject, 10f, 3f);<br>
* }<br>
* @class LTDescr
* @constructor
*/
public class LTDescr
{
public bool toggle;
public bool useEstimatedTime;
public bool useFrames;
public bool useManualTime;
public bool usesNormalDt;
public bool hasInitiliazed;
public bool hasExtraOnCompletes;
public bool hasPhysics;
public bool onCompleteOnRepeat;
public bool onCompleteOnStart;
public bool useRecursion;
public float ratioPassed;
public float passed;
public float delay;
public float time;
public float speed;
public float lastVal;
private uint _id;
public int loopCount;
public uint counter;
public float direction;
public float directionLast;
public float overshoot;
public float period;
public float scale;
public bool destroyOnComplete;
public Transform trans;
public LTRect ltRect;
internal Vector3 fromInternal;
public Vector3 from { get { return this.fromInternal; } set { this.fromInternal = value; } }
internal Vector3 toInternal;
public Vector3 to { get { return this.toInternal; } set { this.toInternal = value; } }
internal Vector3 diff;
internal Vector3 diffDiv2;
public TweenAction type;
public LeanTweenType tweenType;
public LeanTweenType loopType;
public bool hasUpdateCallback;
public EaseTypeDelegate easeMethod;
public ActionMethodDelegate easeInternal {get; set; }
public ActionMethodDelegate initInternal {get; set; }
public delegate Vector3 EaseTypeDelegate();
public delegate void ActionMethodDelegate();
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2
public SpriteRenderer spriteRen;
#endif
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5
public RectTransform rectTransform;
public UnityEngine.UI.Text uiText;
public UnityEngine.UI.Image uiImage;
public UnityEngine.Sprite[] sprites;
#endif
public LTDescrOptional _optional = new LTDescrOptional();
private static uint global_counter = 0;
public override string ToString(){
return (trans!=null ? "name:"+trans.gameObject.name : "gameObject:null")+" toggle:"+toggle+" passed:"+passed+" time:"+time+" delay:"+delay+" direction:"+direction+" from:"+from+" to:"+to+" diff:"+diff+" type:"+type+" ease:"+tweenType+" useEstimatedTime:"+useEstimatedTime+" id:"+id+" hasInitiliazed:"+hasInitiliazed;
}
public LTDescr(){
}
[System.Obsolete("Use 'LeanTween.cancel( id )' instead")]
public LTDescr cancel( GameObject gameObject ){
// Debug.Log("canceling id:"+this._id+" this.uniqueId:"+this.uniqueId+" go:"+this.trans.gameObject);
if(gameObject==this.trans.gameObject)
LeanTween.removeTween((int)this._id, this.uniqueId);
return this;
}
public int uniqueId{
get{
uint toId = _id | counter << 16;
/*uint backId = toId & 0xFFFF;
uint backCounter = toId >> 16;
if(_id!=backId || backCounter!=counter){
Debug.LogError("BAD CONVERSION toId:"+_id);
}*/
return (int)toId;
}
}
public int id{
get{
return uniqueId;
}
}
public LTDescrOptional optional{
get{
return _optional;
}
set{
this._optional = optional;
}
}
public void reset(){
this.toggle = this.useRecursion = this.usesNormalDt = true;
this.trans = null;
this.passed = this.delay = this.lastVal = 0.0f;
this.hasUpdateCallback = this.useEstimatedTime = this.useFrames = this.hasInitiliazed = this.onCompleteOnRepeat = this.destroyOnComplete = this.onCompleteOnStart = this.useManualTime = this.hasExtraOnCompletes = false;
this.tweenType = LeanTweenType.linear;
this.loopType = LeanTweenType.once;
this.loopCount = 0;
this.direction = this.directionLast = this.overshoot = this.scale = 1.0f;
this.period = 0.3f;
this.speed = -1f;
this.easeMethod = this.easeLinear;
this._optional.reset();
global_counter++;
if(global_counter>0x8000)
global_counter = 0;
}
// Initialize and Internal Methods
public LTDescr setMoveX(){
this.type = TweenAction.MOVE_X;
this.initInternal = ()=>{ this.fromInternal.x = trans.position.x; };
this.easeInternal = ()=>{ trans.position=new Vector3( easeMethod().x,trans.position.y,trans.position.z); };
return this;
}
public LTDescr setMoveY(){
this.type = TweenAction.MOVE_Y;
this.initInternal = ()=>{ this.fromInternal.x = trans.position.y; };
this.easeInternal = ()=>{ trans.position=new Vector3( trans.position.x,easeMethod().x,trans.position.z); };
return this;
}
public LTDescr setMoveZ(){
this.type = TweenAction.MOVE_Z;
this.initInternal = ()=>{ this.fromInternal.x = trans.position.z; };;
this.easeInternal = ()=>{ trans.position=new Vector3( trans.position.x,trans.position.y,easeMethod().x); };
return this;
}
public LTDescr setMoveLocalX(){
this.type = TweenAction.MOVE_LOCAL_X;
this.initInternal = ()=>{ this.fromInternal.x = trans.localPosition.x; };
this.easeInternal = ()=>{ trans.localPosition=new Vector3( easeMethod().x,trans.localPosition.y,trans.localPosition.z); };
return this;
}
public LTDescr setMoveLocalY(){
this.type = TweenAction.MOVE_LOCAL_Y;
this.initInternal = ()=>{ this.fromInternal.x = trans.localPosition.y; };
this.easeInternal = ()=>{ trans.localPosition=new Vector3( trans.localPosition.x,easeMethod().x,trans.localPosition.z); };
return this;
}
public LTDescr setMoveLocalZ(){
this.type = TweenAction.MOVE_LOCAL_Z;
this.initInternal = ()=>{ this.fromInternal.x = trans.localPosition.z; };
this.easeInternal = ()=>{ trans.localPosition=new Vector3( trans.localPosition.x,trans.localPosition.y,easeMethod().x); };
return this;
}
private void initFromInternal(){ this.fromInternal.x = 0; }
public LTDescr setMoveCurved(){
this.type = TweenAction.MOVE_CURVED;
this.initInternal = this.initFromInternal;
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
if(this._optional.path.orientToPath){
if(this._optional.path.orientToPath2d){
this._optional.path.place2d( trans, val );
}else{
this._optional.path.place( trans, val );
}
}else{
trans.position = this._optional.path.point( val );
}
};
return this;
}
public LTDescr setMoveCurvedLocal(){
this.type = TweenAction.MOVE_CURVED_LOCAL;
this.initInternal = this.initFromInternal;
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
if(this._optional.path.orientToPath){
if(this._optional.path.orientToPath2d){
this._optional.path.placeLocal2d( trans, val );
}else{
this._optional.path.placeLocal( trans, val );
}
}else{
trans.localPosition = this._optional.path.point( val );
}
};
return this;
}
public LTDescr setMoveSpline(){
this.type = TweenAction.MOVE_SPLINE;
this.initInternal = this.initFromInternal;
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
if(this._optional.spline.orientToPath){
if(this._optional.spline.orientToPath2d){
this._optional.spline.place2d( trans, val );
}else{
this._optional.spline.place( trans, val );
}
}else{
trans.position = this._optional.spline.point( val );
}
};
return this;
}
public LTDescr setMoveSplineLocal(){
this.type = TweenAction.MOVE_SPLINE_LOCAL;
this.initInternal = this.initFromInternal;
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
if(this._optional.spline.orientToPath){
if(this._optional.spline.orientToPath2d){
this._optional.spline.placeLocal2d( trans, val );
}else{
this._optional.spline.placeLocal( trans, val );
}
}else{
trans.localPosition = this._optional.spline.point( val );
}
};
return this;
}
public LTDescr setScaleX(){
this.type = TweenAction.SCALE_X;
this.initInternal = ()=>{ this.fromInternal.x = trans.localScale.x; };
this.easeInternal = ()=>{ trans.localScale = new Vector3( easeMethod().x,trans.localScale.y,trans.localScale.z); };
return this;
}
public LTDescr setScaleY(){
this.type = TweenAction.SCALE_Y;
this.initInternal = ()=>{ this.fromInternal.x = trans.localScale.y; };
this.easeInternal = ()=>{ trans.localScale=new Vector3( trans.localScale.x,easeMethod().x,trans.localScale.z); };
return this;
}
public LTDescr setScaleZ(){
this.type = TweenAction.SCALE_Z;
this.initInternal = ()=>{ this.fromInternal.x = trans.localScale.z; };
this.easeInternal = ()=>{ trans.localScale=new Vector3( trans.localScale.x,trans.localScale.y,easeMethod().x); };
return this;
}
public LTDescr setRotateX(){
this.type = TweenAction.ROTATE_X;
this.initInternal = ()=>{ this.fromInternal.x = trans.eulerAngles.x; this.toInternal.x = LeanTween.closestRot( this.fromInternal.x, this.toInternal.x);};
this.easeInternal = ()=>{ trans.eulerAngles=new Vector3(easeMethod().x,trans.eulerAngles.y,trans.eulerAngles.z); };
return this;
}
public LTDescr setRotateY(){
this.type = TweenAction.ROTATE_Y;
this.initInternal = ()=>{ this.fromInternal.x = trans.eulerAngles.y; this.toInternal.x = LeanTween.closestRot( this.fromInternal.x, this.toInternal.x);};
this.easeInternal = ()=>{ trans.eulerAngles=new Vector3(trans.eulerAngles.x,easeMethod().x,trans.eulerAngles.z); };
return this;
}
public LTDescr setRotateZ(){
this.type = TweenAction.ROTATE_Z;
this.initInternal = ()=>{
this.fromInternal.x = trans.eulerAngles.z;
this.toInternal.x = LeanTween.closestRot( this.fromInternal.x, this.toInternal.x);
};
this.easeInternal = ()=>{ trans.eulerAngles=new Vector3(trans.eulerAngles.x,trans.eulerAngles.y,easeMethod().x); };
return this;
}
public LTDescr setRotateAround(){
this.type = TweenAction.ROTATE_AROUND;
this.initInternal = ()=>{
this.fromInternal.x = 0f;
this._optional.origRotation = trans.rotation;
};
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
Vector3 origPos = trans.localPosition;
Vector3 rotateAroundPt = (Vector3)trans.TransformPoint( this._optional.point );
// Debug.Log("this._optional.point:"+this._optional.point);
trans.RotateAround(rotateAroundPt, this._optional.axis, -this._optional.lastVal);
Vector3 diff = origPos - trans.localPosition;
trans.localPosition = origPos - diff; // Subtract the amount the object has been shifted over by the rotate, to get it back to it's orginal position
trans.rotation = this._optional.origRotation;
rotateAroundPt = (Vector3)trans.TransformPoint( this._optional.point );
trans.RotateAround(rotateAroundPt, this._optional.axis, val);
this._optional.lastVal = val;
};
return this;
}
public LTDescr setRotateAroundLocal(){
this.type = TweenAction.ROTATE_AROUND_LOCAL;
this.initInternal = ()=>{
this.fromInternal.x = 0f;
this._optional.origRotation = trans.localRotation;
};
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
Vector3 origPos = trans.localPosition;
trans.RotateAround((Vector3)trans.TransformPoint( this._optional.point ), trans.TransformDirection(this._optional.axis), -this._optional.lastVal);
Vector3 diff = origPos - trans.localPosition;
trans.localPosition = origPos - diff; // Subtract the amount the object has been shifted over by the rotate, to get it back to it's orginal position
trans.localRotation = this._optional.origRotation;
Vector3 rotateAroundPt = (Vector3)trans.TransformPoint( this._optional.point );
trans.RotateAround(rotateAroundPt, trans.TransformDirection(this._optional.axis), val);
this._optional.lastVal = val;
};
return this;
}
public LTDescr setAlpha(){
this.type = TweenAction.ALPHA;
this.initInternal = ()=>{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
if(trans.gameObject.renderer){ this.fromInternal.x = trans.gameObject.renderer.material.color.a; }else if(trans.childCount>0){ foreach (Transform child in trans) { if(child.gameObject.renderer!=null){ Color col = child.gameObject.renderer.material.color; this.fromInternal.x = col.a; break; }}}
this.easeInternal = this.alpha;
break;
#else
SpriteRenderer ren = trans.gameObject.GetComponent<SpriteRenderer>();
if(ren!=null){
this.fromInternal.x = ren.color.a;
}else{
if(trans.gameObject.GetComponent<Renderer>()!=null && trans.gameObject.GetComponent<Renderer>().material.HasProperty("_Color")){
this.fromInternal.x = trans.gameObject.GetComponent<Renderer>().material.color.a;
}else if(trans.gameObject.GetComponent<Renderer>()!=null && trans.gameObject.GetComponent<Renderer>().material.HasProperty("_TintColor")){
Color col = trans.gameObject.GetComponent<Renderer>().material.GetColor("_TintColor");
this.fromInternal.x = col.a;
}else if(trans.childCount>0){
foreach (Transform child in trans) {
if(child.gameObject.GetComponent<Renderer>()!=null){
Color col = child.gameObject.GetComponent<Renderer>().material.color;
this.fromInternal.x = col.a;
break;
}
}
}
}
#endif
this.easeInternal = ()=>{
val = easeMethod().x;
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
alphaRecursive(this.trans, val, this.useRecursion);
#else
if(this.spriteRen!=null){
this.spriteRen.color = new Color( this.spriteRen.color.r, this.spriteRen.color.g, this.spriteRen.color.b, val);
alphaRecursiveSprite(this.trans, val);
}else{
alphaRecursive(this.trans, val, this.useRecursion);
}
#endif
};
};
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
alphaRecursive(this.trans, val, this.useRecursion);
#else
if(this.spriteRen!=null){
this.spriteRen.color = new Color( this.spriteRen.color.r, this.spriteRen.color.g, this.spriteRen.color.b, val);
alphaRecursiveSprite(this.trans, val);
}else{
alphaRecursive(this.trans, val, this.useRecursion);
}
#endif
};
return this;
}
public LTDescr setTextAlpha(){
this.type = TweenAction.TEXT_ALPHA;
this.initInternal = ()=>{
this.uiText = trans.gameObject.GetComponent<UnityEngine.UI.Text>();
this.fromInternal.x = this.uiText != null ? this.uiText.color.a : 1f;
};
this.easeInternal = ()=>{ textAlphaRecursive( trans, easeMethod().x, this.useRecursion ); };
return this;
}
public LTDescr setAlphaVertex(){
this.type = TweenAction.ALPHA_VERTEX;
this.initInternal = ()=>{ this.fromInternal.x = trans.GetComponent<MeshFilter>().mesh.colors32[0].a; };
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
Mesh mesh = trans.GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
Color32[] colors = new Color32[vertices.Length];
if (colors.Length == 0){ //MaxFW fix: add vertex colors if the mesh doesn't have any
Color32 transparentWhiteColor32 = new Color32(0xff, 0xff, 0xff, 0x00);
colors = new Color32[mesh.vertices.Length];
for (int k=0; k<colors.Length; k++)
colors[k] = transparentWhiteColor32;
mesh.colors32 = colors;
}// fix end
Color32 c = mesh.colors32[0];
c = new Color( c.r, c.g, c.b, val);
for (int k= 0; k < vertices.Length; k++)
colors[k] = c;
mesh.colors32 = colors;
};
return this;
}
public LTDescr setColor(){
this.type = TweenAction.COLOR;
this.initInternal = ()=>{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
if(trans.gameObject.renderer){
this.setFromColor( trans.gameObject.renderer.material.color );
}else if(trans.childCount>0){
foreach (Transform child in trans) {
if(child.gameObject.renderer!=null){
this.setFromColor( child.gameObject.renderer.material.color );
break;
}
}
}
#else
SpriteRenderer renColor = trans.gameObject.GetComponent<SpriteRenderer>();
if(renColor!=null){
this.setFromColor( renColor.color );
}else{
if(trans.gameObject.GetComponent<Renderer>()!=null && trans.gameObject.GetComponent<Renderer>().material.HasProperty("_Color")){
Color col = trans.gameObject.GetComponent<Renderer>().material.color;
this.setFromColor( col );
}else if(trans.gameObject.GetComponent<Renderer>()!=null && trans.gameObject.GetComponent<Renderer>().material.HasProperty("_TintColor")){
Color col = trans.gameObject.GetComponent<Renderer>().material.GetColor ("_TintColor");
this.setFromColor( col );
}else if(trans.childCount>0){
foreach (Transform child in trans) {
if(child.gameObject.GetComponent<Renderer>()!=null){
Color col = child.gameObject.GetComponent<Renderer>().material.color;
this.setFromColor( col );
break;
}
}
}
}
#endif
};
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
Color toColor = tweenColor(this, val);
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2
if(this.spriteRen!=null){
this.spriteRen.color = toColor;
colorRecursiveSprite( trans, toColor);
}else{
#endif
// Debug.Log("val:"+val+" tween:"+tween+" tween.diff:"+tween.diff);
if(this.type==TweenAction.COLOR)
colorRecursive(trans, toColor, this.useRecursion);
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2
}
#endif
if(dt!=0f && this._optional.onUpdateColor!=null){
this._optional.onUpdateColor(toColor);
}else if(dt!=0f && this._optional.onUpdateColorObject!=null){
this._optional.onUpdateColorObject(toColor, this._optional.onUpdateParam);
}
};
return this;
}
public LTDescr setCallbackColor(){
this.type = TweenAction.CALLBACK_COLOR;
this.initInternal = ()=>{ this.diff = new Vector3(1.0f,0.0f,0.0f); };
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
Color toColor = tweenColor(this, val);
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2
if(this.spriteRen!=null){
this.spriteRen.color = toColor;
colorRecursiveSprite( trans, toColor);
}else{
#endif
// Debug.Log("val:"+val+" tween:"+tween+" tween.diff:"+tween.diff);
if(this.type==TweenAction.COLOR)
colorRecursive(trans, toColor, this.useRecursion);
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2
}
#endif
if(dt!=0f && this._optional.onUpdateColor!=null){
this._optional.onUpdateColor(toColor);
}else if(dt!=0f && this._optional.onUpdateColorObject!=null){
this._optional.onUpdateColorObject(toColor, this._optional.onUpdateParam);
}
};
return this;
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5
public LTDescr setTextColor(){
this.type = TweenAction.TEXT_COLOR;
this.initInternal = ()=>{
this.uiText = trans.gameObject.GetComponent<UnityEngine.UI.Text>();
this.setFromColor( this.uiText != null ? this.uiText.color : Color.white );
};
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
Color toColor = tweenColor(this, val);
this.uiText.color = toColor;
if (dt!=0f && this._optional.onUpdateColor != null)
this._optional.onUpdateColor(toColor);
if(this.useRecursion && trans.childCount>0)
textColorRecursive(this.trans, toColor);
};
return this;
}
public LTDescr setCanvasAlpha(){
this.type = TweenAction.CANVAS_ALPHA;
this.initInternal = ()=>{
this.uiImage = trans.gameObject.GetComponent<UnityEngine.UI.Image>();
this.fromInternal.x = this.uiImage != null ? this.uiImage.color.a : 1f;
};
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
if(this.uiImage!=null){
Color c = this.uiImage.color; c.a = val; this.uiImage.color = c;
}
if(this.useRecursion){
alphaRecursive( this.rectTransform, val, 0 );
textAlphaRecursive( this.rectTransform, val);
}
};
return this;
}
public LTDescr setCanvasGroupAlpha(){
this.type = TweenAction.CANVASGROUP_ALPHA;
this.initInternal = ()=>{this.fromInternal.x = trans.gameObject.GetComponent<CanvasGroup>().alpha;};
this.easeInternal = ()=>{ this.trans.GetComponent<CanvasGroup>().alpha = easeMethod().x; };
return this;
}
public LTDescr setCanvasColor(){
this.type = TweenAction.CANVAS_COLOR;
this.initInternal = ()=>{
this.uiImage = trans.gameObject.GetComponent<UnityEngine.UI.Image>();
if(this.uiImage != null){
this.setFromColor( this.uiImage.color );
}else{
this.setFromColor( Color.white );
}
};
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
Color toColor = tweenColor(this, val);
this.uiImage.color = toColor;
if (dt!=0f && this._optional.onUpdateColor != null)
this._optional.onUpdateColor(toColor);
if(this.useRecursion)
colorRecursive(this.rectTransform, toColor);
};
return this;
}
public LTDescr setCanvasMoveX(){
this.type = TweenAction.CANVAS_MOVE_X;
this.initInternal = ()=>{ this.fromInternal.x = this.rectTransform.anchoredPosition3D.x; };
this.easeInternal = ()=>{ Vector3 c = this.rectTransform.anchoredPosition3D; this.rectTransform.anchoredPosition3D = new Vector3(easeMethod().x, c.y, c.z); };
return this;
}
public LTDescr setCanvasMoveY(){
this.type = TweenAction.CANVAS_MOVE_Y;
this.initInternal = ()=>{ this.fromInternal.x = this.rectTransform.anchoredPosition3D.y; };
this.easeInternal = ()=>{ Vector3 c = this.rectTransform.anchoredPosition3D; this.rectTransform.anchoredPosition3D = new Vector3(c.x, easeMethod().x, c.z); };
return this;
}
public LTDescr setCanvasMoveZ(){
this.type = TweenAction.CANVAS_MOVE_Z;
this.initInternal = ()=>{ this.fromInternal.x = this.rectTransform.anchoredPosition3D.z; };
this.easeInternal = ()=>{ Vector3 c = this.rectTransform.anchoredPosition3D; this.rectTransform.anchoredPosition3D = new Vector3(c.x, c.y, easeMethod().x); };
return this;
}
private void initCanvasRotateAround(){
this.lastVal = 0.0f;
this.fromInternal.x = 0.0f;
this._optional.origRotation = this.rectTransform.rotation;
}
public LTDescr setCanvasRotateAround(){
this.type = TweenAction.CANVAS_ROTATEAROUND;
this.initInternal = this.initCanvasRotateAround;
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
RectTransform rect = this.rectTransform;
Vector3 origPos = rect.localPosition;
rect.RotateAround((Vector3)rect.TransformPoint( this._optional.point ), this._optional.axis, -val);
Vector3 diff = origPos - rect.localPosition;
rect.localPosition = origPos - diff; // Subtract the amount the object has been shifted over by the rotate, to get it back to it's orginal position
rect.rotation = this._optional.origRotation;
rect.RotateAround((Vector3)rect.TransformPoint( this._optional.point ), this._optional.axis, val);
};
return this;
}
public LTDescr setCanvasRotateAroundLocal(){
this.type = TweenAction.CANVAS_ROTATEAROUND_LOCAL;
this.initInternal = this.initCanvasRotateAround;
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
RectTransform rect = this.rectTransform;
Vector3 origPos = rect.localPosition;
rect.RotateAround((Vector3)rect.TransformPoint( this._optional.point ), rect.TransformDirection(this._optional.axis), -val);
Vector3 diff = origPos - rect.localPosition;
rect.localPosition = origPos - diff; // Subtract the amount the object has been shifted over by the rotate, to get it back to it's orginal position
rect.rotation = this._optional.origRotation;
rect.RotateAround((Vector3)rect.TransformPoint( this._optional.point ), rect.TransformDirection(this._optional.axis), val);
};
return this;
}
public LTDescr setCanvasPlaySprite(){
this.type = TweenAction.CANVAS_PLAYSPRITE;
this.initInternal = ()=>{
this.uiImage = trans.gameObject.GetComponent<UnityEngine.UI.Image>();
this.fromInternal.x = 0f;
};
this.easeInternal = ()=>{
newVect = easeMethod();
val = newVect.x;
int frame = (int)Mathf.Round( val );
this.uiImage.sprite = this.sprites[ frame ];
};
return this;
}
public LTDescr setCanvasMove(){
this.type = TweenAction.CANVAS_MOVE;
this.initInternal = ()=>{ this.fromInternal = this.rectTransform.anchoredPosition3D; };
this.easeInternal = ()=>{ this.rectTransform.anchoredPosition3D = easeMethod(); };
return this;
}
public LTDescr setCanvasScale(){
this.type = TweenAction.CANVAS_SCALE;
this.initInternal = ()=>{ this.from = this.rectTransform.localScale; };
this.easeInternal = ()=>{ this.rectTransform.localScale = easeMethod(); };
return this;
}
public LTDescr setCanvasSizeDelta(){
this.type = TweenAction.CANVAS_SIZEDELTA;
this.initInternal = ()=>{ this.from = this.rectTransform.sizeDelta; };
this.easeInternal = ()=>{ this.rectTransform.sizeDelta = easeMethod(); };
return this;
}
#endif
private void callback(){ newVect = easeMethod(); val = newVect.x; }
public LTDescr setCallback(){
this.type = TweenAction.CALLBACK;
this.initInternal = ()=>{};
this.easeInternal = this.callback;
return this;
}
public LTDescr setValue3(){
this.type = TweenAction.VALUE3;
this.initInternal = ()=>{};
this.easeInternal = this.callback;
return this;
}
public LTDescr setMove(){
this.type = TweenAction.MOVE;
this.initInternal = ()=>{ this.from = trans.position; };
this.easeInternal = ()=>{
newVect = easeMethod();
trans.position = newVect;
};
return this;
}
public LTDescr setMoveLocal(){
this.type = TweenAction.MOVE_LOCAL;
this.initInternal = ()=>{ this.from = trans.localPosition; };
this.easeInternal = ()=>{
newVect = easeMethod();
trans.localPosition = newVect;
};
return this;
}
public LTDescr setMoveToTransform(){
this.type = TweenAction.MOVE_TO_TRANSFORM;
this.initInternal = ()=>{ this.from = trans.position; };
this.easeInternal = ()=>{
this.to = this._optional.toTrans.position;
this.diff = this.to - this.from;
this.diffDiv2 = this.diff * 0.5f;
newVect = easeMethod();
this.trans.position = newVect;
};
return this;
}
public LTDescr setRotate(){
this.type = TweenAction.ROTATE;
this.initInternal = ()=>{ this.from = trans.eulerAngles; this.to = new Vector3(LeanTween.closestRot( this.fromInternal.x, this.toInternal.x), LeanTween.closestRot( this.from.y, this.to.y), LeanTween.closestRot( this.from.z, this.to.z)); };
this.easeInternal = ()=>{
newVect = easeMethod();
trans.eulerAngles = newVect;
};
return this;
}
public LTDescr setRotateLocal(){
this.type = TweenAction.ROTATE_LOCAL;
this.initInternal = ()=>{ this.from = trans.localEulerAngles; this.to = new Vector3(LeanTween.closestRot( this.fromInternal.x, this.toInternal.x), LeanTween.closestRot( this.from.y, this.to.y), LeanTween.closestRot( this.from.z, this.to.z)); };
this.easeInternal = ()=>{
newVect = easeMethod();
trans.localEulerAngles = newVect;
};
return this;
}
public LTDescr setScale(){
this.type = TweenAction.SCALE;
this.initInternal = ()=>{ this.from = trans.localScale; };
this.easeInternal = ()=>{
newVect = easeMethod();
trans.localScale = newVect;
};
return this;
}
public LTDescr setGUIMove(){
this.type = TweenAction.GUI_MOVE;
this.initInternal = ()=>{ this.from = new Vector3(this._optional.ltRect.rect.x, this._optional.ltRect.rect.y, 0); };
this.easeInternal = ()=>{ Vector3 v = easeMethod(); this._optional.ltRect.rect = new Rect( v.x, v.y, this._optional.ltRect.rect.width, this._optional.ltRect.rect.height); };
return this;
}
public LTDescr setGUIMoveMargin(){
this.type = TweenAction.GUI_MOVE_MARGIN;
this.initInternal = ()=>{ this.from = new Vector2(this._optional.ltRect.margin.x, this._optional.ltRect.margin.y); };
this.easeInternal = ()=>{ Vector3 v = easeMethod(); this._optional.ltRect.margin = new Vector2(v.x, v.y); };
return this;
}
public LTDescr setGUIScale(){
this.type = TweenAction.GUI_SCALE;
this.initInternal = ()=>{ this.from = new Vector3(this._optional.ltRect.rect.width, this._optional.ltRect.rect.height, 0); };
this.easeInternal = ()=>{ Vector3 v = easeMethod(); this._optional.ltRect.rect = new Rect( this._optional.ltRect.rect.x, this._optional.ltRect.rect.y, v.x, v.y); };
return this;
}
public LTDescr setGUIAlpha(){
this.type = TweenAction.GUI_ALPHA;
this.initInternal = ()=>{ this.fromInternal.x = this._optional.ltRect.alpha; };
this.easeInternal = ()=>{ this._optional.ltRect.alpha = easeMethod().x; };
return this;
}
public LTDescr setGUIRotate(){
this.type = TweenAction.GUI_ROTATE;
this.initInternal = ()=>{ if(this._optional.ltRect.rotateEnabled==false){
this._optional.ltRect.rotateEnabled = true;
this._optional.ltRect.resetForRotation();
}
this.fromInternal.x = this._optional.ltRect.rotation;
};
this.easeInternal = ()=>{ this._optional.ltRect.rotation = easeMethod().x; };
return this;
}
public LTDescr setDelayedSound(){
this.type = TweenAction.DELAYED_SOUND;
this.initInternal = ()=>{ this.hasExtraOnCompletes = true; };
this.easeInternal = this.callback;
return this;
}
private void init(){
this.hasInitiliazed = true;
usesNormalDt = !(useEstimatedTime || useManualTime || useFrames); // only set this to true if it uses non of the other timing modes
if (this.time <= 0f) // avoid dividing by zero
this.time = Mathf.Epsilon;
this.initInternal();
this.diff = this.to - this.from;
this.diffDiv2 = this.diff * 0.5f;
if (this._optional.onStart != null)
this._optional.onStart();
if(this.onCompleteOnStart)
callOnCompletes();
if(this.speed>=0){
initSpeed();
}
}
private void initSpeed(){
if(this.type==TweenAction.MOVE_CURVED || this.type==TweenAction.MOVE_CURVED_LOCAL){
this.time = this._optional.path.distance / this.speed;
}else if(this.type==TweenAction.MOVE_SPLINE || this.type==TweenAction.MOVE_SPLINE_LOCAL){
this.time = this._optional.spline.distance/ this.speed;
}else{
this.time = (this.to - this.from).magnitude / this.speed;
}
}
public static float val;
public static float dt;
public static Vector3 newVect;
/**
* If you need a tween to happen immediately instead of waiting for the next Update call, you can force it with this method
*
* @method updateNow
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 0f ).updateNow();
*/
public LTDescr updateNow(){
updateInternal();
return this;
}
public bool updateInternal(){
float directionLocal = this.direction;
if(usesNormalDt){
dt = LeanTween.dtActual;
}else if( this.useEstimatedTime ){
dt = LeanTween.dtEstimated;
}else if( this.useFrames ){
dt = 1;
}else if( this.useManualTime ){
dt = LeanTween.dtManual;
}
if(this.delay<=0f && directionLocal!=0f){
if(trans==null)
return true;
// initialize if has not done so yet
if(!this.hasInitiliazed)
this.init();
dt = dt*directionLocal;
this.passed += dt;
this.ratioPassed = Mathf.Clamp01(this.passed / this.time); // need to clamp when finished so it will finish at the exact spot and not overshoot
this.easeInternal();
if(this.hasUpdateCallback)
this._optional.callOnUpdate(val, this.ratioPassed);
bool isTweenFinished = directionLocal>0f ? this.passed>=this.time : this.passed<=0f;
// Debug.Log("lt "+this+" dt:"+dt+" fin:"+isTweenFinished);
if(isTweenFinished){ // increment or flip tween
this.loopCount--;
if(this.loopType==LeanTweenType.pingPong){
this.direction = 0.0f-directionLocal;
}else{
this.passed = Mathf.Epsilon;
}
isTweenFinished = this.loopCount == 0 || this.loopType == LeanTweenType.once; // only return true if it is fully complete
if(isTweenFinished==false && this.onCompleteOnRepeat && this.hasExtraOnCompletes)
callOnCompletes(); // this only gets called if onCompleteOnRepeat is set to true, otherwise LeanTween class takes care of calling it
return isTweenFinished;
}
}else{
this.delay -= dt;
}
return false;
}
public void callOnCompletes(){
if(this.type==TweenAction.GUI_ROTATE)
this._optional.ltRect.rotateFinished = true;
if(this.type==TweenAction.DELAYED_SOUND){
AudioSource.PlayClipAtPoint((AudioClip)this._optional.onCompleteParam, this.to, this.from.x);
}
if(this._optional.onComplete!=null){
this._optional.onComplete();
}else if(this._optional.onCompleteObject!=null){
this._optional.onCompleteObject(this._optional.onCompleteParam);
}
}
// Helper Methods
public LTDescr setFromColor( Color col ){
this.from = new Vector3(0.0f, col.a, 0.0f);
this.diff = new Vector3(1.0f,0.0f,0.0f);
this._optional.axis = new Vector3( col.r, col.g, col.b );
return this;
}
private static void alphaRecursive( Transform transform, float val, bool useRecursion = true){
Renderer renderer = transform.gameObject.GetComponent<Renderer>();
if(renderer!=null){
foreach(Material mat in renderer.materials){
if(mat.HasProperty("_Color")){
mat.color = new Color( mat.color.r, mat.color.g, mat.color.b, val);
}else if(mat.HasProperty("_TintColor")){
Color col = mat.GetColor ("_TintColor");
mat.SetColor("_TintColor", new Color( col.r, col.g, col.b, val));
}
}
}
if(useRecursion && transform.childCount>0){
foreach (Transform child in transform) {
alphaRecursive(child, val);
}
}
}
private static void colorRecursive( Transform transform, Color toColor, bool useRecursion = true ){
Renderer ren = transform.gameObject.GetComponent<Renderer>();
if(ren!=null){
foreach(Material mat in ren.materials){
mat.color = toColor;
}
}
if(useRecursion && transform.childCount>0){
foreach (Transform child in transform) {
colorRecursive(child, toColor);
}
}
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5
private static void alphaRecursive( RectTransform rectTransform, float val, int recursiveLevel = 0){
if(rectTransform.childCount>0){
foreach (RectTransform child in rectTransform) {
UnityEngine.UI.Image uiImage = child.GetComponent<UnityEngine.UI.Image>();
if(uiImage!=null){
Color c = uiImage.color;
c.a = val;
uiImage.color = c;
}
alphaRecursive(child, val, recursiveLevel + 1);
}
}
}
private static void alphaRecursiveSprite( Transform transform, float val ){
if(transform.childCount>0){
foreach (Transform child in transform) {
SpriteRenderer ren = child.GetComponent<SpriteRenderer>();
if(ren!=null)
ren.color = new Color( ren.color.r, ren.color.g, ren.color.b, val);
alphaRecursiveSprite(child, val);
}
}
}
private static void colorRecursiveSprite( Transform transform, Color toColor ){
if(transform.childCount>0){
foreach (Transform child in transform) {
SpriteRenderer ren = transform.gameObject.GetComponent<SpriteRenderer>();
if(ren!=null)
ren.color = toColor;
colorRecursiveSprite(child, toColor);
}
}
}
private static void colorRecursive( RectTransform rectTransform, Color toColor ){
if(rectTransform.childCount>0){
foreach (RectTransform child in rectTransform) {
UnityEngine.UI.Image uiImage = child.GetComponent<UnityEngine.UI.Image>();
if(uiImage!=null){
uiImage.color = toColor;
}
colorRecursive(child, toColor);
}
}
}
private static void textAlphaRecursive( Transform trans, float val, bool useRecursion = true ){
UnityEngine.UI.Text uiText = trans.gameObject.GetComponent<UnityEngine.UI.Text>();
if(uiText!=null){
Color c = uiText.color;
c.a = val;
uiText.color = c;
}
if(useRecursion && trans.childCount>0){
foreach (Transform child in trans) {
textAlphaRecursive(child, val);
}
}
}
private static void textColorRecursive(Transform trans, Color toColor ){
if(trans.childCount>0){
foreach (Transform child in trans) {
UnityEngine.UI.Text uiText = child.gameObject.GetComponent<UnityEngine.UI.Text>();
if(uiText!=null){
uiText.color = toColor;
}
textColorRecursive(child, toColor);
}
}
}
#endif
private static Color tweenColor( LTDescr tween, float val ){
Vector3 diff3 = tween._optional.point - tween._optional.axis;
float diffAlpha = tween.to.y - tween.from.y;
return new Color(tween._optional.axis.x + diff3.x*val, tween._optional.axis.y + diff3.y*val, tween._optional.axis.z + diff3.z*val, tween.from.y + diffAlpha*val);
}
/**
* Pause a tween
*
* @method pause
* @return {LTDescr} LTDescr an object that distinguishes the tween
*/
public LTDescr pause(){
if(this.direction != 0.0f){ // check if tween is already paused
this.directionLast = this.direction;
this.direction = 0.0f;
}
return this;
}
/**
* Resume a paused tween
*
* @method resume
* @return {LTDescr} LTDescr an object that distinguishes the tween
*/
public LTDescr resume(){
this.direction = this.directionLast;
return this;
}
public LTDescr setAxis( Vector3 axis ){
this._optional.axis = axis;
return this;
}
/**
* Delay the start of a tween
*
* @method setDelay
* @param {float} float time The time to complete the tween in
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setDelay( 1.5f );
*/
public LTDescr setDelay( float delay ){
if(this.useEstimatedTime){
this.delay = delay;
}else{
this.delay = delay;//*Time.timeScale;
}
return this;
}
/**
* Set the type of easing used for the tween. <br>
* <ul><li><a href="LeanTweenType.html">List of all the ease types</a>.</li>
* <li><a href="http://www.robertpenner.com/easing/easing_demo.html">This page helps visualize the different easing equations</a></li>
* </ul>
*
* @method setEase
* @param {LeanTweenType} easeType:LeanTweenType the easing type to use
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setEase( LeanTweenType.easeInBounce );
*/
public LTDescr setEase( LeanTweenType easeType ){
switch( easeType ){
case LeanTweenType.linear:
setEaseLinear(); break;
case LeanTweenType.easeOutQuad:
setEaseOutQuad(); break;
case LeanTweenType.easeInQuad:
setEaseInQuad(); break;
case LeanTweenType.easeInOutQuad:
setEaseInOutQuad(); break;
case LeanTweenType.easeInCubic:
setEaseInCubic();break;
case LeanTweenType.easeOutCubic:
setEaseOutCubic(); break;
case LeanTweenType.easeInOutCubic:
setEaseInOutCubic(); break;
case LeanTweenType.easeInQuart:
setEaseInQuart(); break;
case LeanTweenType.easeOutQuart:
setEaseOutQuart(); break;
case LeanTweenType.easeInOutQuart:
setEaseInOutQuart(); break;
case LeanTweenType.easeInQuint:
setEaseInQuint(); break;
case LeanTweenType.easeOutQuint:
setEaseOutQuint(); break;
case LeanTweenType.easeInOutQuint:
setEaseInOutQuint(); break;
case LeanTweenType.easeInSine:
setEaseInSine(); break;
case LeanTweenType.easeOutSine:
setEaseOutSine(); break;
case LeanTweenType.easeInOutSine:
setEaseInOutSine(); break;
case LeanTweenType.easeInExpo:
setEaseInExpo(); break;
case LeanTweenType.easeOutExpo:
setEaseOutExpo(); break;
case LeanTweenType.easeInOutExpo:
setEaseInOutExpo(); break;
case LeanTweenType.easeInCirc:
setEaseInCirc(); break;
case LeanTweenType.easeOutCirc:
setEaseOutCirc(); break;
case LeanTweenType.easeInOutCirc:
setEaseInOutCirc(); break;
case LeanTweenType.easeInBounce:
setEaseInBounce(); break;
case LeanTweenType.easeOutBounce:
setEaseOutBounce(); break;
case LeanTweenType.easeInOutBounce:
setEaseInOutBounce(); break;
case LeanTweenType.easeInBack:
setEaseInBack(); break;
case LeanTweenType.easeOutBack:
setEaseOutBack(); break;
case LeanTweenType.easeInOutBack:
setEaseInOutBack(); break;
case LeanTweenType.easeInElastic:
setEaseInElastic(); break;
case LeanTweenType.easeOutElastic:
setEaseOutElastic(); break;
case LeanTweenType.easeInOutElastic:
setEaseInOutElastic(); break;
case LeanTweenType.punch:
setEasePunch(); break;
case LeanTweenType.easeShake:
setEaseShake(); break;
case LeanTweenType.easeSpring:
setEaseSpring(); break;
default:
setEaseLinear(); break;
}
return this;
}
public LTDescr setEaseLinear(){ this.tweenType = LeanTweenType.linear; this.easeMethod = this.easeLinear; return this; }
public LTDescr setEaseSpring(){ this.tweenType = LeanTweenType.easeSpring; this.easeMethod = this.easeSpring; return this; }
public LTDescr setEaseInQuad(){ this.tweenType = LeanTweenType.easeInQuad; this.easeMethod = this.easeInQuad; return this; }
public LTDescr setEaseOutQuad(){ this.tweenType = LeanTweenType.easeOutQuad; this.easeMethod = this.easeOutQuad; return this; }
public LTDescr setEaseInOutQuad(){ this.tweenType = LeanTweenType.easeInOutQuad; this.easeMethod = this.easeInOutQuad; return this;}
public LTDescr setEaseInCubic(){ this.tweenType = LeanTweenType.easeInCubic; this.easeMethod = this.easeInCubic; return this; }
public LTDescr setEaseOutCubic(){ this.tweenType = LeanTweenType.easeOutCubic; this.easeMethod = this.easeOutCubic; return this; }
public LTDescr setEaseInOutCubic(){ this.tweenType = LeanTweenType.easeInOutCubic; this.easeMethod = this.easeInOutCubic; return this; }
public LTDescr setEaseInQuart(){ this.tweenType = LeanTweenType.easeInQuart; this.easeMethod = this.easeInQuart; return this; }
public LTDescr setEaseOutQuart(){ this.tweenType = LeanTweenType.easeOutQuart; this.easeMethod = this.easeOutQuart; return this; }
public LTDescr setEaseInOutQuart(){ this.tweenType = LeanTweenType.easeInOutQuart; this.easeMethod = this.easeInOutQuart; return this; }
public LTDescr setEaseInQuint(){ this.tweenType = LeanTweenType.easeInQuint; this.easeMethod = this.easeInQuint; return this; }
public LTDescr setEaseOutQuint(){ this.tweenType = LeanTweenType.easeOutQuint; this.easeMethod = this.easeOutQuint; return this; }
public LTDescr setEaseInOutQuint(){ this.tweenType = LeanTweenType.easeInOutQuint; this.easeMethod = this.easeInOutQuint; return this; }
public LTDescr setEaseInSine(){ this.tweenType = LeanTweenType.easeInSine; this.easeMethod = this.easeInSine; return this; }
public LTDescr setEaseOutSine(){ this.tweenType = LeanTweenType.easeOutSine; this.easeMethod = this.easeOutSine; return this; }
public LTDescr setEaseInOutSine(){ this.tweenType = LeanTweenType.easeInOutSine; this.easeMethod = this.easeInOutSine; return this; }
public LTDescr setEaseInExpo(){ this.tweenType = LeanTweenType.easeInExpo; this.easeMethod = this.easeInExpo; return this; }
public LTDescr setEaseOutExpo(){ this.tweenType = LeanTweenType.easeOutExpo; this.easeMethod = this.easeOutExpo; return this; }
public LTDescr setEaseInOutExpo(){ this.tweenType = LeanTweenType.easeInOutExpo; this.easeMethod = this.easeInOutExpo; return this; }
public LTDescr setEaseInCirc(){ this.tweenType = LeanTweenType.easeInCirc; this.easeMethod = this.easeInCirc; return this; }
public LTDescr setEaseOutCirc(){ this.tweenType = LeanTweenType.easeOutCirc; this.easeMethod = this.easeOutCirc; return this; }
public LTDescr setEaseInOutCirc(){ this.tweenType = LeanTweenType.easeInOutCirc; this.easeMethod = this.easeInOutCirc; return this; }
public LTDescr setEaseInBounce(){ this.tweenType = LeanTweenType.easeInBounce; this.easeMethod = this.easeInBounce; return this; }
public LTDescr setEaseOutBounce(){ this.tweenType = LeanTweenType.easeOutBounce; this.easeMethod = this.easeOutBounce; return this; }
public LTDescr setEaseInOutBounce(){ this.tweenType = LeanTweenType.easeInOutBounce; this.easeMethod = this.easeInOutBounce; return this; }
public LTDescr setEaseInBack(){ this.tweenType = LeanTweenType.easeInBack; this.easeMethod = this.easeInBack; return this; }
public LTDescr setEaseOutBack(){ this.tweenType = LeanTweenType.easeOutBack; this.easeMethod = this.easeOutBack; return this; }
public LTDescr setEaseInOutBack(){ this.tweenType = LeanTweenType.easeInOutBack; this.easeMethod = this.easeInOutBack; return this; }
public LTDescr setEaseInElastic(){ this.tweenType = LeanTweenType.easeInElastic; this.easeMethod = this.easeInElastic; return this; }
public LTDescr setEaseOutElastic(){ this.tweenType = LeanTweenType.easeOutElastic; this.easeMethod = this.easeOutElastic; return this; }
public LTDescr setEaseInOutElastic(){ this.tweenType = LeanTweenType.easeInOutElastic; this.easeMethod = this.easeInOutElastic; return this; }
public LTDescr setEasePunch(){ this._optional.animationCurve = LeanTween.punch; this.toInternal.x = this.from.x + this.to.x; this.easeMethod = this.tweenOnCurve; return this; }
public LTDescr setEaseShake(){ this._optional.animationCurve = LeanTween.shake; this.toInternal.x = this.from.x + this.to.x; this.easeMethod = this.tweenOnCurve; return this; }
private Vector3 tweenOnCurve(){
float r = this._optional.animationCurve.Evaluate(ratioPassed) * this.scale;
return new Vector3(this.from.x + (this.diff.x) * r,
this.from.y + (this.diff.y) * r,
this.from.z + (this.diff.z) * r );
}
// Vector3 Ease Methods
private Vector3 easeInOutQuad(){
val = this.ratioPassed * 2f;
if (val < 1f) {
val = val * val;
return new Vector3( this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
}
val = (1f-val) * (val - 3f) + 1f;
return new Vector3( this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
}
private Vector3 easeInQuad(){
val = ratioPassed * ratioPassed;
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y, this.diff.z * val + this.from.z);
}
private Vector3 easeOutQuad(){
val = this.ratioPassed;
val = -val * (val - 2f);
return (this.diff * val + this.from);
}
private Vector3 easeLinear(){
val = this.ratioPassed;
return new Vector3(this.from.x+this.diff.x*val, this.from.y+this.diff.y*val, this.from.z+this.diff.z*val);
}
private Vector3 easeSpring(){
val = Mathf.Clamp01(this.ratioPassed);
val = (Mathf.Sin(val * Mathf.PI * (0.2f + 2.5f * val * val * val)) * Mathf.Pow(1f - val, 2.2f ) + val) * (1f + (1.2f * (1f - val) ));
return this.from + this.diff * val;
}
private Vector3 easeInCubic(){
val = this.ratioPassed * this.ratioPassed * this.ratioPassed;
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y, this.diff.z * val + this.from.z);
}
private Vector3 easeOutCubic(){
val = this.ratioPassed - 1f;
val = (val * val * val + 1);
return new Vector3( this.diff.x * val + this.from.x, this.diff.y * val + this.from.y, this.diff.z * val + this.from.z) ;
}
private Vector3 easeInOutCubic(){
val = this.ratioPassed * 2f;
if (val < 1f) {
val = val * val * val;
return new Vector3(this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
}
val -= 2f;
val = val * val * val + 2f;
return new Vector3(this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y,this.diffDiv2.z * val + this.from.z);
}
private Vector3 easeInQuart(){
val = this.ratioPassed * this.ratioPassed * this.ratioPassed * this.ratioPassed;
return diff * val + this.from;
}
private Vector3 easeOutQuart(){
val = this.ratioPassed - 1f;
val = -(val * val * val * val - 1);
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y,this.diff.z * val + this.from.z);
}
private Vector3 easeInOutQuart(){
val = this.ratioPassed * 2f;
if (val < 1f) {
val = val * val * val * val;
return new Vector3(this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
}
val -= 2f;
val = (val * val * val * val - 2f);
return new Vector3(-this.diffDiv2.x * val + this.from.x, -this.diffDiv2.x * val + this.from.x, -this.diffDiv2.x * val + this.from.x);
}
private Vector3 easeInQuint(){
val = this.ratioPassed;
val = val * val * val * val * val;
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y, this.diff.z * val + this.from.z);
}
private Vector3 easeOutQuint(){
val = this.ratioPassed - 1f;
val = (val * val * val * val * val + 1f);
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y, this.diff.z * val + this.from.z);
}
private Vector3 easeInOutQuint(){
val = this.ratioPassed * 2f;
if (val < 1f){
val = val * val * val * val * val;
return new Vector3(this.diffDiv2.x * val + this.from.x,this.diffDiv2.y * val + this.from.y,this.diffDiv2.z * val + this.from.z);
}
val -= 2f;
val = (val * val * val * val * val + 2f);
return new Vector3(this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
}
private Vector3 easeInSine(){
val = - Mathf.Cos(this.ratioPassed * LeanTween.PI_DIV2);
return new Vector3(this.diff.x * val + this.diff.x + this.from.x, this.diff.y * val + this.diff.y + this.from.y, this.diff.z * val + this.diff.z + this.from.z);
}
private Vector3 easeOutSine(){
val = Mathf.Sin(this.ratioPassed * LeanTween.PI_DIV2);
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y,this.diff.z * val + this.from.z);
}
private Vector3 easeInOutSine(){
val = -(Mathf.Cos(Mathf.PI * this.ratioPassed) - 1f);
return new Vector3(this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
}
private Vector3 easeInExpo(){
val = Mathf.Pow(2f, 10f * (this.ratioPassed - 1f));
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y, this.diff.z * val + this.from.z);
}
private Vector3 easeOutExpo(){
val = (-Mathf.Pow(2f, -10f * this.ratioPassed) + 1f);
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y, this.diff.z * val + this.from.z);
}
private Vector3 easeInOutExpo(){
val = this.ratioPassed * 2f;
val = Mathf.Pow(2f, 10f * (val - 1f));
if (val < 1f)
return new Vector3(this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
val--;
val = (-Mathf.Pow(2f, -10f * val) + 2f);
return new Vector3(this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
}
private Vector3 easeInCirc(){
val = -(Mathf.Sqrt(1f - this.ratioPassed * this.ratioPassed) - 1f);
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y, this.diff.z * val + this.from.z);
}
private Vector3 easeOutCirc(){
val = this.ratioPassed - 1f;
val = Mathf.Sqrt(1f - val * val);
return new Vector3(this.diff.x * val + this.from.x, this.diff.y * val + this.from.y, this.diff.z * val + this.from.z);
}
private Vector3 easeInOutCirc(){
val = this.ratioPassed * 2f;
if (val < 1f){
val = -(Mathf.Sqrt(1f - val * val) - 1f);
return new Vector3(this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
}
val -= 2f;
val = (Mathf.Sqrt(1f - val * val) + 1f);
return new Vector3(this.diffDiv2.x * val + this.from.x, this.diffDiv2.y * val + this.from.y, this.diffDiv2.z * val + this.from.z);
}
private Vector3 easeInBounce(){
val = this.ratioPassed;
val = 1f - val;
return new Vector3(this.diff.x - LeanTween.easeOutBounce(0, this.diff.x, val) + this.from.x,
this.diff.y - LeanTween.easeOutBounce(0, this.diff.y, val) + this.from.y,
this.diff.z - LeanTween.easeOutBounce(0, this.diff.z, val) + this.from.z);
}
private Vector3 easeOutBounce(){
val = ratioPassed;
if (val < (1 / 2.75f)){
val = (7.5625f * val * val);
return this.diff * val + this.from;
}else if (val < (2 / 2.75f)){
val -= (1.5f / 2.75f);
val = (7.5625f * (val) * val + .75f);
return this.diff * val + this.from;
}else if (val < (2.5 / 2.75)){
val -= (2.25f / 2.75f);
val = (7.5625f * (val) * val + .9375f);
return this.diff * val + this.from;
}else{
val -= (2.625f / 2.75f);
val = 7.5625f * (val) * val + .984375f;
return this.diff * val + this.from;
}
}
private Vector3 easeInOutBounce(){
val = this.ratioPassed * 2f;
if (val < 1f){
return new Vector3(LeanTween.easeInBounce(0, this.diff.x, val) * 0.5f + this.from.x,
LeanTween.easeInBounce(0, this.diff.y, val) * 0.5f + this.from.y,
LeanTween.easeInBounce(0, this.diff.z, val) * 0.5f + this.from.z);
}else {
val = val - 1f;
return new Vector3(LeanTween.easeOutBounce(0, this.diff.x, val) * 0.5f + this.diffDiv2.x + this.from.x,
LeanTween.easeOutBounce(0, this.diff.y, val) * 0.5f + this.diffDiv2.y + this.from.y,
LeanTween.easeOutBounce(0, this.diff.z, val) * 0.5f + this.diffDiv2.z + this.from.z);
}
}
private Vector3 easeInBack(){
val = this.ratioPassed;
val /= 1;
float s = 1.70158f * this.overshoot;
return this.diff * (val) * val * ((s + 1) * val - s) + this.from;
}
private Vector3 easeOutBack(){
float s = 1.70158f * this.overshoot;
val = (this.ratioPassed / 1) - 1;
val = ((val) * val * ((s + 1) * val + s) + 1);
return this.diff * val + this.from;
}
private Vector3 easeInOutBack(){
float s = 1.70158f * this.overshoot;
val = this.ratioPassed * 2f;
if ((val) < 1){
s *= (1.525f) * overshoot;
return this.diffDiv2 * (val * val * (((s) + 1) * val - s)) + this.from;
}
val -= 2;
s *= (1.525f) * overshoot;
val = ((val) * val * (((s) + 1) * val + s) + 2);
return this.diffDiv2 * val + this.from;
}
private Vector3 easeInElastic(){
return new Vector3(LeanTween.easeInElastic(this.from.x,this.to.x,this.ratioPassed,this.overshoot,this.period),
LeanTween.easeInElastic(this.from.y,this.to.y,this.ratioPassed,this.overshoot,this.period),
LeanTween.easeInElastic(this.from.z,this.to.z,this.ratioPassed,this.overshoot,this.period));
}
private Vector3 easeOutElastic(){
return new Vector3(LeanTween.easeOutElastic(this.from.x,this.to.x,this.ratioPassed,this.overshoot,this.period),
LeanTween.easeOutElastic(this.from.y,this.to.y,this.ratioPassed,this.overshoot,this.period),
LeanTween.easeOutElastic(this.from.z,this.to.z,this.ratioPassed,this.overshoot,this.period));
}
private Vector3 easeInOutElastic()
{
return new Vector3(LeanTween.easeInOutElastic(this.from.x,this.to.x,this.ratioPassed,this.overshoot,this.period),
LeanTween.easeInOutElastic(this.from.y,this.to.y,this.ratioPassed,this.overshoot,this.period),
LeanTween.easeInOutElastic(this.from.z,this.to.z,this.ratioPassed,this.overshoot,this.period));
}
/**
* Set how far past a tween will overshoot for certain ease types (compatible: easeInBack, easeInOutBack, easeOutBack, easeOutElastic, easeInElastic, easeInOutElastic). <br>
* @method setOvershoot
* @param {float} overshoot:float how far past the destination it will go before settling in
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setEase( LeanTweenType.easeOutBack ).setOvershoot(2f);
*/
public LTDescr setOvershoot( float overshoot ){
this.overshoot = overshoot;
return this;
}
/**
* Set how short the iterations are for certain ease types (compatible: easeOutElastic, easeInElastic, easeInOutElastic). <br>
* @method setPeriod
* @param {float} period:float how short the iterations are that the tween will animate at (default 0.3f)
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setEase( LeanTweenType.easeOutElastic ).setPeriod(0.3f);
*/
public LTDescr setPeriod( float period ){
this.period = period;
return this;
}
/**
* Set how large the effect is for certain ease types (compatible: punch, shake, animation curves). <br>
* @method setScale
* @param {float} scale:float how much the ease will be multiplied by (default 1f)
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setEase( LeanTweenType.punch ).setScale(2f);
*/
public LTDescr setScale( float scale ){
this.scale = scale;
return this;
}
/**
* Set the type of easing used for the tween with a custom curve. <br>
* @method setEase (AnimationCurve)
* @param {AnimationCurve} easeDefinition:AnimationCurve an <a href="http://docs.unity3d.com/Documentation/ScriptReference/AnimationCurve.html" target="_blank">AnimationCure</a> that describes the type of easing you want, this is great for when you want a unique type of movement
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setEase( LeanTweenType.easeInBounce );
*/
public LTDescr setEase( AnimationCurve easeCurve ){
this._optional.animationCurve = easeCurve;
this.easeMethod = this.tweenOnCurve;
this.tweenType = LeanTweenType.animationCurve;
return this;
}
/**
* Set the end that the GameObject is tweening towards
* @method setTo
* @param {Vector3} to:Vector3 point at which you want the tween to reach
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LTDescr descr = LeanTween.move( cube, Vector3.up, new Vector3(1f,3f,0f), 1.0f ).setEase( LeanTweenType.easeInOutBounce );<br>
* // Later your want to change your destination or your destiation is constantly moving<br>
* descr.setTo( new Vector3(5f,10f,3f); );<br>
*/
public LTDescr setTo( Vector3 to ){
if(this.hasInitiliazed){
this.to = to;
this.diff = to - this.from;
}else{
this.to = to;
}
return this;
}
public LTDescr setTo( Transform to ){
this._optional.toTrans = to;
return this;
}
public LTDescr setFrom( Vector3 from ){
if(this.trans){
this.init();
}
this.from = from;
// this.hasInitiliazed = true; // this is set, so that the "from" value isn't overwritten later on when the tween starts
this.diff = this.to - this.from;
return this;
}
public LTDescr setFrom( float from ){
return setFrom( new Vector3(from, 0f, 0f) );
}
public LTDescr setDiff( Vector3 diff ){
this.diff = diff;
return this;
}
public LTDescr setHasInitialized( bool has ){
this.hasInitiliazed = has;
return this;
}
public LTDescr setId( uint id ){
this._id = id;
this.counter = global_counter;
// Debug.Log("Global counter:"+global_counter);
return this;
}
/**
* Set the finish time of the tween
* @method setTime
* @param {float} finishTime:float the length of time in seconds you wish the tween to complete in
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* int tweenId = LeanTween.moveX(gameObject, 5f, 2.0f ).id;<br>
* // Later<br>
* LTDescr descr = description( tweenId );<br>
* descr.setTime( 1f );<br>
*/
public LTDescr setTime( float time ){
float passedTimeRatio = this.passed / this.time;
this.passed = time * passedTimeRatio;
this.time = time;
return this;
}
/**
* Set the finish time of the tween
* @method setSpeed
* @param {float} speed:float the speed in unity units per second you wish the object to travel (overrides the given time)
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveLocalZ( gameObject, 10f, 1f).setSpeed(0.2f) // the given time is ignored when speed is set<br>
*/
public LTDescr setSpeed( float speed ){
this.speed = speed;
if(this.hasInitiliazed)
initSpeed();
return this;
}
/**
* Set the tween to repeat a number of times.
* @method setRepeat
* @param {int} repeatNum:int the number of times to repeat the tween. -1 to repeat infinite times
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setRepeat( 10 ).setLoopPingPong();
*/
public LTDescr setRepeat( int repeat ){
this.loopCount = repeat;
if((repeat>1 && this.loopType == LeanTweenType.once) || (repeat < 0 && this.loopType == LeanTweenType.once)){
this.loopType = LeanTweenType.clamp;
}
if(this.type==TweenAction.CALLBACK || this.type==TweenAction.CALLBACK_COLOR){
this.setOnCompleteOnRepeat(true);
}
return this;
}
public LTDescr setLoopType( LeanTweenType loopType ){
this.loopType = loopType;
return this;
}
public LTDescr setUseEstimatedTime( bool useEstimatedTime ){
this.useEstimatedTime = useEstimatedTime;
return this;
}
/**
* Set ignore time scale when tweening an object when you want the animation to be time-scale independent (ignores the Time.timeScale value). Great for pause screens, when you want all other action to be stopped (or slowed down)
* @method setIgnoreTimeScale
* @param {bool} useUnScaledTime:bool whether to use the unscaled time or not
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setRepeat( 2 ).setIgnoreTimeScale( true );
*/
public LTDescr setIgnoreTimeScale( bool useUnScaledTime ){
this.useEstimatedTime = useUnScaledTime;
return this;
}
/**
* Use frames when tweening an object, when you don't want the animation to be time-frame independent...
* @method setUseFrames
* @param {bool} useFrames:bool whether to use estimated time or not
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setRepeat( 2 ).setUseFrames( true );
*/
public LTDescr setUseFrames( bool useFrames ){
this.useFrames = useFrames;
return this;
}
public LTDescr setUseManualTime( bool useManualTime ){
this.useManualTime = useManualTime;
return this;
}
public LTDescr setLoopCount( int loopCount ){
this.loopType = LeanTweenType.clamp;
this.loopCount = loopCount;
return this;
}
/**
* No looping involved, just run once (the default)
* @method setLoopOnce
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setLoopOnce();
*/
public LTDescr setLoopOnce(){ this.loopType = LeanTweenType.once; return this; }
/**
* When the animation gets to the end it starts back at where it began
* @method setLoopClamp
* @param {int} loops:int (defaults to -1) how many times you want the loop to happen (-1 for an infinite number of times)
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setLoopClamp( 2 );
*/
public LTDescr setLoopClamp(){
this.loopType = LeanTweenType.clamp;
if(this.loopCount==0)
this.loopCount = -1;
return this;
}
public LTDescr setLoopClamp( int loops ){
this.loopCount = loops;
return this;
}
/**
* When the animation gets to the end it then tweens back to where it started (and on, and on)
* @method setLoopPingPong
* @param {int} loops:int (defaults to -1) how many times you want the loop to happen in both directions (-1 for an infinite number of times). Passing a value of 1 will cause the object to go towards and back from it's destination once.
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setLoopPingPong( 2 );
*/
public LTDescr setLoopPingPong(){
this.loopType = LeanTweenType.pingPong;
if(this.loopCount==0)
this.loopCount = -1;
return this;
}
public LTDescr setLoopPingPong( int loops ) {
this.loopType = LeanTweenType.pingPong;
this.loopCount = loops == -1 ? loops : loops * 2;
return this;
}
/**
* Have a method called when the tween finishes
* @method setOnComplete
* @param {Action} onComplete:Action the method that should be called when the tween is finished ex: tweenFinished(){ }
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setOnComplete( tweenFinished );
*/
public LTDescr setOnComplete( Action onComplete ){
this._optional.onComplete = onComplete;
this.hasExtraOnCompletes = true;
return this;
}
/**
* Have a method called when the tween finishes
* @method setOnComplete (object)
* @param {Action<object>} onComplete:Action<object> the method that should be called when the tween is finished ex: tweenFinished( object myObj ){ }
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setOnComplete( tweenFinished );
*/
public LTDescr setOnComplete( Action<object> onComplete ){
this._optional.onCompleteObject = onComplete;
this.hasExtraOnCompletes = true;
return this;
}
public LTDescr setOnComplete( Action<object> onComplete, object onCompleteParam ){
this._optional.onCompleteObject = onComplete;
this.hasExtraOnCompletes = true;
if(onCompleteParam!=null)
this._optional.onCompleteParam = onCompleteParam;
return this;
}
/**
* Pass an object to along with the onComplete Function
* @method setOnCompleteParam
* @param {object} onComplete:object an object that
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.delayedCall(1.5f, enterMiniGameStart).setOnCompleteParam( new object[]{""+5} );<br><br>
* void enterMiniGameStart( object val ){<br>
* object[] arr = (object [])val;<br>
* int lvl = int.Parse((string)arr[0]);<br>
* }<br>
*/
public LTDescr setOnCompleteParam( object onCompleteParam ){
this._optional.onCompleteParam = onCompleteParam;
this.hasExtraOnCompletes = true;
return this;
}
/**
* Have a method called on each frame that the tween is being animated (passes a float value)
* @method setOnUpdate
* @param {Action<float>} onUpdate:Action<float> a method that will be called on every frame with the float value of the tweened object
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setOnUpdate( tweenMoved );<br>
* <br>
* void tweenMoved( float val ){ }<br>
*/
public LTDescr setOnUpdate( Action<float> onUpdate ){
this._optional.onUpdateFloat = onUpdate;
this.hasUpdateCallback = true;
return this;
}
public LTDescr setOnUpdateRatio(Action<float,float> onUpdate)
{
this._optional.onUpdateFloatRatio = onUpdate;
this.hasUpdateCallback = true;
return this;
}
public LTDescr setOnUpdateObject( Action<float,object> onUpdate ){
this._optional.onUpdateFloatObject = onUpdate;
this.hasUpdateCallback = true;
return this;
}
public LTDescr setOnUpdateVector2( Action<Vector2> onUpdate ){
this._optional.onUpdateVector2 = onUpdate;
this.hasUpdateCallback = true;
return this;
}
public LTDescr setOnUpdateVector3( Action<Vector3> onUpdate ){
this._optional.onUpdateVector3 = onUpdate;
this.hasUpdateCallback = true;
return this;
}
public LTDescr setOnUpdateColor( Action<Color> onUpdate ){
this._optional.onUpdateColor = onUpdate;
this.hasUpdateCallback = true;
return this;
}
public LTDescr setOnUpdateColor( Action<Color,object> onUpdate ){
this._optional.onUpdateColorObject = onUpdate;
this.hasUpdateCallback = true;
return this;
}
#if !UNITY_FLASH
public LTDescr setOnUpdate( Action<Color> onUpdate ){
this._optional.onUpdateColor = onUpdate;
this.hasUpdateCallback = true;
return this;
}
public LTDescr setOnUpdate( Action<Color,object> onUpdate ){
this._optional.onUpdateColorObject = onUpdate;
this.hasUpdateCallback = true;
return this;
}
/**
* Have a method called on each frame that the tween is being animated (passes a float value and a object)
* @method setOnUpdate (object)
* @param {Action<float,object>} onUpdate:Action<float,object> a method that will be called on every frame with the float value of the tweened object, and an object of the person's choosing
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setOnUpdate( tweenMoved ).setOnUpdateParam( myObject );<br>
* <br>
* void tweenMoved( float val, object obj ){ }<br>
*/
public LTDescr setOnUpdate( Action<float,object> onUpdate, object onUpdateParam = null ){
this._optional.onUpdateFloatObject = onUpdate;
this.hasUpdateCallback = true;
if(onUpdateParam!=null)
this._optional.onUpdateParam = onUpdateParam;
return this;
}
public LTDescr setOnUpdate( Action<Vector3,object> onUpdate, object onUpdateParam = null ){
this._optional.onUpdateVector3Object = onUpdate;
this.hasUpdateCallback = true;
if(onUpdateParam!=null)
this._optional.onUpdateParam = onUpdateParam;
return this;
}
public LTDescr setOnUpdate( Action<Vector2> onUpdate, object onUpdateParam = null ){
this._optional.onUpdateVector2 = onUpdate;
this.hasUpdateCallback = true;
if(onUpdateParam!=null)
this._optional.onUpdateParam = onUpdateParam;
return this;
}
/**
* Have a method called on each frame that the tween is being animated (passes a float value)
* @method setOnUpdate (Vector3)
* @param {Action<Vector3>} onUpdate:Action<Vector3> a method that will be called on every frame with the float value of the tweened object
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setOnUpdate( tweenMoved );<br>
* <br>
* void tweenMoved( Vector3 val ){ }<br>
*/
public LTDescr setOnUpdate( Action<Vector3> onUpdate, object onUpdateParam = null ){
this._optional.onUpdateVector3 = onUpdate;
this.hasUpdateCallback = true;
if(onUpdateParam!=null)
this._optional.onUpdateParam = onUpdateParam;
return this;
}
#endif
/**
* Have an object passed along with the onUpdate method
* @method setOnUpdateParam
* @param {object} onUpdateParam:object an object that will be passed along with the onUpdate method
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveX(gameObject, 5f, 2.0f ).setOnUpdate( tweenMoved ).setOnUpdateParam( myObject );<br>
* <br>
* void tweenMoved( float val, object obj ){ }<br>
*/
public LTDescr setOnUpdateParam( object onUpdateParam ){
this._optional.onUpdateParam = onUpdateParam;
return this;
}
/**
* While tweening along a curve, set this property to true, to be perpendicalur to the path it is moving upon
* @method setOrientToPath
* @param {bool} doesOrient:bool whether the gameobject will orient to the path it is animating along
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.move( ltLogo, path, 1.0f ).setEase(LeanTweenType.easeOutQuad).setOrientToPath(true).setAxis(Vector3.forward);<br>
*/
public LTDescr setOrientToPath( bool doesOrient ){
if(this.type==TweenAction.MOVE_CURVED || this.type==TweenAction.MOVE_CURVED_LOCAL){
if(this._optional.path==null)
this._optional.path = new LTBezierPath();
this._optional.path.orientToPath = doesOrient;
}else{
this._optional.spline.orientToPath = doesOrient;
}
return this;
}
/**
* While tweening along a curve, set this property to true, to be perpendicalur to the path it is moving upon
* @method setOrientToPath2d
* @param {bool} doesOrient:bool whether the gameobject will orient to the path it is animating along
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.move( ltLogo, path, 1.0f ).setEase(LeanTweenType.easeOutQuad).setOrientToPath2d(true).setAxis(Vector3.forward);<br>
*/
public LTDescr setOrientToPath2d( bool doesOrient2d ){
setOrientToPath(doesOrient2d);
if(this.type==TweenAction.MOVE_CURVED || this.type==TweenAction.MOVE_CURVED_LOCAL){
this._optional.path.orientToPath2d = doesOrient2d;
}else{
this._optional.spline.orientToPath2d = doesOrient2d;
}
return this;
}
public LTDescr setRect( LTRect rect ){
this._optional.ltRect = rect;
return this;
}
public LTDescr setRect( Rect rect ){
this._optional.ltRect = new LTRect(rect);
return this;
}
public LTDescr setPath( LTBezierPath path ){
this._optional.path = path;
return this;
}
/**
* Set the point at which the GameObject will be rotated around
* @method setPoint
* @param {Vector3} point:Vector3 point at which you want the object to rotate around (local space)
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.rotateAround( cube, Vector3.up, 360.0f, 1.0f ) .setPoint( new Vector3(1f,0f,0f) ) .setEase( LeanTweenType.easeInOutBounce );<br>
*/
public LTDescr setPoint( Vector3 point ){
this._optional.point = point;
return this;
}
public LTDescr setDestroyOnComplete( bool doesDestroy ){
this.destroyOnComplete = doesDestroy;
return this;
}
public LTDescr setAudio( object audio ){
this._optional.onCompleteParam = audio;
return this;
}
/**
* Set the onComplete method to be called at the end of every loop cycle (also applies to the delayedCall method)
* @method setOnCompleteOnRepeat
* @param {bool} isOn:bool does call onComplete on every loop cycle
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.delayedCall(gameObject,0.3f, delayedMethod).setRepeat(4).setOnCompleteOnRepeat(true);
*/
public LTDescr setOnCompleteOnRepeat( bool isOn ){
this.onCompleteOnRepeat = isOn;
return this;
}
/**
* Set the onComplete method to be called at the beginning of the tween (it will still be called when it is completed as well)
* @method setOnCompleteOnStart
* @param {bool} isOn:bool does call onComplete at the start of the tween
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.delayedCall(gameObject, 2f, ()=>{<br> // Flash an object 5 times
* LeanTween.alpha(gameObject, 0f, 1f);<br>
* LeanTween.alpha(gameObject, 1f, 0f).setDelay(1f);<br>
* }).setOnCompleteOnStart(true).setRepeat(5);<br>
*/
public LTDescr setOnCompleteOnStart( bool isOn ){
this.onCompleteOnStart = isOn;
return this;
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5
public LTDescr setRect( RectTransform rect ){
this.rectTransform = rect;
return this;
}
public LTDescr setSprites( UnityEngine.Sprite[] sprites ){
this.sprites = sprites;
return this;
}
public LTDescr setFrameRate( float frameRate ){
this.time = this.sprites.Length / frameRate;
return this;
}
#endif
/**
* Have a method called when the tween starts
* @method setOnStart
* @param {Action<>} onStart:Action<> the method that should be called when the tween is starting ex: tweenStarted( ){ }
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* <i>C#:</i><br>
* LeanTween.moveX(gameObject, 5f, 2.0f ).setOnStart( ()=>{ Debug.Log("I started!"); });
* <i>Javascript:</i><br>
* LeanTween.moveX(gameObject, 5f, 2.0f ).setOnStart( function(){ Debug.Log("I started!"); } );
*/
public LTDescr setOnStart( Action onStart ){
this._optional.onStart = onStart;
return this;
}
/**
* Set the direction of a tween -1f for backwards 1f for forwards (currently only bezier and spline paths are supported)
* @method setDirection
* @param {float} direction:float the direction that the tween should run, -1f for backwards 1f for forwards
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.moveSpline(gameObject, new Vector3[]{new Vector3(0f,0f,0f),new Vector3(1f,0f,0f),new Vector3(1f,0f,0f),new Vector3(1f,0f,1f)}, 1.5f).setDirection(-1f);<br>
*/
public LTDescr setDirection( float direction ){
if(this.direction!=-1f && this.direction!=1f){
Debug.LogWarning("You have passed an incorrect direction of '"+direction+"', direction must be -1f or 1f");
return this;
}
if(this.direction!=direction){
// Debug.Log("reverse path:"+this.path+" spline:"+this._optional.spline+" hasInitiliazed:"+this.hasInitiliazed);
if(this.hasInitiliazed){
this.direction = direction;
}else{
if(this._optional.path!=null){
this._optional.path = new LTBezierPath( LTUtility.reverse( this._optional.path.pts ) );
}else if(this._optional.spline!=null){
this._optional.spline = new LTSpline( LTUtility.reverse( this._optional.spline.pts ) );
}
// this.passed = this.time - this.passed;
}
}
return this;
}
/**
* Set whether or not the tween will recursively effect an objects children in the hierarchy
* @method setRecursive
* @param {bool} useRecursion:bool whether the tween will recursively effect an objects children in the hierarchy
* @return {LTDescr} LTDescr an object that distinguishes the tween
* @example
* LeanTween.alpha(gameObject, 0f, 1f).setRecursive(true);<br>
*/
public LTDescr setRecursive( bool useRecursion ){
this.useRecursion = useRecursion;
return this;
}
}
| 35.485714 | 318 | 0.707244 | [
"MIT"
] | stervets/bomber | Assets/Plugins/LeanTween/LTDescr.cs | 78,248 | 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 System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.ServiceFabric.Common;
using Microsoft.Azure.Commands.ServiceFabric.Models;
using Microsoft.Azure.Management.ServiceFabric;
using ServiceFabricProperties = Microsoft.Azure.Commands.ServiceFabric.Properties;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
namespace Microsoft.Azure.Commands.ServiceFabric.Commands
{
[Cmdlet(VerbsCommon.Get, CmdletNoun.AzureRmServiceFabricCluster, DefaultParameterSetName = "BySubscription"), OutputType(typeof(IList<PSCluster>))]
public class GetAzureRmServiceFabricCluster : ServiceFabricClusterCmdlet
{
private const string ByResourceGroup = "ByResourceGroup";
private const string ByName = "ByName";
[Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByResourceGroup,
HelpMessage = "Specify the name of the resource group.")]
[Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ByName,
HelpMessage = "Specify the name of the resource group.")]
[ResourceGroupCompleter]
[ValidateNotNullOrEmpty()]
public override string ResourceGroupName { get; set; }
[Parameter(Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = ByName,
HelpMessage = "Specify the name of the cluster")]
[ValidateNotNullOrEmpty()]
[Alias("ClusterName")]
public override string Name { get; set; }
public override void ExecuteCmdlet()
{
switch (ParameterSetName)
{
case ByName:
{
var cluster = GetCurrentCluster();
WriteObject(new List<PSCluster>() { new PSCluster(cluster) }, true);
break;
}
case ByResourceGroup:
{
var clusters = SFRPClient.Clusters.
ListByResourceGroup(ResourceGroupName).
Select(c => new PSCluster(c)).ToList();
WriteObject(clusters, true);
break;
}
default:
{
var clusters = SFRPClient.Clusters.List().Select(c => new PSCluster(c)).ToList();
WriteObject(clusters, true);
break;
}
}
}
}
} | 47.189189 | 152 | 0.584765 | [
"MIT"
] | AzureDataBox/azure-powershell | src/ResourceManager/ServiceFabric/Commands.ServiceFabric/Commands/GetAzureRmServiceFabricClusterResouce.cs | 3,421 | C# |
namespace Muc.Systems.Input {
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Muc.Extensions;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
#if (MUC_HIDE_COMPONENTS || MUC_HIDE_SYSTEM_COMPONENTS)
[AddComponentMenu("")]
#else
[AddComponentMenu("MyUnityCollection/" + nameof(Muc.Systems.Input) + "/" + nameof(QuaternionInput))]
#endif
public class QuaternionInput : Input<Quaternion> {
protected override void OnInputUpdate(InputAction.CallbackContext context) {
if (value != (value = context.ReadValue<Quaternion>())) {
onChange.Invoke(value);
}
}
internal override bool IsControlSupported(InputControl control) {
return control is QuaternionControl;
}
}
} | 24.333333 | 101 | 0.758406 | [
"MIT"
] | Satsaa/HeatSim | Assets/MyUnityCollection/Scripts/Muc.Systems/Muc.Systems.Input/QuaternionInput.cs | 803 | C# |
using System;
using System.Reflection;
using System.Collections.Generic;
namespace Anet.Data
{
internal static class TypeExtensions
{
public static string Name(this Type type) =>
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().Name;
#else
type.Name;
#endif
public static bool IsValueType(this Type type) =>
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().IsValueType;
#else
type.IsValueType;
#endif
public static bool IsEnum(this Type type) =>
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().IsEnum;
#else
type.IsEnum;
#endif
public static bool IsGenericType(this Type type) =>
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().IsGenericType;
#else
type.IsGenericType;
#endif
public static bool IsInterface(this Type type) =>
#if NETSTANDARD1_3 || NETCOREAPP1_0
type.GetTypeInfo().IsInterface;
#else
type.IsInterface;
#endif
#if NETSTANDARD1_3 || NETCOREAPP1_0
public static IEnumerable<Attribute> GetCustomAttributes(this Type type, bool inherit)
{
return type.GetTypeInfo().GetCustomAttributes(inherit);
}
public static TypeCode GetTypeCode(Type type)
{
if (type == null) return TypeCode.Empty;
if (typeCodeLookup.TryGetValue(type, out TypeCode result)) return result;
if (type.IsEnum())
{
type = Enum.GetUnderlyingType(type);
if (typeCodeLookup.TryGetValue(type, out result)) return result;
}
return TypeCode.Object;
}
private static readonly Dictionary<Type, TypeCode> typeCodeLookup = new Dictionary<Type, TypeCode>
{
[typeof(bool)] = TypeCode.Boolean,
[typeof(byte)] = TypeCode.Byte,
[typeof(char)] = TypeCode.Char,
[typeof(DateTime)] = TypeCode.DateTime,
[typeof(decimal)] = TypeCode.Decimal,
[typeof(double)] = TypeCode.Double,
[typeof(short)] = TypeCode.Int16,
[typeof(int)] = TypeCode.Int32,
[typeof(long)] = TypeCode.Int64,
[typeof(object)] = TypeCode.Object,
[typeof(sbyte)] = TypeCode.SByte,
[typeof(float)] = TypeCode.Single,
[typeof(string)] = TypeCode.String,
[typeof(ushort)] = TypeCode.UInt16,
[typeof(uint)] = TypeCode.UInt32,
[typeof(ulong)] = TypeCode.UInt64,
};
#else
public static TypeCode GetTypeCode(Type type) => Type.GetTypeCode(type);
#endif
public static MethodInfo GetPublicInstanceMethod(this Type type, string name, Type[] types)
{
#if NETSTANDARD1_3 || NETCOREAPP1_0
var method = type.GetMethod(name, types);
return (method?.IsPublic == true && !method.IsStatic) ? method : null;
#else
return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public, null, types, null);
#endif
}
}
}
| 31.773196 | 106 | 0.609345 | [
"MIT"
] | JTOne123/anet | Anet.Data/Dapper/TypeExtensions.cs | 3,084 | 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.HybridCompute
{
/// <summary>
/// A private endpoint connection
/// API Version: 2021-01-28-preview.
/// </summary>
[AzureNativeResourceType("azure-native:hybridcompute:PrivateEndpointConnection")]
public partial class PrivateEndpointConnection : Pulumi.CustomResource
{
/// <summary>
/// The name of the resource
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Resource properties.
/// </summary>
[Output("properties")]
public Output<Outputs.PrivateEndpointConnectionPropertiesResponse> Properties { get; private set; } = null!;
/// <summary>
/// The system meta data relating to this resource.
/// </summary>
[Output("systemData")]
public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!;
/// <summary>
/// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a PrivateEndpointConnection 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 PrivateEndpointConnection(string name, PrivateEndpointConnectionArgs args, CustomResourceOptions? options = null)
: base("azure-native:hybridcompute:PrivateEndpointConnection", name, args ?? new PrivateEndpointConnectionArgs(), MakeResourceOptions(options, ""))
{
}
private PrivateEndpointConnection(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:hybridcompute:PrivateEndpointConnection", 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:hybridcompute:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:hybridcompute/v20200815preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:hybridcompute/v20200815preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-native:hybridcompute/v20210128preview:PrivateEndpointConnection"},
new Pulumi.Alias { Type = "azure-nextgen:hybridcompute/v20210128preview:PrivateEndpointConnection"},
},
};
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 PrivateEndpointConnection 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 PrivateEndpointConnection Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new PrivateEndpointConnection(name, id, options);
}
}
public sealed class PrivateEndpointConnectionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the private endpoint connection.
/// </summary>
[Input("privateEndpointConnectionName")]
public Input<string>? PrivateEndpointConnectionName { get; set; }
/// <summary>
/// Resource properties.
/// </summary>
[Input("properties")]
public Input<Inputs.PrivateEndpointConnectionPropertiesArgs>? Properties { get; set; }
/// <summary>
/// The name of the resource group. The name is case insensitive.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the Azure Arc PrivateLinkScope resource.
/// </summary>
[Input("scopeName", required: true)]
public Input<string> ScopeName { get; set; } = null!;
public PrivateEndpointConnectionArgs()
{
}
}
}
| 43.368 | 159 | 0.631249 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/HybridCompute/PrivateEndpointConnection.cs | 5,421 | C# |
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using GeneticSharp.Domain.Chromosomes;
namespace GeneticSharp.Domain.Crossovers
{
/// <summary>
/// Cycle Crossover (CX).
/// <remarks>
/// The Cycle Crossover (CX) proposed by Oliver builds offspring in such a way that each
/// city (and its position) comes from one of the parents.
/// <see href="http://arxiv.org/ftp/arxiv/papers/1203/1203.3097.pdf">A Comparative Study of Adaptive Crossover Operators for Genetic Algorithms to Resolve the Traveling Salesman Problem</see>
/// <para>
/// The Cycle Crossover operator identifies a number of so-called cycles between two parent chromosomes.
/// Then, to form Child 1, cycle one is copied from parent 1, cycle 2 from parent 2, cycle 3 from parent 1, and so on.
/// <see ref="http://www.rubicite.com/Tutorials/GeneticAlgorithms/CrossoverOperators/CycleCrossoverOperator.aspx">Crossover Technique: Cycle Crossover</see>
/// </para>
/// </remarks>
/// </summary>
[DisplayName("Cycle (CX)")]
public class CycleCrossover : CrossoverBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="GeneticSharp.Domain.Crossovers.CycleCrossover"/> class.
/// </summary>
public CycleCrossover()
: base(2, 2)
{
IsOrdered = true;
}
#endregion
#region Methods
/// <summary>
/// Performs the cross with specified parents generating the children.
/// </summary>
/// <param name="parents">The parents chromosomes.</param>
/// <returns>The offspring (children) of the parents.</returns>
protected override IList<IChromosome> PerformCross(IList<IChromosome> parents)
{
var parent1 = parents[0];
var parent2 = parents[1];
if (parents.AnyHasRepeatedGene())
{
throw new CrossoverException(this, "The Cycle Crossover (CX) can be only used with ordered chromosomes. The specified chromosome has repeated genes.");
}
var cycles = new List<List<int>>();
var offspring1 = parent1.CreateNew();
var offspring2 = parent2.CreateNew();
var parent1Genes = parent1.GetGenes();
var parent2Genes = parent2.GetGenes();
// Search for the cycles.
for (int i = 0; i < parent1.Length; i++)
{
if (!cycles.SelectMany(p => p).Contains(i))
{
var cycle = new List<int>();
CreateCycle(parent1Genes, parent2Genes, i, cycle);
cycles.Add(cycle);
}
}
// Copy the cycles to the offpring.
for (int i = 0; i < cycles.Count; i++)
{
var cycle = cycles[i];
if (i % 2 == 0)
{
// Copy cycle index pair: values from Parent 1 and copied to Child 1, and values from Parent 2 will be copied to Child 2.
CopyCycleIndexPair(cycle, parent1Genes, offspring1, parent2Genes, offspring2);
}
else
{
// Copy cycle index odd: values from Parent 1 will be copied to Child 2, and values from Parent 1 will be copied to Child 1.
CopyCycleIndexPair(cycle, parent1Genes, offspring2, parent2Genes, offspring1);
}
}
return new List<IChromosome>() { offspring1, offspring2 };
}
/// <summary>
/// Copies the cycle index pair.
/// </summary>
/// <param name="cycle">The cycle.</param>
/// <param name="fromParent1Genes">From parent1 genes.</param>
/// <param name="toOffspring1">To offspring1.</param>
/// <param name="fromParent2Genes">From parent2 genes.</param>
/// <param name="toOffspring2">To offspring2.</param>
private static void CopyCycleIndexPair(IList<int> cycle, Gene[] fromParent1Genes, IChromosome toOffspring1, Gene[] fromParent2Genes, IChromosome toOffspring2)
{
int geneCycleIndex = 0;
for (int j = 0; j < cycle.Count; j++)
{
geneCycleIndex = cycle[j];
toOffspring1.ReplaceGene(geneCycleIndex, fromParent1Genes[geneCycleIndex]);
toOffspring2.ReplaceGene(geneCycleIndex, fromParent2Genes[geneCycleIndex]);
}
}
/// <summary>
/// Creates the cycle recursively.
/// </summary>
/// <param name="parent1Genes">The parent one's genes.</param>
/// <param name="parent2Genes">The parent two's genes.</param>
/// <param name="geneIndex">The current gene index.</param>
/// <param name="cycle">The cycle.</param>
private void CreateCycle(Gene[] parent1Genes, Gene[] parent2Genes, int geneIndex, List<int> cycle)
{
if (!cycle.Contains(geneIndex))
{
var parent2Gene = parent2Genes[geneIndex];
cycle.Add(geneIndex);
var newGeneIndex = parent1Genes.Select((g, i) => new { g.Value, Index = i }).First(g => g.Value.Equals(parent2Gene.Value));
if (geneIndex != newGeneIndex.Index)
{
CreateCycle(parent1Genes, parent2Genes, newGeneIndex.Index, cycle);
}
}
}
#endregion
}
} | 42.128788 | 195 | 0.575616 | [
"MIT"
] | JianLoong/GeneticSharp | src/GeneticSharp.Domain/Crossovers/CycleCrossover.cs | 5,563 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationPropertySymbol : CodeGenerationSymbol, IPropertySymbol
{
private readonly RefKind _refKind;
public ITypeSymbol Type { get; }
public NullableAnnotation NullableAnnotation => Type.NullableAnnotation;
public bool IsIndexer { get; }
public ImmutableArray<IParameterSymbol> Parameters { get; }
public ImmutableArray<IPropertySymbol> ExplicitInterfaceImplementations { get; }
public IMethodSymbol GetMethod { get; }
public IMethodSymbol SetMethod { get; }
public CodeGenerationPropertySymbol(
INamedTypeSymbol containingType,
ImmutableArray<AttributeData> attributes,
Accessibility declaredAccessibility,
DeclarationModifiers modifiers,
ITypeSymbol type,
RefKind refKind,
ImmutableArray<IPropertySymbol> explicitInterfaceImplementations,
string name,
bool isIndexer,
ImmutableArray<IParameterSymbol> parametersOpt,
IMethodSymbol getMethod,
IMethodSymbol setMethod)
: base(containingType?.ContainingAssembly, containingType, attributes, declaredAccessibility, modifiers, name)
{
this.Type = type;
this._refKind = refKind;
this.IsIndexer = isIndexer;
this.Parameters = parametersOpt.NullToEmpty();
this.ExplicitInterfaceImplementations = explicitInterfaceImplementations.NullToEmpty();
this.GetMethod = getMethod;
this.SetMethod = setMethod;
}
protected override CodeGenerationSymbol Clone()
{
var result = new CodeGenerationPropertySymbol(
this.ContainingType, this.GetAttributes(), this.DeclaredAccessibility,
this.Modifiers, this.Type, this.RefKind, this.ExplicitInterfaceImplementations,
this.Name, this.IsIndexer, this.Parameters,
this.GetMethod, this.SetMethod);
CodeGenerationPropertyInfo.Attach(result,
CodeGenerationPropertyInfo.GetIsNew(this),
CodeGenerationPropertyInfo.GetIsUnsafe(this),
CodeGenerationPropertyInfo.GetInitializer(this));
return result;
}
public override SymbolKind Kind => SymbolKind.Property;
public override void Accept(SymbolVisitor visitor)
=> visitor.VisitProperty(this);
public override TResult Accept<TResult>(SymbolVisitor<TResult> visitor)
=> visitor.VisitProperty(this);
public bool IsReadOnly => this.GetMethod != null && this.SetMethod == null;
public bool IsWriteOnly => this.GetMethod == null && this.SetMethod != null;
public new IPropertySymbol OriginalDefinition => this;
public RefKind RefKind => this._refKind;
public bool ReturnsByRef => this._refKind == RefKind.Ref;
public bool ReturnsByRefReadonly => this._refKind == RefKind.RefReadOnly;
public IPropertySymbol OverriddenProperty => null;
public bool IsWithEvents => false;
public ImmutableArray<CustomModifier> RefCustomModifiers => ImmutableArray<CustomModifier>.Empty;
public ImmutableArray<CustomModifier> TypeCustomModifiers => ImmutableArray<CustomModifier>.Empty;
}
}
| 39.849462 | 122 | 0.680788 | [
"MIT"
] | Acidburn0zzz/roslyn | src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationPropertySymbol.cs | 3,708 | C# |
namespace Common
{
public enum ProgrammingLanguage
{
ACRYLIC,
CRAYON,
PYTHON,
}
}
| 11.818182 | 36 | 0.484615 | [
"MIT"
] | blakeohare/crayon | Compiler/Common/ProgrammingLanguage.cs | 132 | C# |
using ElectricalAppliances.Console.TypeAAppliances;
using ElectricalAppliances.Console.TypeGAppliances;
namespace ElectricalAppliances.Console
{
public static class Program
{
public static void Main()
{
ITypeAPluggableAppliance appliance =
new FourOutletPowerStrip(
outlet1: new UPS(new Computer()),
outlet2: new HairDryer(),
outlet3: new TypeAToGAdapter(new UKCamera()),
outlet4: new ChildrensSafetyOutletPlug());
var room = new HotelRoom(appliance);
}
}
} | 30.8 | 65 | 0.603896 | [
"MIT"
] | AzureCloudMonk/codesamples-1 | ElectricalAppliances/src/ElectricalAppliances.Console/Program.cs | 618 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v9/services/offline_user_data_job_service.proto
// </auto-generated>
// Original file comments:
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
//
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace Google.Ads.GoogleAds.V9.Services {
/// <summary>
/// Service to manage offline user data jobs.
/// </summary>
public static partial class OfflineUserDataJobService
{
static readonly string __ServiceName = "google.ads.googleads.v9.services.OfflineUserDataJobService";
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context)
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (message is global::Google.Protobuf.IBufferMessage)
{
context.SetPayloadLength(message.CalculateSize());
global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter());
context.Complete();
return;
}
#endif
context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message));
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static class __Helper_MessageCache<T>
{
public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T));
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T>
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (__Helper_MessageCache<T>.IsBufferMessage)
{
return parser.ParseFrom(context.PayloadAsReadOnlySequence());
}
#endif
return parser.ParseFrom(context.PayloadAsNewBuffer());
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest> __Marshaller_google_ads_googleads_v9_services_CreateOfflineUserDataJobRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse> __Marshaller_google_ads_googleads_v9_services_CreateOfflineUserDataJobResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest> __Marshaller_google_ads_googleads_v9_services_GetOfflineUserDataJobRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob> __Marshaller_google_ads_googleads_v9_resources_OfflineUserDataJob = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest> __Marshaller_google_ads_googleads_v9_services_AddOfflineUserDataJobOperationsRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse> __Marshaller_google_ads_googleads_v9_services_AddOfflineUserDataJobOperationsResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest> __Marshaller_google_ads_googleads_v9_services_RunOfflineUserDataJobRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.LongRunning.Operation> __Marshaller_google_longrunning_Operation = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.LongRunning.Operation.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest, global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse> __Method_CreateOfflineUserDataJob = new grpc::Method<global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest, global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse>(
grpc::MethodType.Unary,
__ServiceName,
"CreateOfflineUserDataJob",
__Marshaller_google_ads_googleads_v9_services_CreateOfflineUserDataJobRequest,
__Marshaller_google_ads_googleads_v9_services_CreateOfflineUserDataJobResponse);
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest, global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob> __Method_GetOfflineUserDataJob = new grpc::Method<global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest, global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob>(
grpc::MethodType.Unary,
__ServiceName,
"GetOfflineUserDataJob",
__Marshaller_google_ads_googleads_v9_services_GetOfflineUserDataJobRequest,
__Marshaller_google_ads_googleads_v9_resources_OfflineUserDataJob);
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest, global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse> __Method_AddOfflineUserDataJobOperations = new grpc::Method<global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest, global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse>(
grpc::MethodType.Unary,
__ServiceName,
"AddOfflineUserDataJobOperations",
__Marshaller_google_ads_googleads_v9_services_AddOfflineUserDataJobOperationsRequest,
__Marshaller_google_ads_googleads_v9_services_AddOfflineUserDataJobOperationsResponse);
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest, global::Google.LongRunning.Operation> __Method_RunOfflineUserDataJob = new grpc::Method<global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest, global::Google.LongRunning.Operation>(
grpc::MethodType.Unary,
__ServiceName,
"RunOfflineUserDataJob",
__Marshaller_google_ads_googleads_v9_services_RunOfflineUserDataJobRequest,
__Marshaller_google_longrunning_Operation);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Ads.GoogleAds.V9.Services.OfflineUserDataJobServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of OfflineUserDataJobService</summary>
[grpc::BindServiceMethod(typeof(OfflineUserDataJobService), "BindService")]
public abstract partial class OfflineUserDataJobServiceBase
{
/// <summary>
/// Creates an offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [NotAllowlistedError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse> CreateOfflineUserDataJob(global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Returns the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob> GetOfflineUserDataJob(global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Adds operations to the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperations(global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Runs the offline user data job.
///
/// When finished, the long running operation will contain the processing
/// result or failure information, if any.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> RunOfflineUserDataJob(global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for OfflineUserDataJobService</summary>
public partial class OfflineUserDataJobServiceClient : grpc::ClientBase<OfflineUserDataJobServiceClient>
{
/// <summary>Creates a new client for OfflineUserDataJobService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public OfflineUserDataJobServiceClient(grpc::ChannelBase channel) : base(channel)
{
}
/// <summary>Creates a new client for OfflineUserDataJobService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public OfflineUserDataJobServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected OfflineUserDataJobServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected OfflineUserDataJobServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Creates an offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [NotAllowlistedError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse CreateOfflineUserDataJob(global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return CreateOfflineUserDataJob(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates an offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [NotAllowlistedError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse CreateOfflineUserDataJob(global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateOfflineUserDataJob, null, options, request);
}
/// <summary>
/// Creates an offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [NotAllowlistedError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse> CreateOfflineUserDataJobAsync(global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return CreateOfflineUserDataJobAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates an offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [NotAllowlistedError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse> CreateOfflineUserDataJobAsync(global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateOfflineUserDataJob, null, options, request);
}
/// <summary>
/// Returns the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob GetOfflineUserDataJob(global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetOfflineUserDataJob(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob GetOfflineUserDataJob(global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetOfflineUserDataJob, null, options, request);
}
/// <summary>
/// Returns the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob> GetOfflineUserDataJobAsync(global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetOfflineUserDataJobAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob> GetOfflineUserDataJobAsync(global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetOfflineUserDataJob, null, options, request);
}
/// <summary>
/// Adds operations to the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse AddOfflineUserDataJobOperations(global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return AddOfflineUserDataJobOperations(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Adds operations to the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse AddOfflineUserDataJobOperations(global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AddOfflineUserDataJobOperations, null, options, request);
}
/// <summary>
/// Adds operations to the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperationsAsync(global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return AddOfflineUserDataJobOperationsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Adds operations to the offline user data job.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse> AddOfflineUserDataJobOperationsAsync(global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AddOfflineUserDataJobOperations, null, options, request);
}
/// <summary>
/// Runs the offline user data job.
///
/// When finished, the long running operation will contain the processing
/// result or failure information, if any.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.LongRunning.Operation RunOfflineUserDataJob(global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return RunOfflineUserDataJob(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Runs the offline user data job.
///
/// When finished, the long running operation will contain the processing
/// result or failure information, if any.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.LongRunning.Operation RunOfflineUserDataJob(global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_RunOfflineUserDataJob, null, options, request);
}
/// <summary>
/// Runs the offline user data job.
///
/// When finished, the long running operation will contain the processing
/// result or failure information, if any.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> RunOfflineUserDataJobAsync(global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return RunOfflineUserDataJobAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Runs the offline user data job.
///
/// When finished, the long running operation will contain the processing
/// result or failure information, if any.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [HeaderError]()
/// [InternalError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> RunOfflineUserDataJobAsync(global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_RunOfflineUserDataJob, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected override OfflineUserDataJobServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new OfflineUserDataJobServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public static grpc::ServerServiceDefinition BindService(OfflineUserDataJobServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_CreateOfflineUserDataJob, serviceImpl.CreateOfflineUserDataJob)
.AddMethod(__Method_GetOfflineUserDataJob, serviceImpl.GetOfflineUserDataJob)
.AddMethod(__Method_AddOfflineUserDataJobOperations, serviceImpl.AddOfflineUserDataJobOperations)
.AddMethod(__Method_RunOfflineUserDataJob, serviceImpl.RunOfflineUserDataJob).Build();
}
/// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary>
/// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public static void BindService(grpc::ServiceBinderBase serviceBinder, OfflineUserDataJobServiceBase serviceImpl)
{
serviceBinder.AddMethod(__Method_CreateOfflineUserDataJob, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobRequest, global::Google.Ads.GoogleAds.V9.Services.CreateOfflineUserDataJobResponse>(serviceImpl.CreateOfflineUserDataJob));
serviceBinder.AddMethod(__Method_GetOfflineUserDataJob, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V9.Services.GetOfflineUserDataJobRequest, global::Google.Ads.GoogleAds.V9.Resources.OfflineUserDataJob>(serviceImpl.GetOfflineUserDataJob));
serviceBinder.AddMethod(__Method_AddOfflineUserDataJobOperations, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsRequest, global::Google.Ads.GoogleAds.V9.Services.AddOfflineUserDataJobOperationsResponse>(serviceImpl.AddOfflineUserDataJobOperations));
serviceBinder.AddMethod(__Method_RunOfflineUserDataJob, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V9.Services.RunOfflineUserDataJobRequest, global::Google.LongRunning.Operation>(serviceImpl.RunOfflineUserDataJob));
}
}
}
#endregion
| 60.065649 | 438 | 0.704852 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V9/Services/OfflineUserDataJobServiceGrpc.g.cs | 39,343 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Snowflake.Model.Database.Models;
namespace Snowflake.Model.Database.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20200505193855_WithValueType")]
partial class WithValueType
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.3");
modelBuilder.Entity("Snowflake.Model.Database.Models.ConfigurationProfileModel", b =>
{
b.Property<Guid>("ValueCollectionGuid")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ConfigurationSource")
.HasColumnType("TEXT");
b.HasKey("ValueCollectionGuid");
b.ToTable("ConfigurationProfiles");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.ConfigurationValueModel", b =>
{
b.Property<Guid>("Guid")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("OptionKey")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("SectionKey")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("ValueCollectionGuid")
.HasColumnType("TEXT");
b.Property<int>("ValueType")
.HasColumnType("INTEGER");
b.HasKey("Guid");
b.HasIndex("ValueCollectionGuid");
b.ToTable("ConfigurationValues");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.ControllerElementMappingCollectionModel", b =>
{
b.Property<Guid>("ProfileID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("ControllerID")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("DeviceName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("DriverType")
.HasColumnType("INTEGER");
b.Property<string>("ProfileName")
.HasColumnType("TEXT");
b.Property<int>("VendorID")
.HasColumnType("INTEGER");
b.HasKey("ProfileID");
b.ToTable("ControllerElementMappings");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.ControllerElementMappingModel", b =>
{
b.Property<Guid>("ProfileID")
.HasColumnType("TEXT");
b.Property<string>("LayoutElement")
.HasColumnType("TEXT");
b.Property<string>("DeviceCapability")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("ProfileID", "LayoutElement");
b.ToTable("MappedControllerElements");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.GameRecordConfigurationProfileModel", b =>
{
b.Property<Guid>("ProfileID")
.HasColumnType("TEXT");
b.Property<Guid>("GameID")
.HasColumnType("TEXT");
b.Property<string>("ConfigurationSource")
.HasColumnType("TEXT");
b.Property<string>("ProfileName")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("ProfileID", "GameID", "ConfigurationSource");
b.HasIndex("GameID");
b.HasIndex("ProfileID")
.IsUnique();
b.ToTable("GameRecordsConfigurationProfiles");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.PortDeviceEntryModel", b =>
{
b.Property<string>("OrchestratorName")
.HasColumnType("TEXT");
b.Property<string>("PlatformID")
.HasColumnType("TEXT");
b.Property<int>("PortIndex")
.HasColumnType("INTEGER");
b.Property<string>("ControllerID")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Driver")
.HasColumnType("INTEGER");
b.Property<Guid>("InstanceGuid")
.HasColumnType("TEXT");
b.Property<Guid>("ProfileGuid")
.HasColumnType("TEXT");
b.HasKey("OrchestratorName", "PlatformID", "PortIndex");
b.ToTable("PortDeviceEntries");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.RecordMetadataModel", b =>
{
b.Property<Guid>("RecordMetadataID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("MetadataKey")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("MetadataValue")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("RecordID")
.HasColumnType("TEXT");
b.HasKey("RecordMetadataID");
b.HasIndex("RecordID");
b.ToTable("Metadata");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.RecordModel", b =>
{
b.Property<Guid>("RecordID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("RecordType")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("RecordID");
b.ToTable("Records");
b.HasDiscriminator<string>("Discriminator").HasValue("RecordModel");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.FileRecordModel", b =>
{
b.HasBaseType("Snowflake.Model.Database.Models.RecordModel");
b.Property<string>("MimeType")
.IsRequired()
.HasColumnType("TEXT");
b.HasDiscriminator().HasValue("FileRecordModel");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.GameRecordModel", b =>
{
b.HasBaseType("Snowflake.Model.Database.Models.RecordModel");
b.Property<string>("PlatformID")
.IsRequired()
.HasColumnType("TEXT");
b.HasDiscriminator().HasValue("GameRecordModel");
});
modelBuilder.Entity("Snowflake.Model.Database.Models.ConfigurationValueModel", b =>
{
b.HasOne("Snowflake.Model.Database.Models.ConfigurationProfileModel", "Profile")
.WithMany("Values")
.HasForeignKey("ValueCollectionGuid")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Snowflake.Model.Database.Models.ControllerElementMappingModel", b =>
{
b.HasOne("Snowflake.Model.Database.Models.ControllerElementMappingCollectionModel", "Collection")
.WithMany("MappedElements")
.HasForeignKey("ProfileID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Snowflake.Model.Database.Models.GameRecordConfigurationProfileModel", b =>
{
b.HasOne("Snowflake.Model.Database.Models.GameRecordModel", "Game")
.WithMany("ConfigurationProfiles")
.HasForeignKey("GameID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Snowflake.Model.Database.Models.ConfigurationProfileModel", "Profile")
.WithOne()
.HasForeignKey("Snowflake.Model.Database.Models.GameRecordConfigurationProfileModel", "ProfileID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Snowflake.Model.Database.Models.RecordMetadataModel", b =>
{
b.HasOne("Snowflake.Model.Database.Models.RecordModel", "Record")
.WithMany("Metadata")
.HasForeignKey("RecordID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.898917 | 122 | 0.474709 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SnowflakePowered/snowflake | src/Snowflake.Framework/Model/Database/Migrations/20200505193855_WithValueType.Designer.cs | 10,223 | C# |
using System.Reflection;
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("AWSSDK.SimpleNotificationService")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Simple Notification Service. Amazon Simple Notification Service (Amazon SNS) is a fast, flexible, fully managed push messaging service. Amazon SNS makes it simple and cost-effective to push notifications to Apple, Google, Fire OS, and Windows devices, as well as Android devices in China with Baidu Cloud Push. You can also use SNS to push notifications to internet connected smart devices, as well as other distributed services.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.5.1.4")] | 56.09375 | 517 | 0.762117 | [
"Apache-2.0"
] | altso/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/SimpleNotificationService/Properties/AssemblyInfo.cs | 1,795 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\mfidl.h(3028,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[Guid("545b3a48-3283-4f62-866f-a62d8f598f9f"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IMFVideoSampleAllocatorEx : IMFVideoSampleAllocator
{
// IMFVideoSampleAllocator
[PreserveSig]
new HRESULT SetDirectXManager(/* [unique][in] */ [MarshalAs(UnmanagedType.IUnknown)] object pManager);
[PreserveSig]
new HRESULT UninitializeSampleAllocator();
[PreserveSig]
new HRESULT InitializeSampleAllocator(/* [in] */ uint cRequestedFrames, /* [in] */ IMFMediaType pMediaType);
[PreserveSig]
new HRESULT AllocateSample(/* [out] */ out IMFSample ppSample);
// IMFVideoSampleAllocatorEx
[PreserveSig]
HRESULT InitializeSampleAllocatorEx(/* [annotation] _In_ */ uint cInitialSamples, /* [annotation] _In_ */ uint cMaximumSamples, /* [annotation] _In_opt_ */ IMFAttributes pAttributes, /* [annotation] _In_ */ IMFMediaType pMediaType);
}
}
| 41.607143 | 240 | 0.68412 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/IMFVideoSampleAllocatorEx.cs | 1,167 | C# |
namespace LightningDB
{
/// <summary>
/// Transaction open mode
/// </summary>
public enum TransactionBeginFlags
{
/// <summary>
/// Normal mode
/// </summary>
None = 0,
/// <summary>
/// MDB_RDONLY. Open the environment in read-only mode.
/// No write operations will be allowed.
/// MDB will still modify the lock file - except on read-only filesystems, where MDB does not use locks.
/// </summary>
ReadOnly = 0x20000
}
}
| 25.333333 | 112 | 0.550752 | [
"MIT"
] | bradserbu/mylonite-net | lib/lightning.net/src/LightningDB/TransactionBeginFlags.cs | 534 | C# |
using System.Reflection;
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("MSBuildCodeMetrics.JetBrains")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MSBuildCodeMetrics.JetBrains")]
[assembly: AssemblyCopyright("Copyright © 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("cb1da39c-c9e9-42a3-ae0a-6f4d13e1e60e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.583333 | 85 | 0.727719 | [
"MIT"
] | ericlemes/MSBuildCodeMetrics | src/MSBuildCodeMetrics.JetBrains/Properties/AssemblyInfo.cs | 1,428 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Nebulator.Device")]
[assembly: AssemblyDescription("Nebulator Device")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Nebulator")]
// Version information is supplied by CommonAssemblyInfo.cs.
| 31.181818 | 60 | 0.80758 | [
"MIT"
] | kant/Nebulator | Device/Properties/AssemblyInfo.cs | 345 | C# |
using System.IO;
using UnityEditor;
using UnityEngine;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
public class DatasetGenerator : EditorWindow
{
[MenuItem("Dataset generator", menuItem = "Neural network/Dataset generator")]
public static void CreateWindow()
{
GetWindow<DatasetGenerator>("Dataset generator");
}
private readonly Color32 _clearColor = new Color32(204, 255, 254, 255);
private FigureDatabase _database;
private Dataset _dataset;
private string _datasetPath;
private bool DatasetHasUnsavedChanged
{
get => hasUnsavedChanges;
set => hasUnsavedChanges = value;
}
private bool _datasetHasIrrevocableChanges;
private string[] _figureNames;
private int? _selectedFigureIndex;
private readonly float _drawZonePadding = 10.0f;
private readonly float _drawZoneThreshold = 5.0f;
private RectInt _textureRect;
private Texture2D _texture;
private Color32[] _clearArray;
private bool _drawInputCollecting;
private readonly List<Vector2Int> _points = new List<Vector2Int>();
private Pen _editorPen;
private Pen _bufferPen;
private readonly BitBuffer _figureBuffer = new BitBuffer(32, 32);
private readonly float _toolsMaxHeight = 165.0f;
private Vector2 _toolsScrollPosition;
private FigureRecognizer _recognizer;
private bool _useRecognizer;
private bool _useFigureRotator;
private float[] _angles = new float[] { 15.0f, -15.0f };
private readonly Stack<int> _figureAddingHistory = new Stack<int>();
private int _figureAddedAfterSave;
private void Awake()
{
_texture = new Texture2D(1, 1, TextureFormat.RGBA32, false)
{
filterMode = FilterMode.Point,
hideFlags = HideFlags.HideAndDontSave,
wrapMode = TextureWrapMode.Clamp
};
_textureRect = new RectInt(0, 0, 1, 1);
}
private void OnDestroy()
{
DestroyImmediate(_texture);
if (_recognizer != null)
{
_recognizer.Dispose();
}
}
private void OnGUI()
{
DatabaseEditor();
if (_database != null)
{
DatasetEditor();
}
if (_dataset != null)
{
ToolsEditor();
FigureSelector();
if (_selectedFigureIndex == null)
{
EditorGUILayout.LabelField("No selected figure");
return;
}
FigureInformation();
FigureDrawZone();
}
}
public override void SaveChanges()
{
base.SaveChanges();
SaveDataset();
}
private void DatabaseEditor()
{
FigureDatabase database = (FigureDatabase)EditorGUILayout.ObjectField(
"Figure database",
_database,
typeof(FigureDatabase),
allowSceneObjects: false
);
if (database != _database)
{
SetDatabase(database);
}
}
private void SetDatabase(FigureDatabase database)
{
_useRecognizer = false;
if (_database != null && _recognizer != null)
{
_recognizer.Dispose();
_recognizer = null;
}
SetDataset(dataset: null, path: null);
_database = database;
if (database == null)
{
return;
}
if (_database.LoadNeuralNetwork() != null)
{
_recognizer = new FigureRecognizer(_database);
}
int count = _database.GetFiguresCount();
_figureNames = new string[count];
for (int i = 0; i < count; i++)
{
Figure figure = _database.GetFigure(i);
_figureNames[i] = $"{figure.Name} (id: {i})";
}
if (count == 0)
{
_selectedFigureIndex = null;
}
else
{
_selectedFigureIndex = 0;
}
}
private void DatasetEditor()
{
using (new EditorGUILayout.HorizontalScope())
{
if (string.IsNullOrWhiteSpace(_datasetPath))
{
EditorGUILayout.LabelField("No dataset");
}
else
{
EditorGUILayout.PrefixLabel("Dataset path");
EditorGUILayout.LabelField(new GUIContent(_datasetPath, _datasetPath));
if (GUILayout.Button("Save as", GUILayout.MaxWidth(60.0f)))
{
SaveDatasetAs();
}
using (new EditorGUI.DisabledGroupScope(!DatasetHasUnsavedChanged))
{
if (GUILayout.Button("Save", GUILayout.MaxWidth(45.0f)))
{
if (string.IsNullOrWhiteSpace(_datasetPath))
{
SaveDatasetAs();
}
SaveDataset();
}
}
}
if (GUILayout.Button("New", GUILayout.MaxWidth(45.0f)))
{
CreateDataset();
}
if (GUILayout.Button("Load", GUILayout.MaxWidth(45.0f)))
{
LoadDataset();
}
}
}
private void CreateDataset()
{
string path = EditorUtility.SaveFilePanel("Save dataset", Application.dataPath, "Dataset", "dataset");
if (string.IsNullOrWhiteSpace(path))
{
return;
}
SetDataset(new Dataset(_database), path);
SaveDataset();
}
private void SaveDatasetAs()
{
string path = EditorUtility.SaveFilePanel("Save dataset", Application.dataPath, "Dataset", "dataset");
if (string.IsNullOrWhiteSpace(path))
{
return;
}
_datasetPath = path;
SaveDataset();
}
private void SaveDataset()
{
try
{
Dataset.SaveToFile(_dataset, _datasetPath);
_figureAddedAfterSave = 0;
DatasetHasUnsavedChanged = false;
_datasetHasIrrevocableChanges = false;
}
catch (Exception exception)
{
Debug.LogError($"Failed save. Error: {exception.Message}.");
}
}
private void LoadDataset()
{
string path = EditorUtility.OpenFilePanel("Load dataset", Application.dataPath, "dataset");
if (string.IsNullOrWhiteSpace(path))
{
return;
}
try
{
Dataset loadedDataset = Dataset.LoadFromFile(path);
if (loadedDataset.DatabaseId != _database.Id)
{
bool ok = EditorUtility.DisplayDialog(
"Wrong id",
"The dataset contains an identifier for another database. Change dataset id?",
"Change",
"Cancel"
);
if (ok)
{
SetDataset(Dataset.CopyForDatabase(_database, loadedDataset), path);
}
else
{
return;
}
}
else
{
SetDataset(loadedDataset, path);
}
}
catch (Exception exception)
{
Debug.LogError($"Failed load. Error: {exception.Message}.");
}
}
private void SetDataset(Dataset dataset, string path)
{
_dataset = dataset;
_datasetPath = path;
_figureAddedAfterSave = 0;
DatasetHasUnsavedChanged = false;
_datasetHasIrrevocableChanges = false;
_figureAddingHistory.Clear();
}
private void ToolsEditor()
{
EditorGUILayout.LabelField("Tools");
float scrollHeight = Mathf.Clamp(0.3f * position.height, 0.0f, _toolsMaxHeight);
var scrollView = new EditorGUILayout.ScrollViewScope(_toolsScrollPosition, GUILayout.Height(scrollHeight));
using (scrollView)
{
_toolsScrollPosition = scrollView.scrollPosition;
PensEditor();
RecognizerEditor();
FigureRotatorEditor();
}
}
private void PensEditor()
{
_editorPen = EditorGUILayout.ObjectField(
new GUIContent("Editor pen"),
_editorPen,
typeof(Pen),
allowSceneObjects: false
) as Pen;
_bufferPen = EditorGUILayout.ObjectField(
new GUIContent("Dataset pen"),
_bufferPen,
typeof(Pen),
allowSceneObjects: false
) as Pen;
}
private void RecognizerEditor()
{
if (_recognizer == null)
{
return;
}
_useRecognizer = EditorGUILayout.BeginToggleGroup("Recognizer", _useRecognizer);
EditorGUI.indentLevel++;
_recognizer.Threshold = EditorGUILayout.FloatField("Threshold", _recognizer.Threshold);
EditorGUI.indentLevel--;
EditorGUILayout.EndToggleGroup();
}
private void FigureRotatorEditor()
{
_useFigureRotator = EditorGUILayout.BeginToggleGroup("Figure rotator", _useFigureRotator);
EditorGUI.indentLevel++;
int length = EditorGUILayout.IntField("Angles count", _angles.Length);
if (length != _angles.Length)
{
_angles = new float[length];
}
for (int i = 0; i < length; i++)
{
_angles[i] = EditorGUILayout.FloatField($"Angle {i}", _angles[i]);
}
EditorGUI.indentLevel--;
EditorGUILayout.EndToggleGroup();
}
private void FigureSelector()
{
if (_figureNames.Length == 0)
{
EditorGUILayout.LabelField("No figures in database");
return;
}
using (new GUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Figure");
_selectedFigureIndex = EditorGUILayout.Popup(_selectedFigureIndex.Value, _figureNames);
}
}
private void FigureInformation()
{
using (new GUILayout.HorizontalScope())
{
Figure figure = _database.GetFigure(_selectedFigureIndex.Value);
Rect padding = GUILayoutUtility.GetRect(5.0f, 100.0f, GUILayout.Width(5.0f), GUILayout.Height(100.0f));
Rect previewRect = GUILayoutUtility.GetRect(
100.0f,
100.0f,
GUILayout.Width(100.0f),
GUILayout.Height(100.0f)
);
EditorGUI.DrawRect(previewRect, Color.gray);
if (figure.Sprite != null)
{
Texture texture = figure.Sprite.texture;
Rect textureCoords = figure.Sprite.GetTextureCoords();
GUI.DrawTextureWithTexCoords(previewRect, figure.Sprite.texture, textureCoords);
}
using (new GUILayout.VerticalScope(GUILayout.Height(100.0f)))
{
EditorGUILayout.LabelField($"Id: {_selectedFigureIndex.Value}");
EditorGUILayout.LabelField($"Name: {figure.Name}");
int countInDataset = _dataset.Elements.Count(element => element.Id == _selectedFigureIndex.Value);
EditorGUILayout.LabelField($"Count in dataset: {countInDataset}");
GUILayout.FlexibleSpace();
EditorGUI.BeginDisabledGroup(_figureAddingHistory.Count == 0);
if (GUILayout.Button("Undo figure adding"))
{
UndoFigureAdding();
}
EditorGUI.EndDisabledGroup();
}
}
}
private void UndoFigureAdding()
{
if (_figureAddingHistory.Count == 0)
{
return;
}
if (_figureAddedAfterSave == 0)
{
DatasetHasUnsavedChanged = true;
_datasetHasIrrevocableChanges = true;
}
else
{
_figureAddedAfterSave--;
if (!_datasetHasIrrevocableChanges)
{
DatasetHasUnsavedChanged = _figureAddedAfterSave != 0;
}
}
int elementCount = _figureAddingHistory.Pop();
for (int i = 0; i < elementCount; i++)
{
_dataset.Elements.RemoveAt(_dataset.Elements.Count - 1);
}
}
private void FigureDrawZone()
{
if (_editorPen == null || _bufferPen == null)
{
EditorGUILayout.LabelField("No pen");
return;
}
Rect lastRect = GUILayoutUtility.GetLastRect();
Vector2 offset = new Vector2(
0.0f,
lastRect.y + lastRect.height + _drawZonePadding
);
Rect zoneRect = new Rect(
offset.x,
offset.y,
position.width,
position.height - offset.y
);
if (zoneRect.height <= _drawZoneThreshold)
{
return;
}
if (Event.current.type == EventType.Repaint)
{
if (_texture.width != (int)zoneRect.width || _texture.height != (int)zoneRect.height)
{
ResizeTexture((int)zoneRect.width, (int)zoneRect.height);
}
}
CollectDrawInput(zoneRect);
GUI.DrawTexture(zoneRect, _texture);
}
private void ResizeTexture(int width, int height)
{
_textureRect = new RectInt(0, 0, width, height);
_texture.Resize(width, height);
ClearTexture();
}
private void ClearTexture()
{
int size = _texture.width * _texture.height;
if (_clearArray == null || _clearArray.Length != size)
{
_clearArray = new Color32[size];
for (int y = 0; y < _texture.height; y++)
{
int offset = y * _texture.width;
for (int x = 0; x < _texture.width; x++)
{
_clearArray[offset + x] = _clearColor;
}
}
}
_texture.SetPixels32(_clearArray);
_texture.Apply();
}
private void CollectDrawInput(in Rect drawZone)
{
Vector2Int point = MousePositionToTexture(drawZone);
switch (Event.current.type)
{
case EventType.MouseDown:
if (_textureRect.Contains(point))
{
StartDrawing();
}
break;
case EventType.MouseUp:
if (_drawInputCollecting)
{
EndDrawing();
}
break;
}
if (_drawInputCollecting)
{
if (!_textureRect.Contains(point))
{
return;
}
if (_points.Count == 0)
{
_editorPen.DrawDot(point, _texture.SetPixel, Color.black, _textureRect);
}
else if (_points.Last() == point)
{
return;
}
else
{
_editorPen.DrawLine(_points.Last(), point, _texture.SetPixel, Color.black, _textureRect);
}
_points.Add(point);
_texture.Apply();
if (Event.current.type != EventType.Repaint)
{
Repaint();
}
}
}
private Vector2Int MousePositionToTexture(in Rect drawZone)
{
Vector2 mousePosition = Event.current.mousePosition;
Vector2Int point = new Vector2Int((int)mousePosition.x, (int)mousePosition.y);
point.x -= (int)drawZone.position.x;
point.y -= (int)drawZone.position.y;
point.y = (int)drawZone.height - point.y;
return point;
}
private void StartDrawing()
{
_drawInputCollecting = true;
}
private void EndDrawing()
{
_drawInputCollecting = false;
ProcessFigure();
_points.Clear();
_figureBuffer.Clear();
ClearTexture();
Repaint();
}
private void ProcessFigure()
{
if (_points.Count < 2)
{
return;
}
_figureBuffer.LineLoop(_bufferPen, _points);
if (_useRecognizer)
{
Figure figure = _recognizer.Recognize(_figureBuffer, out int figureIndex);
if (figure != null && figureIndex == _selectedFigureIndex.Value)
{
return;
}
}
int elementCount = 1;
AddFigureInDataset();
if (_useFigureRotator && _angles.Length != 0)
{
foreach (List<Vector2Int> rotatedPoints in FigureRotator.Rotations(_points, _angles))
{
_figureBuffer.Clear();
_figureBuffer.LineLoop(_bufferPen, rotatedPoints);
AddFigureInDataset();
elementCount++;
}
}
_figureAddingHistory.Push(elementCount);
}
private void AddFigureInDataset()
{
DatasetHasUnsavedChanged = true;
_figureAddedAfterSave++;
_dataset.Elements.Add(new DatasetElement(
_selectedFigureIndex.Value,
_figureBuffer.ToOneLine()
));
}
}
| 26.822257 | 115 | 0.533883 | [
"MIT"
] | Trequend/CloudKeeper | Assets/Scripts/Editor/DatasetGenerator.cs | 17,354 | C# |
using System;
using UnityEngine;
namespace YsoCorp {
public class ADataManager : YCBehaviour {
private int _version = 1;
private string _prefix = "";
public ADataManager(string p = "", int v = 1) {
this._prefix = p;
this._version = v;
}
public string GetKey(string key) {
return this._prefix + key + this._version;
}
public bool HasKey(string key) {
return PlayerPrefs.HasKey(this.GetKey(key));
}
public void DeleteAll(bool forceDeletion = false) {
#if UNITY_EDITOR
PlayerPrefs.DeleteAll();
#endif
if (forceDeletion == true) {
PlayerPrefs.DeleteAll();
}
}
public void DeleteKey(string key) {
PlayerPrefs.DeleteKey(this.GetKey(key));
}
public void ForceSave() {
PlayerPrefs.Save();
}
// INT
public int GetInt(string key, int defaultValue = 0) {
return PlayerPrefs.GetInt(this.GetKey(key), defaultValue);
}
public void SetInt(string key, int value) {
PlayerPrefs.SetInt(this.GetKey(key), value);
}
// BOOL
public bool GetBool(string key, bool defaultValue = false) {
return PlayerPrefs.GetInt(this.GetKey(key), defaultValue ? 1 : 0) == 1;
}
public void SetBool(string key, bool value) {
PlayerPrefs.SetInt(this.GetKey(key), value ? 1 : 0);
}
// FLOAT
public float GetFloat(string key, float defaultValue = 0) {
return PlayerPrefs.GetFloat(this.GetKey(key), defaultValue);
}
public void SetFloat(string key, float value) {
PlayerPrefs.SetFloat(this.GetKey(key), value);
}
// STRING
public string GetString(string key, string value = "") {
return PlayerPrefs.GetString(this.GetKey(key), value);
}
public void SetString(string key, string value) {
PlayerPrefs.SetString(this.GetKey(key), value);
}
// OBJECT
public T GetObject<T>(string key, string value = "{}") {
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(PlayerPrefs.GetString(this.GetKey(key), value));
}
public void SetObject<T>(string key, T value) {
PlayerPrefs.SetString(this.GetKey(key), Newtonsoft.Json.JsonConvert.SerializeObject(value));
}
// ARRAY
public T[] GetArray<T>(string key, string value = "[]") {
return this.GetObject<T[]>(key, value);
}
public void SetArray<T>(string key, T[] value) {
this.SetObject(key, value);
}
}
} | 30.175824 | 116 | 0.563729 | [
"MIT"
] | MathieuGery/HC2-Knuckles | Assets/GameUtils/Scripts/Abstracts/ADataManager.cs | 2,746 | C# |
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using ACT.SpecialSpellTimer.Config.Models;
using ACT.SpecialSpellTimer.Image;
using ACT.SpecialSpellTimer.Sound;
using ACT.SpecialSpellTimer.Utility;
using FFXIV.Framework.Bridge;
using FFXIV.Framework.Common;
using FFXIV.Framework.Extensions;
using FFXIV.Framework.WPF.Views;
namespace ACT.SpecialSpellTimer.Models
{
/// <summary>
/// スペルタイマ
/// </summary>
[Serializable]
[XmlType(TypeName = "SpellTimer")]
public class Spell :
TreeItemBase,
IDisposable,
IFilterizableTrigger
{
[XmlIgnore]
public override ItemTypes ItemType => ItemTypes.Spell;
#region ITrigger
public void MatchTrigger(string logLine)
=> SpellsController.Instance.MatchCore(this, logLine);
#endregion ITrigger
#region ITreeItem
private bool enabled = false;
[XmlIgnore]
public override string DisplayText => this.SpellTitle;
[XmlIgnore]
public override int SortPriority { get; set; }
[XmlIgnore]
public override bool IsExpanded
{
get => false;
set { }
}
public override bool Enabled
{
get => this.enabled;
set => this.SetProperty(ref this.enabled, value);
}
[XmlIgnore]
public override ICollectionView Children => null;
#endregion ITreeItem
[XmlIgnore]
public volatile bool UpdateDone;
public Spell()
{
}
private bool isCircleStyle;
public bool IsCircleStyle
{
get => this.isCircleStyle;
set
{
if (this.SetProperty(ref this.isCircleStyle, value))
{
this.RaisePropertyChanged(nameof(this.IsStandardStyle));
this.RaisePropertyChanged(nameof(this.DefaultSpellMargin));
}
}
}
private VerticalAlignment titleVerticalAlignmentInCircle = VerticalAlignment.Center;
public VerticalAlignment TitleVerticalAlignmentInCircle
{
get => this.titleVerticalAlignmentInCircle;
set => this.SetProperty(ref this.titleVerticalAlignmentInCircle, value);
}
[XmlIgnore]
public bool IsStandardStyle => !this.isCircleStyle;
private double left, top;
public double Left
{
get => this.left;
set
{
if (this.SetProperty(ref this.left, Math.Round(value)))
{
}
}
}
public double Top
{
get => this.top;
set
{
if (this.SetProperty(ref this.top, Math.Round(value)))
{
}
}
}
private long id;
public long ID
{
get => this.id;
set => this.SetProperty(ref id, value);
}
private Guid guid = Guid.NewGuid();
public Guid Guid
{
get => this.guid;
set => this.SetProperty(ref this.guid, value);
}
private Guid panelID = Guid.Empty;
public Guid PanelID
{
get => this.panelID;
set => this.SetProperty(ref this.panelID, value);
}
[XmlIgnore]
public SpellPanel Panel => SpellPanelTable.Instance.Table.FirstOrDefault(x => x.ID == this.PanelID);
private static readonly Thickness HorizontalDefaultMargin = new Thickness(0, 0, 10, 0);
private static readonly Thickness VerticalDefaultMarginStandard = new Thickness(0, 2, 0, 10);
private static readonly Thickness VerticalDefaultMarginCircle = new Thickness(0, 0, 0, 10);
[XmlIgnore]
public Thickness DefaultSpellMargin
{
get
{
var result = new Thickness();
var panel = this.Panel;
if (panel == null)
{
return result;
}
if (!panel.EnabledAdvancedLayout)
{
result = !panel.Horizontal ?
getVerticalMargin() :
HorizontalDefaultMargin;
}
else
{
if (panel.IsStackLayout)
{
switch (panel.StackPanelOrientation)
{
case Orientation.Horizontal:
result = HorizontalDefaultMargin;
break;
case Orientation.Vertical:
result = getVerticalMargin();
break;
}
}
}
return result;
// Standard スタイルでは互換性のため上のマージン2pxを残している
// Circle スタイルでは2pxのマージンを廃止したため使い分ける
Thickness getVerticalMargin()
=> this.IsCircleStyle ? VerticalDefaultMarginCircle : VerticalDefaultMarginStandard;
}
}
public void RaiseSpellMarginChanged()
=> this.RaisePropertyChanged(nameof(this.DefaultSpellMargin));
private string panelName = string.Empty;
[XmlElement(ElementName = "Panel")]
public string PanelName
{
get
{
if (this.PanelID == Guid.Empty)
{
return this.panelName;
}
return this.Panel?.PanelName;
}
set => this.panelName = value;
}
private bool isDesignMode = false;
[XmlIgnore]
public bool IsDesignMode
{
get => this.isDesignMode;
set => this.SetProperty(ref this.isDesignMode, value);
}
private bool isTest = false;
/// <summary>
/// 動作テスト用のフラグ
/// </summary>
/// <remarks>擬似的にマッチさせるで使用するテストモード用フラグ</remarks>
[XmlIgnore]
public bool IsTest
{
get => this.isTest;
set => this.SetProperty(ref this.isTest, value);
}
private string spellTitle = string.Empty;
/// <summary>
/// スペルタイトル(スペル表示名)
/// </summary>
public string SpellTitle
{
get => this.spellTitle;
set
{
if (this.SetProperty(ref this.spellTitle, value))
{
this.RaisePropertyChanged(nameof(this.DisplayText));
}
}
}
private string spellTitleReplaced = string.Empty;
[XmlIgnore]
public string SpellTitleReplaced
{
get => this.spellTitleReplaced;
set => this.SetProperty(ref this.spellTitleReplaced, value);
}
#region Keywords & Regex compiler
[XmlIgnore]
public bool IsRealtimeCompile { get; set; } = false;
private bool regexEnabled;
private string keyword;
private string keywordForExtend1;
private string keywordForExtend2;
private string keywordForExtend3;
public bool RegexEnabled
{
get => this.regexEnabled;
set
{
if (this.SetProperty(ref this.regexEnabled, value))
{
this.KeywordReplaced = string.Empty;
this.KeywordForExtendReplaced1 = string.Empty;
this.KeywordForExtendReplaced2 = string.Empty;
this.KeywordForExtendReplaced3 = string.Empty;
if (this.IsRealtimeCompile)
{
var ex = this.CompileRegex();
if (ex != null)
{
ModernMessageBox.ShowDialog(
"Regex compile error ! This is invalid keyword.",
"Regex compiler",
MessageBoxButton.OK,
ex);
}
ex = this.CompileRegexExtend1();
if (ex != null)
{
ModernMessageBox.ShowDialog(
"Regex compile error ! This is invalid keyword.",
"Regex compiler",
MessageBoxButton.OK,
ex);
}
ex = this.CompileRegexExtend2();
if (ex != null)
{
ModernMessageBox.ShowDialog(
"Regex compile error ! This is invalid keyword.",
"Regex compiler",
MessageBoxButton.OK,
ex);
}
ex = this.CompileRegexExtend3();
if (ex != null)
{
ModernMessageBox.ShowDialog(
"Regex compile error ! This is invalid keyword.",
"Regex compiler",
MessageBoxButton.OK,
ex);
}
}
}
}
}
public string Keyword
{
get => this.keyword;
set
{
if (this.SetProperty(ref this.keyword, value))
{
this.KeywordReplaced = string.Empty;
if (this.IsRealtimeCompile)
{
var ex = this.CompileRegex();
if (ex != null)
{
ModernMessageBox.ShowDialog(
"Regex compile error ! This is invalid keyword.",
"Regex compiler",
MessageBoxButton.OK,
ex);
}
}
}
}
}
public string KeywordForExtend1
{
get => this.keywordForExtend1;
set
{
if (this.SetProperty(ref this.keywordForExtend1, value))
{
this.KeywordForExtendReplaced1 = string.Empty;
if (this.IsRealtimeCompile)
{
var ex = this.CompileRegexExtend1();
if (ex != null)
{
ModernMessageBox.ShowDialog(
"Regex compile error ! This is invalid keyword.",
"Regex compiler",
MessageBoxButton.OK,
ex);
}
}
}
}
}
public string KeywordForExtend2
{
get => this.keywordForExtend2;
set
{
if (this.SetProperty(ref this.keywordForExtend2, value))
{
this.KeywordForExtendReplaced2 = string.Empty;
if (this.IsRealtimeCompile)
{
var ex = this.CompileRegexExtend2();
if (ex != null)
{
ModernMessageBox.ShowDialog(
"Regex compile error ! This is invalid keyword.",
"Regex compiler",
MessageBoxButton.OK,
ex);
}
}
}
}
}
public string KeywordForExtend3
{
get => this.keywordForExtend3;
set
{
if (this.SetProperty(ref this.keywordForExtend3, value))
{
this.KeywordForExtendReplaced3 = string.Empty;
if (this.IsRealtimeCompile)
{
var ex = this.CompileRegexExtend3();
if (ex != null)
{
ModernMessageBox.ShowDialog(
"Regex compile error ! This is invalid keyword.",
"Regex compiler",
MessageBoxButton.OK,
ex);
}
}
}
}
}
/// <summary>
/// リキャスト時間
/// </summary>
public double RecastTime { get; set; } = 0;
private double delayToShow = 0;
/// <summary>
/// 表示までのディレイ
/// </summary>
public double DelayToShow
{
get => this.delayToShow;
set => this.SetProperty(ref this.delayToShow, value);
}
/// <summary>
/// 延長する時間1
/// </summary>
public double RecastTimeExtending1 { get; set; } = 0;
/// <summary>
/// 延長する時間2
/// </summary>
public double RecastTimeExtending2 { get; set; } = 0;
/// <summary>
/// 延長する時間3
/// </summary>
public double RecastTimeExtending3 { get; set; } = 0;
private bool overlapRecastTime;
/// <summary>
/// 元のリキャスト時間を超えて延長するか?
/// </summary>
public bool OverlapRecastTime
{
get => this.overlapRecastTime;
set => this.SetProperty(ref this.overlapRecastTime, value);
}
private bool isNotResetBarOnExtended = false;
/// <summary>
/// 延長したときにバーをリセットしない?
/// </summary>
public bool IsNotResetBarOnExtended
{
get => this.isNotResetBarOnExtended;
set => this.SetProperty(ref this.isNotResetBarOnExtended, value);
}
[XmlIgnore]
public string KeywordReplaced { get; set; }
[XmlIgnore]
public string KeywordForExtendReplaced1 { get; set; }
[XmlIgnore]
public string KeywordForExtendReplaced2 { get; set; }
[XmlIgnore]
public string KeywordForExtendReplaced3 { get; set; }
[XmlIgnore]
public Regex Regex { get; set; }
[XmlIgnore]
public Regex RegexForExtend1 { get; set; }
[XmlIgnore]
public Regex RegexForExtend2 { get; set; }
[XmlIgnore]
public Regex RegexForExtend3 { get; set; }
[XmlIgnore]
public string RegexPattern { get; set; }
[XmlIgnore]
public string RegexForExtendPattern1 { get; set; }
[XmlIgnore]
public string RegexForExtendPattern2 { get; set; }
[XmlIgnore]
public string RegexForExtendPattern3 { get; set; }
public Exception CompileRegex()
{
var pattern = string.Empty;
try
{
this.KeywordReplaced = TableCompiler.Instance.GetMatchingKeyword(
this.KeywordReplaced,
this.Keyword);
if (this.RegexEnabled)
{
pattern = this.KeywordReplaced.ToRegexPattern();
if (this.Regex == null ||
this.RegexPattern != pattern)
{
this.Regex = pattern.ToRegex();
this.RegexPattern = pattern;
}
}
else
{
this.Regex = null;
this.RegexPattern = string.Empty;
}
}
catch (Exception ex)
{
return ex;
}
return null;
}
public Exception CompileRegexExtend1()
{
var pattern = string.Empty;
try
{
this.KeywordForExtendReplaced1 = TableCompiler.Instance.GetMatchingKeyword(
this.KeywordForExtendReplaced1,
this.KeywordForExtend1);
if (this.RegexEnabled)
{
pattern = this.KeywordForExtendReplaced1.ToRegexPattern();
if (this.RegexForExtend1 == null ||
this.RegexForExtendPattern1 != pattern)
{
this.RegexForExtend1 = pattern.ToRegex();
this.RegexForExtendPattern1 = pattern;
}
}
else
{
this.RegexForExtend1 = null;
this.RegexForExtendPattern1 = string.Empty;
}
}
catch (Exception ex)
{
return ex;
}
return null;
}
public Exception CompileRegexExtend2()
{
var pattern = string.Empty;
try
{
this.KeywordForExtendReplaced2 = TableCompiler.Instance.GetMatchingKeyword(
this.KeywordForExtendReplaced2,
this.KeywordForExtend2);
if (this.RegexEnabled)
{
pattern = this.KeywordForExtendReplaced2.ToRegexPattern();
if (this.RegexForExtend2 == null ||
this.RegexForExtendPattern2 != pattern)
{
this.RegexForExtend2 = pattern.ToRegex();
this.RegexForExtendPattern2 = pattern;
}
}
else
{
this.RegexForExtend2 = null;
this.RegexForExtendPattern2 = string.Empty;
}
}
catch (Exception ex)
{
return ex;
}
return null;
}
public Exception CompileRegexExtend3()
{
var pattern = string.Empty;
try
{
this.KeywordForExtendReplaced3 = TableCompiler.Instance.GetMatchingKeyword(
this.KeywordForExtendReplaced3,
this.KeywordForExtend3);
if (this.RegexEnabled)
{
pattern = this.KeywordForExtendReplaced3.ToRegexPattern();
if (this.RegexForExtend3 == null ||
this.RegexForExtendPattern3 != pattern)
{
this.RegexForExtend3 = pattern.ToRegex();
this.RegexForExtendPattern3 = pattern;
}
}
else
{
this.RegexForExtend3 = null;
this.RegexForExtendPattern3 = string.Empty;
}
}
catch (Exception ex)
{
return ex;
}
return null;
}
#endregion Keywords & Regex compiler
/// <summary>
/// ※注意が必要な項目※
/// 昔の名残で項目名と異なる動作になっている。
/// プログレスバーの表示/非表示ではなく、スペル全体の表示/非表示を司る重要な項目として動作している
/// </summary>
private bool progressBarVisible = true;
public bool ProgressBarVisible
{
get => this.progressBarVisible;
set => this.SetProperty(ref this.progressBarVisible, value);
}
public FontInfo Font { get; set; } = FontInfo.DefaultFont;
public string FontColor { get; set; } = Colors.White.ToLegacy().ToHTML();
public string FontOutlineColor { get; set; } = Colors.Navy.ToLegacy().ToHTML();
private double warningTime = 0;
public double WarningTime
{
get => this.warningTime;
set => this.SetProperty(ref this.warningTime, value);
}
private bool changeFontColorsWhenWarning;
public bool ChangeFontColorsWhenWarning
{
get => this.changeFontColorsWhenWarning;
set => this.SetProperty(ref this.changeFontColorsWhenWarning, value);
}
public string WarningFontColor { get; set; } = Colors.White.ToLegacy().ToHTML();
public string WarningFontOutlineColor { get; set; } = Colors.Red.ToLegacy().ToHTML();
private bool changeFontColorWhenContainsMe;
public bool ChangeFontColorWhenContainsMe
{
get => this.changeFontColorWhenContainsMe;
set => this.SetProperty(ref this.changeFontColorWhenContainsMe, value);
}
private int barWidth;
public int BarWidth
{
get => this.barWidth;
set => this.SetProperty(ref this.barWidth, value);
}
private int barHeight;
public int BarHeight
{
get => this.barHeight;
set => this.SetProperty(ref this.barHeight, value);
}
public string BarColor { get; set; } = Colors.White.ToLegacy().ToHTML();
public string BarOutlineColor { get; set; } = Colors.Navy.ToLegacy().ToHTML();
private double barBlurRadius = 11;
public double BarBlurRadius
{
get => this.barBlurRadius;
set => this.SetProperty(ref this.barBlurRadius, value);
}
public string BackgroundColor { get; set; } = Colors.Black.ToLegacy().ToHTML();
public int BackgroundAlpha { get; set; } = 0;
[XmlIgnore]
public DateTime CompleteScheduledTime { get; set; }
private long displayNo;
public long DisplayNo
{
get => this.displayNo;
set => this.SetProperty(ref this.displayNo, value);
}
private bool dontHide;
public bool DontHide
{
get => this.dontHide;
set => this.SetProperty(ref this.dontHide, value);
}
private bool isHideInNotCombat;
public bool IsHideInNotCombat
{
get => this.isHideInNotCombat;
set => this.SetProperty(ref this.isHideInNotCombat, value);
}
public bool ExtendBeyondOriginalRecastTime { get; set; }
private bool hideSpellName;
public bool HideSpellName
{
get => this.hideSpellName;
set => this.SetProperty(ref this.hideSpellName, value);
}
private bool hideCounter;
public bool HideCounter
{
get => this.hideCounter;
set => this.SetProperty(ref this.hideCounter, value);
}
private bool isCounterToCenter = false;
public bool IsCounterToCenter
{
get => this.isCounterToCenter;
set
{
if (this.SetProperty(ref this.isCounterToCenter, value))
{
this.RaisePropertyChanged(nameof(this.CounterAlignment));
this.RaisePropertyChanged(nameof(this.SpellTitleColumnWidth));
this.RaisePropertyChanged(nameof(this.CounterColumnWidth));
}
}
}
[XmlIgnore]
public HorizontalAlignment CounterAlignment =>
this.isCounterToCenter ?
HorizontalAlignment.Center :
HorizontalAlignment.Right;
[XmlIgnore]
public GridLength SpellTitleColumnWidth =>
this.isCounterToCenter ?
GridLength.Auto :
new GridLength(1.0, GridUnitType.Star);
[XmlIgnore]
public GridLength CounterColumnWidth =>
this.isCounterToCenter ?
new GridLength(1.0, GridUnitType.Star) :
GridLength.Auto;
/// <summary>インスタンス化されたスペルか?</summary>
[XmlIgnore]
public bool IsInstance { get; set; }
private bool isReverse;
public bool IsReverse
{
get => this.isReverse;
set => this.SetProperty(ref this.isReverse, value);
}
public DateTime MatchDateTime { get; set; } = DateTime.MinValue;
[XmlIgnore]
public string MatchedLog { get; set; } = string.Empty;
private bool useHotbarRecastTime = false;
public bool UseHotbarRecastTime
{
get => this.useHotbarRecastTime;
set => this.SetProperty(ref this.useHotbarRecastTime, value);
}
private string hotbarName = string.Empty;
public string HotbarName
{
get => this.hotbarName;
set => this.SetProperty(ref this.hotbarName, value);
}
private bool reduceIconBrightness;
public bool ReduceIconBrightness
{
get => this.reduceIconBrightness;
set => this.SetProperty(ref this.reduceIconBrightness, value);
}
private string spellIcon = string.Empty;
public string SpellIcon
{
get => this.spellIcon;
set
{
if (this.SetProperty(ref this.spellIcon, value))
{
this.RaisePropertyChanged(nameof(this.SpellIconFullPath));
this.RaisePropertyChanged(nameof(this.SpellIconImage));
}
}
}
[XmlIgnore]
public string SpellIconFullPath =>
string.IsNullOrEmpty(this.SpellIcon) ?
string.Empty :
IconController.Instance.GetIconFile(this.SpellIcon)?.FullPath;
[XmlIgnore]
public BitmapSource SpellIconImage =>
string.IsNullOrEmpty(this.SpellIcon) ?
IconController.BlankBitmap :
IconController.Instance.GetIconFile(this.SpellIcon)?.BitmapImage;
private int spellIconSize = 24;
public int SpellIconSize
{
get => this.spellIconSize;
set => this.SetProperty(ref this.spellIconSize, value);
}
private bool isNotResetAtWipeout = false;
public bool IsNotResetAtWipeout
{
get => this.isNotResetAtWipeout;
set => this.SetProperty(ref this.isNotResetAtWipeout, value);
}
/// <summary>スペルが作用した対象</summary>
[XmlIgnore]
public string TargetName { get; set; } = string.Empty;
public bool TimeupHide { get; set; }
/// <summary>インスタンス化する</summary>
/// <remarks>表示テキストが異なる条件でマッチングした場合に当該スペルの新しいインスタンスを生成する</remarks>
public bool ToInstance { get; set; }
public double UpperLimitOfExtension { get; set; } = 0;
public double BlinkTime { get; set; } = 0;
public bool BlinkIcon { get; set; } = false;
public bool BlinkBar { get; set; } = false;
private int actualSortOrder = 0;
[XmlIgnore]
public int ActualSortOrder
{
get => this.actualSortOrder;
set => this.SetProperty(ref this.actualSortOrder, value);
}
private Visibility visibility = Visibility.Collapsed;
[XmlIgnore]
public Visibility Visibility
{
get => this.visibility;
set => this.SetProperty(ref this.visibility, value);
}
#region Filters & Conditions
private string jobFilter = string.Empty;
public string JobFilter
{
get => this.jobFilter;
set => this.SetProperty(ref this.jobFilter, value);
}
private string partyJobFilter = string.Empty;
public string PartyJobFilter
{
get => this.partyJobFilter;
set => this.SetProperty(ref this.partyJobFilter, value);
}
private string partyCompositionFilter = string.Empty;
public string PartyCompositionFilter
{
get => this.partyCompositionFilter;
set => this.SetProperty(ref this.partyCompositionFilter, value);
}
private string zoneFilter = string.Empty;
public string ZoneFilter
{
get => this.zoneFilter;
set => this.SetProperty(ref this.zoneFilter, value);
}
public Guid[] TimersMustRunningForStart { get; set; } = new Guid[0];
public Guid[] TimersMustStoppingForStart { get; set; } = new Guid[0];
private ExpressionFilter[] expressionFilters = new ExpressionFilter[]
{
new ExpressionFilter(),
new ExpressionFilter(),
new ExpressionFilter(),
new ExpressionFilter(),
};
[XmlArray("ExpressionFilter")]
[XmlArrayItem("expression")]
public ExpressionFilter[] ExpressionFilters
{
get => this.expressionFilters;
set => this.SetProperty(ref this.expressionFilters, value);
}
#endregion Filters & Conditions
#region Sequential TTS
/// <summary>
/// 同時再生を抑制してシーケンシャルにTTSを再生する
/// </summary>
public bool IsSequentialTTS { get; set; } = false;
public void Play(string tts, AdvancedNoticeConfig config, bool forceSync = false)
=> Spell.PlayCore(tts, this.IsSequentialTTS | forceSync, config, this);
public static void PlayCore(
string tts,
bool isSync,
AdvancedNoticeConfig noticeConfig,
ITrigger trigger)
{
if (string.IsNullOrEmpty(tts))
{
return;
}
if (noticeConfig == null)
{
SoundController.Instance.Play(tts);
return;
}
var isWave = false;
if (tts.EndsWith(".wav", StringComparison.OrdinalIgnoreCase) ||
tts.EndsWith(".wave", StringComparison.OrdinalIgnoreCase) ||
tts.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase))
{
isWave = true;
}
// waveサウンドはシンクロ再生しない
if (isWave)
{
noticeConfig.PlayWave(tts);
return;
}
// ゆっくりがいないならシンクロ再生はしない
if (!PlayBridge.Instance.IsAvailable ||
!isSync)
{
noticeConfig.Speak(tts);
return;
}
var priority = int.MaxValue;
if (trigger is Spell spell)
{
priority = (int)spell.DisplayNo;
}
noticeConfig.Speak(tts, true, priority);
}
#endregion Sequential TTS
#region to Notice
public string MatchTextToSpeak { get; set; } = string.Empty;
public AdvancedNoticeConfig MatchAdvancedConfig { get; set; } = new AdvancedNoticeConfig();
public double OverTime { get; set; } = 0;
public string OverTextToSpeak { get; set; } = string.Empty;
[XmlIgnore]
public bool OverDone { get; set; }
public AdvancedNoticeConfig OverAdvancedConfig { get; set; } = new AdvancedNoticeConfig();
public double BeforeTime { get; set; } = 0;
public string BeforeTextToSpeak { get; set; } = string.Empty;
[XmlIgnore]
public bool BeforeDone { get; set; }
public AdvancedNoticeConfig BeforeAdvancedConfig { get; set; } = new AdvancedNoticeConfig();
public string TimeupTextToSpeak { get; set; } = string.Empty;
[XmlIgnore]
public bool TimeupDone { get; set; }
public AdvancedNoticeConfig TimeupAdvancedConfig { get; set; } = new AdvancedNoticeConfig();
#endregion to Notice
#region to Notice wave files
[XmlIgnore]
private string matchSound = string.Empty;
[XmlIgnore]
private string overSound = string.Empty;
[XmlIgnore]
private string beforeSound = string.Empty;
[XmlIgnore]
private string timeupSound = string.Empty;
[XmlIgnore]
public string MatchSound { get => this.matchSound; set => this.matchSound = value; }
[XmlElement(ElementName = "MatchSound")]
public string MatchSoundToFile
{
get => Path.GetFileName(this.matchSound);
set
{
if (!string.IsNullOrEmpty(value))
{
this.matchSound = Path.Combine(SoundController.Instance.WaveDirectory, value);
}
}
}
[XmlIgnore]
public string OverSound { get => this.overSound; set => this.overSound = value; }
[XmlElement(ElementName = "OverSound")]
public string OverSoundToFile
{
get => Path.GetFileName(this.overSound);
set
{
if (!string.IsNullOrEmpty(value))
{
this.overSound = Path.Combine(SoundController.Instance.WaveDirectory, value);
}
}
}
[XmlIgnore]
public string BeforeSound { get => this.beforeSound; set => this.beforeSound = value; }
[XmlElement(ElementName = "BeforeSound")]
public string BeforeSoundToFile
{
get => Path.GetFileName(this.beforeSound);
set
{
if (!string.IsNullOrEmpty(value))
{
this.beforeSound = Path.Combine(SoundController.Instance.WaveDirectory, value);
}
}
}
[XmlIgnore]
public string TimeupSound { get => this.timeupSound; set => this.timeupSound = value; }
[XmlElement(ElementName = "TimeupSound")]
public string TimeupSoundToFile
{
get => Path.GetFileName(this.timeupSound);
set
{
if (!string.IsNullOrEmpty(value))
{
this.timeupSound = Path.Combine(SoundController.Instance.WaveDirectory, value);
}
}
}
#endregion to Notice wave files
#region Performance Monitor
[XmlIgnore]
public double MatchingDuration { get; set; } = 0.0;
[XmlIgnore]
private DateTime matchingStartDateTime;
public void StartMatching()
{
this.matchingStartDateTime = DateTime.Now;
}
public void EndMatching()
{
var ticks = (DateTime.Now - this.matchingStartDateTime).Ticks;
if (ticks == 0)
{
return;
}
var cost = ticks / 1000;
if (this.MatchingDuration != 0)
{
this.MatchingDuration += cost;
this.MatchingDuration /= 2;
}
else
{
this.MatchingDuration += cost;
}
}
#endregion Performance Monitor
[XmlIgnore]
private DelayableTask overSoundTask;
[XmlIgnore]
private DelayableTask beforeSoundTask;
[XmlIgnore]
private DelayableTask timeupSoundTask;
public void Dispose()
{
if (this.overSoundTask != null)
{
this.overSoundTask.IsCancel = true;
}
if (this.beforeSoundTask != null)
{
this.beforeSoundTask.IsCancel = true;
}
if (this.timeupSoundTask != null)
{
this.timeupSoundTask.IsCancel = true;
}
}
/// <summary>
/// マッチ後n秒後のサウンドタイマを開始する
/// </summary>
public void StartOverSoundTimer()
{
if (this.overSoundTask != null)
{
this.overSoundTask.IsCancel = true;
}
if (this.OverTime <= 0 ||
this.MatchDateTime <= DateTime.MinValue)
{
return;
}
if (string.IsNullOrWhiteSpace(this.OverSound) &&
string.IsNullOrWhiteSpace(this.OverTextToSpeak))
{
return;
}
var timeToPlay = this.MatchDateTime.AddSeconds(this.OverTime);
var duration = (timeToPlay - DateTime.Now).TotalMilliseconds;
if (duration > 0d)
{
this.overSoundTask = DelayableTask.Run(
this.PlayOverSound,
TimeSpan.FromMilliseconds(duration));
}
}
/// <summary>
/// リキャストn秒前のサウンドタイマを開始する
/// </summary>
public void StartBeforeSoundTimer()
{
if (this.beforeSoundTask != null)
{
this.beforeSoundTask.IsCancel = true;
}
if (this.BeforeTime <= 0 ||
this.MatchDateTime <= DateTime.MinValue)
{
return;
}
if (string.IsNullOrWhiteSpace(this.BeforeSound) &&
string.IsNullOrWhiteSpace(this.BeforeTextToSpeak))
{
return;
}
if (this.CompleteScheduledTime <= DateTime.MinValue)
{
return;
}
var timeToPlay = this.CompleteScheduledTime.AddSeconds(this.BeforeTime * -1);
var duration = (timeToPlay - DateTime.Now).TotalMilliseconds;
if (duration > 0d)
{
this.beforeSoundTask = DelayableTask.Run(
this.PlayBeforeSound,
TimeSpan.FromMilliseconds(duration));
}
}
/// <summary>
/// リキャスト完了のサウンドタイマを開始する
/// </summary>
public void StartTimeupSoundTimer()
{
if (this.timeupSoundTask != null)
{
this.timeupSoundTask.IsCancel = true;
}
if (this.CompleteScheduledTime <= DateTime.MinValue ||
this.MatchDateTime <= DateTime.MinValue)
{
return;
}
if (string.IsNullOrWhiteSpace(this.TimeupSound) &&
string.IsNullOrWhiteSpace(this.TimeupTextToSpeak))
{
return;
}
var timeToPlay = this.CompleteScheduledTime;
var duration = (timeToPlay - DateTime.Now).TotalMilliseconds;
if (duration > 0d)
{
this.timeupSoundTask = DelayableTask.Run(
this.PlayTimeupSound,
TimeSpan.FromMilliseconds(duration));
}
else
{
this.PlayTimeupSound();
}
}
private void PlayBeforeSound()
{
this.BeforeDone = true;
var regex = this.Regex;
var wave = this.BeforeSound;
var speak = this.BeforeTextToSpeak;
this.Play(wave, this.BeforeAdvancedConfig);
if (!string.IsNullOrWhiteSpace(speak))
{
if (regex == null ||
!speak.Contains("$"))
{
this.Play(speak, this.BeforeAdvancedConfig);
return;
}
var match = regex.Match(this.MatchedLog);
speak = match.Result(speak);
this.Play(speak, this.BeforeAdvancedConfig);
}
}
private void PlayOverSound()
{
this.OverDone = true;
var regex = this.Regex;
var wave = this.OverSound;
var speak = this.OverTextToSpeak;
this.Play(wave, this.OverAdvancedConfig);
if (!string.IsNullOrWhiteSpace(speak))
{
if (regex == null ||
!speak.Contains("$"))
{
this.Play(speak, this.OverAdvancedConfig);
return;
}
var match = regex.Match(this.MatchedLog);
speak = match.Result(speak);
this.Play(speak, this.OverAdvancedConfig);
}
}
private void PlayTimeupSound()
{
this.TimeupDone = true;
var regex = this.Regex;
var wave = this.TimeupSound;
var speak = this.TimeupTextToSpeak;
this.Play(wave, this.TimeupAdvancedConfig);
if (!string.IsNullOrWhiteSpace(speak))
{
if (regex == null ||
!speak.Contains("$"))
{
this.Play(speak, this.TimeupAdvancedConfig);
return;
}
var match = regex.Match(this.MatchedLog);
speak = match.Result(speak);
this.Play(speak, this.TimeupAdvancedConfig);
}
}
#region Clone
public Spell Clone() => (Spell)this.MemberwiseClone();
#endregion Clone
#region NewSpell
public static Spell CreateNew()
{
var n = new Spell();
lock (SpellTable.Instance.Table)
{
n.ID = SpellTable.Instance.Table.Any() ?
SpellTable.Instance.Table.Max(x => x.ID) + 1 :
1;
n.DisplayNo = SpellTable.Instance.Table.Any() ?
SpellTable.Instance.Table.Max(x => x.DisplayNo) + 1 :
50;
}
n.PanelID = SpellPanel.GeneralPanel.ID;
n.SpellTitle = "New Spell";
n.SpellIconSize = 24;
n.FontColor = Colors.White.ToLegacy().ToHTML();
n.FontOutlineColor = Colors.MidnightBlue.ToLegacy().ToHTML();
n.WarningFontColor = Colors.White.ToLegacy().ToHTML();
n.WarningFontOutlineColor = Colors.OrangeRed.ToLegacy().ToHTML();
n.BarColor = Colors.White.ToLegacy().ToHTML();
n.BarOutlineColor = Colors.MidnightBlue.ToLegacy().ToHTML();
n.BackgroundColor = Colors.Transparent.ToLegacy().ToHTML();
n.BarWidth = 190;
n.BarHeight = 8;
n.Enabled = true;
return n;
}
/// <summary>
/// 同様のインスタンスを作る(新規スペルの登録用)
/// </summary>
/// <returns>
/// 同様のインスタンス</returns>
public Spell CreateSimilarNew()
{
var n = Spell.CreateNew();
n.PanelID = this.PanelID;
n.SpellTitle = this.SpellTitle + " New";
n.SpellIcon = this.SpellIcon;
n.SpellIconSize = this.SpellIconSize;
n.Keyword = this.Keyword;
n.RegexEnabled = this.RegexEnabled;
n.RecastTime = this.RecastTime;
n.KeywordForExtend1 = this.KeywordForExtend1;
n.RecastTimeExtending1 = this.RecastTimeExtending1;
n.KeywordForExtend2 = this.KeywordForExtend2;
n.RecastTimeExtending2 = this.RecastTimeExtending2;
n.KeywordForExtend3 = this.KeywordForExtend3;
n.RecastTimeExtending3 = this.RecastTimeExtending3;
n.IsNotResetBarOnExtended = this.IsNotResetBarOnExtended;
n.ExtendBeyondOriginalRecastTime = this.ExtendBeyondOriginalRecastTime;
n.UpperLimitOfExtension = this.UpperLimitOfExtension;
n.ProgressBarVisible = this.ProgressBarVisible;
n.IsReverse = this.IsReverse;
n.FontColor = this.FontColor;
n.FontOutlineColor = this.FontOutlineColor;
n.WarningFontColor = this.WarningFontColor;
n.WarningFontOutlineColor = this.WarningFontOutlineColor;
n.BarColor = this.BarColor;
n.BarOutlineColor = this.BarOutlineColor;
n.BarBlurRadius = this.BarBlurRadius;
n.DontHide = this.DontHide;
n.HideSpellName = this.HideSpellName;
n.WarningTime = this.WarningTime;
n.BlinkTime = this.BlinkTime;
n.BlinkIcon = this.BlinkIcon;
n.BlinkBar = this.BlinkBar;
n.ChangeFontColorsWhenWarning = this.ChangeFontColorsWhenWarning;
n.ChangeFontColorWhenContainsMe = this.ChangeFontColorWhenContainsMe;
n.OverlapRecastTime = this.OverlapRecastTime;
n.ReduceIconBrightness = this.ReduceIconBrightness;
n.Font = this.Font.Clone() as FontInfo;
n.IsCircleStyle = this.IsCircleStyle;
n.IsCounterToCenter = this.IsCounterToCenter;
n.TitleVerticalAlignmentInCircle = this.TitleVerticalAlignmentInCircle;
n.BarWidth = this.BarWidth;
n.BarHeight = this.BarHeight;
n.BackgroundColor = this.BackgroundColor;
n.BackgroundAlpha = this.BackgroundAlpha;
n.HideCounter = this.HideCounter;
n.JobFilter = this.JobFilter;
n.PartyJobFilter = this.PartyJobFilter;
n.ZoneFilter = this.ZoneFilter;
n.TimersMustRunningForStart = this.TimersMustRunningForStart;
n.TimersMustStoppingForStart = this.TimersMustStoppingForStart;
n.MatchAdvancedConfig = this.MatchAdvancedConfig.Clone() as AdvancedNoticeConfig;
n.OverAdvancedConfig = this.OverAdvancedConfig.Clone() as AdvancedNoticeConfig;
n.BeforeAdvancedConfig = this.BeforeAdvancedConfig.Clone() as AdvancedNoticeConfig;
n.TimeupAdvancedConfig = this.TimeupAdvancedConfig.Clone() as AdvancedNoticeConfig;
n.IsSequentialTTS = this.IsSequentialTTS;
n.ToInstance = this.ToInstance;
n.Enabled = this.Enabled;
return n;
}
public Spell CreateInstanceNew(
string title)
{
var n = Spell.CreateNew();
n.SpellTitleReplaced = title;
n.PanelID = this.PanelID;
n.SpellTitle = this.SpellTitle;
n.SpellIcon = this.SpellIcon;
n.SpellIconSize = this.SpellIconSize;
n.Keyword = this.Keyword;
n.KeywordForExtend1 = this.KeywordForExtend1;
n.KeywordForExtend2 = this.KeywordForExtend2;
n.KeywordForExtend3 = this.KeywordForExtend3;
n.RecastTimeExtending1 = this.RecastTimeExtending1;
n.RecastTimeExtending2 = this.RecastTimeExtending2;
n.RecastTimeExtending3 = this.RecastTimeExtending3;
n.RecastTime = this.RecastTime;
n.IsNotResetBarOnExtended = this.IsNotResetBarOnExtended;
n.ExtendBeyondOriginalRecastTime = this.ExtendBeyondOriginalRecastTime;
n.UpperLimitOfExtension = this.UpperLimitOfExtension;
n.ProgressBarVisible = this.ProgressBarVisible;
n.MatchSound = this.MatchSound;
n.MatchTextToSpeak = this.MatchTextToSpeak;
n.OverSound = this.OverSound;
n.OverTextToSpeak = this.OverTextToSpeak;
n.OverTime = this.OverTime;
n.BeforeSound = this.BeforeSound;
n.BeforeTextToSpeak = this.BeforeTextToSpeak;
n.BeforeTime = this.BeforeTime;
n.TimeupSound = this.TimeupSound;
n.TimeupTextToSpeak = this.TimeupTextToSpeak;
n.MatchDateTime = this.MatchDateTime;
n.TimeupHide = this.TimeupHide;
n.IsReverse = this.IsReverse;
n.Font = this.Font;
n.FontColor = this.FontColor;
n.FontOutlineColor = this.FontOutlineColor;
n.WarningFontColor = this.WarningFontColor;
n.WarningFontOutlineColor = this.WarningFontOutlineColor;
n.BarColor = this.BarColor;
n.BarOutlineColor = this.BarOutlineColor;
n.BarBlurRadius = this.BarBlurRadius;
n.IsCircleStyle = this.IsCircleStyle;
n.IsCounterToCenter = this.IsCounterToCenter;
n.TitleVerticalAlignmentInCircle = this.TitleVerticalAlignmentInCircle;
n.BarWidth = this.BarWidth;
n.BarHeight = this.BarHeight;
n.BackgroundColor = this.BackgroundColor;
n.BackgroundAlpha = this.BackgroundAlpha;
n.HideCounter = this.HideCounter;
n.DontHide = this.DontHide;
n.HideSpellName = this.HideSpellName;
n.WarningTime = this.WarningTime;
n.ChangeFontColorsWhenWarning = this.ChangeFontColorsWhenWarning;
n.ChangeFontColorWhenContainsMe = this.ChangeFontColorWhenContainsMe;
n.BlinkTime = this.BlinkTime;
n.BlinkIcon = this.BlinkIcon;
n.BlinkBar = this.BlinkBar;
n.OverlapRecastTime = this.OverlapRecastTime;
n.ReduceIconBrightness = this.ReduceIconBrightness;
n.RegexEnabled = this.RegexEnabled;
n.IsNotResetAtWipeout = this.IsNotResetAtWipeout;
n.JobFilter = this.JobFilter;
n.PartyJobFilter = this.PartyJobFilter;
n.ZoneFilter = this.ZoneFilter;
n.TimersMustRunningForStart = this.TimersMustRunningForStart;
n.TimersMustStoppingForStart = this.TimersMustStoppingForStart;
n.Enabled = this.Enabled;
n.MatchedLog = this.MatchedLog;
n.Regex = this.Regex;
n.RegexPattern = this.RegexPattern;
n.KeywordReplaced = this.KeywordReplaced;
n.RegexForExtend1 = this.RegexForExtend1;
n.RegexForExtendPattern1 = this.RegexForExtendPattern1;
n.KeywordForExtendReplaced1 = this.KeywordForExtendReplaced1;
n.RegexForExtend2 = this.RegexForExtend2;
n.RegexForExtendPattern2 = this.RegexForExtendPattern2;
n.KeywordForExtendReplaced2 = this.KeywordForExtendReplaced2;
n.RegexForExtend3 = this.RegexForExtend3;
n.RegexForExtendPattern3 = this.RegexForExtendPattern3;
n.KeywordForExtendReplaced3 = this.KeywordForExtendReplaced3;
n.MatchAdvancedConfig = this.MatchAdvancedConfig;
n.OverAdvancedConfig = this.OverAdvancedConfig;
n.BeforeAdvancedConfig = this.BeforeAdvancedConfig;
n.TimeupAdvancedConfig = this.TimeupAdvancedConfig;
n.IsSequentialTTS = this.IsSequentialTTS;
n.ToInstance = false;
n.IsInstance = true;
n.IsDesignMode = false;
return n;
}
#endregion NewSpell
public void SimulateMatch()
{
var now = DateTime.Now;
// 擬似的にマッチ状態にする
this.IsTest = true;
this.MatchDateTime = now;
this.CompleteScheduledTime = now.AddSeconds(this.RecastTime);
this.UpdateDone = false;
this.OverDone = false;
this.BeforeDone = false;
this.TimeupDone = false;
// マッチ時点のサウンドを再生する
this.MatchAdvancedConfig.PlayWave(this.MatchSound);
this.MatchAdvancedConfig.Speak(this.MatchTextToSpeak);
// 遅延サウンドタイマを開始する
this.StartOverSoundTimer();
this.StartBeforeSoundTimer();
this.StartTimeupSoundTimer();
// トリガリストに加える
TableCompiler.Instance.AddTestTrigger(this);
}
/// <summary>
/// ToString()
/// </summary>
/// <returns></returns>
public override string ToString()
=> !string.IsNullOrEmpty(this.SpellTitleReplaced) ?
this.SpellTitleReplaced :
this.SpellTitle;
#region Sample Spells
public static readonly Spell[] SampleSpells = new[]
{
// ランパート
new Spell()
{
PanelID = SpellPanel.GeneralPanel.ID,
SpellTitle = "ランパート",
Keyword = "<mex>の「ランパート」",
RegexEnabled = true,
RecastTime = 90,
BarHeight = 8,
BarWidth = 120,
}
};
#endregion Sample Spells
}
}
| 31.006471 | 108 | 0.515661 | [
"BSD-3-Clause"
] | anoyetta/ACT.Hojoring | source/ACT.SpecialSpellTimer/ACT.SpecialSpellTimer.Core/Models/Spell.cs | 53,807 | C# |
/*
* 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.
*/
using System.Collections.Generic;
using Newtonsoft.Json;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Vcs;
using Aliyun.Acs.Vcs.Transform;
using Aliyun.Acs.Vcs.Transform.V20200515;
namespace Aliyun.Acs.Vcs.Model.V20200515
{
public class RecognizeFaceQualityRequest : RpcAcsRequest<RecognizeFaceQualityResponse>
{
public RecognizeFaceQualityRequest()
: base("Vcs", "2020-05-15", "RecognizeFaceQuality")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string corpId;
private string picUrl;
private string picContent;
private string picFormat;
public string CorpId
{
get
{
return corpId;
}
set
{
corpId = value;
DictionaryUtil.Add(BodyParameters, "CorpId", value);
}
}
public string PicUrl
{
get
{
return picUrl;
}
set
{
picUrl = value;
DictionaryUtil.Add(BodyParameters, "PicUrl", value);
}
}
public string PicContent
{
get
{
return picContent;
}
set
{
picContent = value;
DictionaryUtil.Add(BodyParameters, "PicContent", value);
}
}
public string PicFormat
{
get
{
return picFormat;
}
set
{
picFormat = value;
DictionaryUtil.Add(BodyParameters, "PicFormat", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override RecognizeFaceQualityResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return RecognizeFaceQualityResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 25.215517 | 134 | 0.669744 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-vcs/Vcs/Model/V20200515/RecognizeFaceQualityRequest.cs | 2,925 | C# |
using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityStandardAssets.Characters.ThirdPerson;
public class GameController : MonoBehaviour {
public static GameController instance;
public GameObject MainCamera;
public GameObject Player;
public ThirdPersonCharacter ThirdPersonScript;
public int timeTaken, alerts;
private void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
Player = GameObject.FindGameObjectWithTag("Player");
ThirdPersonScript = Player.GetComponent<ThirdPersonCharacter>();
}
void Update ()
{
if (ThirdPersonScript.Health <= 0) EndGame();
}
public void EndGame()
{
MainCamera.GetComponent<CinemachineBrain>().enabled = false;
SceneManager.LoadScene("MissionFailed");
}
} | 23.883721 | 72 | 0.660175 | [
"MIT"
] | ITSGameDevTeamY3/Project-Dissonance | Assets/GameController.cs | 1,029 | C# |
/*
// <copyright>
// dotNetRDF is free and open source software licensed under the MIT License
// -------------------------------------------------------------------------
//
// Copyright (c) 2009-2020 dotNetRDF Project (http://dotnetrdf.org/)
//
// 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.
// </copyright>
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using VDS.RDF.Parsing;
using VDS.RDF.Writing;
namespace VDS.RDF
{
/// <summary>
/// Represents the definition of a MIME Type including mappings to relevant readers and writers.
/// </summary>
public sealed class MimeTypeDefinition
{
private String _name, _canonicalType, _canonicalExt, _formatUri;
private Encoding _encoding = Encoding.UTF8;
private List<String> _mimeTypes = new List<string>();
private List<String> _fileExtensions = new List<string>();
private Type _rdfParserType, _rdfDatasetParserType, _sparqlResultsParserType;
private Type _rdfWriterType, _rdfDatasetWriterType, _sparqlResultsWriterType;
private Dictionary<Type, Type> _objectParserTypes = new Dictionary<Type, Type>();
/// <summary>
/// Creates a new MIME Type Definition.
/// </summary>
/// <param name="syntaxName">Syntax Name for the Syntax which has this MIME Type definition.</param>
/// <param name="mimeTypes">MIME Types.</param>
/// <param name="fileExtensions">File Extensions.</param>
public MimeTypeDefinition(String syntaxName, IEnumerable<String> mimeTypes, IEnumerable<String> fileExtensions)
{
if (mimeTypes == null) throw new ArgumentNullException("MIME Types enumeration cannot be null");
_name = syntaxName;
_mimeTypes.AddRange(mimeTypes.Select(t => CheckValidMimeType(t)));
foreach (String ext in fileExtensions)
{
_fileExtensions.Add(CheckFileExtension(ext));
}
}
/// <summary>
/// Creates a new MIME Type Definition.
/// </summary>
/// <param name="syntaxName">Syntax Name for the Syntax which has this MIME Type definition.</param>
/// <param name="formatUri">Format URI as defined by the. <a href="http://www.w3.org/ns/formats/">W3C</a></param>
/// <param name="mimeTypes">MIME Types.</param>
/// <param name="fileExtensions">File Extensions.</param>
public MimeTypeDefinition(String syntaxName, String formatUri, IEnumerable<String> mimeTypes, IEnumerable<String> fileExtensions)
: this(syntaxName, mimeTypes, fileExtensions)
{
_formatUri = formatUri;
}
/// <summary>
/// Creates a new MIME Type Definition.
/// </summary>
/// <param name="syntaxName">Syntax Name for the Syntax which has this MIME Type definition.</param>
/// <param name="mimeTypes">MIME Types.</param>
/// <param name="fileExtensions">File Extensions.</param>
/// <param name="rdfParserType">Type to use to parse RDF (or null if not applicable).</param>
/// <param name="rdfDatasetParserType">Type to use to parse RDF Datasets (or null if not applicable).</param>
/// <param name="sparqlResultsParserType">Type to use to parse SPARQL Results (or null if not applicable).</param>
/// <param name="rdfWriterType">Type to use to writer RDF (or null if not applicable).</param>
/// <param name="rdfDatasetWriterType">Type to use to write RDF Datasets (or null if not applicable).</param>
/// <param name="sparqlResultsWriterType">Type to use to write SPARQL Results (or null if not applicable).</param>
public MimeTypeDefinition(String syntaxName, IEnumerable<String> mimeTypes, IEnumerable<String> fileExtensions, Type rdfParserType, Type rdfDatasetParserType, Type sparqlResultsParserType, Type rdfWriterType, Type rdfDatasetWriterType, Type sparqlResultsWriterType)
: this(syntaxName, mimeTypes, fileExtensions)
{
RdfParserType = rdfParserType;
RdfDatasetParserType = rdfDatasetParserType;
SparqlResultsParserType = sparqlResultsParserType;
RdfWriterType = rdfWriterType;
RdfDatasetWriterType = rdfDatasetWriterType;
SparqlResultsWriterType = sparqlResultsWriterType;
}
/// <summary>
/// Creates a new MIME Type Definition.
/// </summary>
/// <param name="syntaxName">Syntax Name for the Syntax which has this MIME Type definition.</param>
/// <param name="formatUri">Format URI as defined by the. <a href="http://www.w3.org/ns/formats/">W3C</a></param>
/// <param name="mimeTypes">MIME Types.</param>
/// <param name="fileExtensions">File Extensions.</param>
/// <param name="rdfParserType">Type to use to parse RDF (or null if not applicable).</param>
/// <param name="rdfDatasetParserType">Type to use to parse RDF Datasets (or null if not applicable).</param>
/// <param name="sparqlResultsParserType">Type to use to parse SPARQL Results (or null if not applicable).</param>
/// <param name="rdfWriterType">Type to use to writer RDF (or null if not applicable).</param>
/// <param name="rdfDatasetWriterType">Type to use to write RDF Datasets (or null if not applicable).</param>
/// <param name="sparqlResultsWriterType">Type to use to write SPARQL Results (or null if not applicable).</param>
public MimeTypeDefinition(String syntaxName, String formatUri, IEnumerable<String> mimeTypes, IEnumerable<String> fileExtensions, Type rdfParserType, Type rdfDatasetParserType, Type sparqlResultsParserType, Type rdfWriterType, Type rdfDatasetWriterType, Type sparqlResultsWriterType)
: this(syntaxName, mimeTypes, fileExtensions, rdfParserType, rdfDatasetParserType, sparqlResultsParserType, rdfWriterType, rdfDatasetWriterType, sparqlResultsWriterType)
{
_formatUri = formatUri;
}
/// <summary>
/// Gets the name of the Syntax to which this MIME Type Definition relates.
/// </summary>
public String SyntaxName
{
get
{
return _name;
}
}
/// <summary>
/// Gets the Format URI as defined by the <a href="http://www.w3.org/ns/formats/">W3C</a> (where applicable).
/// </summary>
public String FormatUri
{
get
{
return _formatUri;
}
}
/// <summary>
/// Gets the Encoding that should be used for reading and writing this Syntax.
/// </summary>
public Encoding Encoding
{
get
{
if (_encoding != null)
{
return _encoding;
}
else
{
return Encoding.UTF8;
}
}
set
{
_encoding = value;
}
}
#region MIME Type Management
/// <summary>
/// Gets the MIME Types defined.
/// </summary>
public IEnumerable<String> MimeTypes
{
get
{
return _mimeTypes;
}
}
/// <summary>
/// Checks that MIME Types are valid.
/// </summary>
/// <param name="type">Type.</param>
public String CheckValidMimeType(String type)
{
type = type.Trim().ToLowerInvariant();
if (!MimeTypesHelper.IsValidMimeType(type))
{
throw new RdfException(type + " is not a valid MIME Type");
}
return type;
}
/// <summary>
/// Adds a MIME Type to this definition.
/// </summary>
/// <param name="type">MIME Type.</param>
public void AddMimeType(String type)
{
if (!_mimeTypes.Contains(CheckValidMimeType(type)))
{
_mimeTypes.Add(CheckValidMimeType(type));
}
}
/// <summary>
/// Gets the Canonical MIME Type that should be used.
/// </summary>
public String CanonicalMimeType
{
get
{
if (_canonicalType != null)
{
return _canonicalType;
}
else if (_mimeTypes.Count > 0)
{
return _mimeTypes.First();
}
else
{
throw new RdfException("No MIME Types are defined for " + _name);
}
}
set
{
if (value == null)
{
_canonicalType = value;
}
else if (_mimeTypes.Contains(value))
{
_canonicalType = value;
}
else
{
throw new RdfException("Cannot set the Canonical MIME Type for " + _name + " to " + value + " as this is no such MIME Type listed in this definition. Use AddMimeType to add a MIME Type prior to setting the CanonicalType.");
}
}
}
/// <summary>
/// Determines whether the Definition supports a particular MIME type.
/// </summary>
/// <param name="mimeType">MIME Type.</param>
/// <returns></returns>
[Obsolete("Deprecated in favour of the alternative overload which takes a MimeTypeSelector", false)]
public bool SupportsMimeType(String mimeType)
{
String type = mimeType.ToLowerInvariant();
type = type.Contains(';') ? type.Substring(0, type.IndexOf(';')) : type;
return _mimeTypes.Contains(type) || mimeType.Equals(MimeTypesHelper.Any);
}
/// <summary>
/// Determines whether the definition supports the MIME type specified by the selector.
/// </summary>
/// <param name="selector">MIME Type selector.</param>
/// <returns></returns>
public bool SupportsMimeType(MimeTypeSelector selector)
{
if (selector.IsInvalid) return false;
if (selector.IsAny) return true;
if (selector.IsRange)
{
if (selector.RangeType == null) return false;
return _mimeTypes.Any(type => type.StartsWith(selector.RangeType));
}
else
{
return _mimeTypes.Contains(selector.Type);
}
}
#endregion
#region File Extension Management
/// <summary>
/// Gets the File Extensions associated with this Syntax.
/// </summary>
public IEnumerable<String> FileExtensions
{
get
{
return _fileExtensions;
}
}
/// <summary>
/// Adds a File Extension for this Syntax.
/// </summary>
/// <param name="ext">File Extension.</param>
public void AddFileExtension(String ext)
{
if (!_fileExtensions.Contains(CheckFileExtension(ext)))
{
_fileExtensions.Add(CheckFileExtension(ext));
}
}
private String CheckFileExtension(String ext)
{
if (ext.StartsWith(".")) return ext.Substring(1);
return ext.ToLowerInvariant();
}
/// <summary>
/// Gets whether any file extensions are associated with this syntax.
/// </summary>
public bool HasFileExtensions
{
get
{
return _canonicalExt != null || _fileExtensions.Count > 0;
}
}
/// <summary>
/// Gets/Sets the Canonical File Extension for this Syntax.
/// </summary>
public String CanonicalFileExtension
{
get
{
if (_canonicalExt != null)
{
return _canonicalExt;
}
else if (_fileExtensions.Count > 0)
{
return _fileExtensions.First();
}
else
{
throw new RdfException("No File Extensions are defined for " + _name);
}
}
set
{
if (value == null)
{
_canonicalExt = value;
}
else if (_fileExtensions.Contains(CheckFileExtension(value)))
{
_fileExtensions.Add(CheckFileExtension(value));
}
else
{
throw new RdfException("Cannot set the Canonical File Extension for " + _name + " to " + value + " as this is no such File Extension listed in this definition. Use AddFileExtension to add a File Extension prior to setting the CanonicalFileExtension.");
}
}
}
/// <summary>
/// Determines whether the Definition supports a particular File Extension.
/// </summary>
/// <param name="ext">File Extension.</param>
/// <returns></returns>
public bool SupportsFileExtension(String ext)
{
ext = ext.ToLowerInvariant();
if (ext.StartsWith(".")) ext = ext.Substring(1);
return _fileExtensions.Contains(ext);
}
#endregion
#region Parser and Writer Management
/// <summary>
/// Ensures that a given Type implements a required Interface.
/// </summary>
/// <param name="property">Property to which we are assigning.</param>
/// <param name="t">Type.</param>
/// <param name="interfaceType">Required Interface Type.</param>
private bool EnsureInterface(String property, Type t, Type interfaceType)
{
if (!t.GetInterfaces().Any(itype => itype.Equals(interfaceType)))
{
throw new RdfException("Cannot use Type " + t.FullName + " for the " + property + " Type as it does not implement the required interface " + interfaceType.FullName);
}
else
{
return true;
}
}
private bool EnsureObjectParserInterface(Type t, Type obj)
{
bool ok = false;
foreach (Type i in t.GetInterfaces())
{
#if NETCORE
if(i.IsGenericType())
#else
if (i.IsGenericType)
#endif
{
if (i.GetGenericArguments().First().Equals(obj))
{
ok = true;
break;
}
}
}
if (!ok)
{
throw new RdfException("Cannot use Type " + t.FullName + " as an Object Parser for the Type " + obj.FullName + " as it does not implement the required interface IObjectParser<" + obj.Name + ">");
}
return ok;
}
/// <summary>
/// Gets/Sets the Type to use to parse RDF (or null if not applicable).
/// </summary>
public Type RdfParserType
{
get
{
return _rdfParserType;
}
set
{
if (value == null)
{
_rdfParserType = value;
}
else
{
if (EnsureInterface("RDF Parser", value, typeof(IRdfReader)))
{
_rdfParserType = value;
}
}
}
}
/// <summary>
/// Gets/Sets the Type to use to parse RDF Datasets (or null if not applicable).
/// </summary>
public Type RdfDatasetParserType
{
get
{
return _rdfDatasetParserType;
}
set
{
if (value == null)
{
_rdfDatasetParserType = value;
}
else
{
if (EnsureInterface("RDF Dataset Parser", value, typeof(IStoreReader)))
{
_rdfDatasetParserType = value;
}
}
}
}
/// <summary>
/// Gets/Sets the Type to use to parse SPARQL Results (or null if not applicable).
/// </summary>
public Type SparqlResultsParserType
{
get
{
return _sparqlResultsParserType;
}
set
{
if (value == null)
{
_sparqlResultsParserType = value;
}
else
{
if (EnsureInterface("SPARQL Results Parser", value, typeof(ISparqlResultsReader)))
{
_sparqlResultsParserType = value;
}
}
}
}
/// <summary>
/// Gets/Sets the Type to use to writer RDF (or null if not applicable).
/// </summary>
public Type RdfWriterType
{
get
{
return _rdfWriterType;
}
set
{
if (value == null)
{
_rdfWriterType = value;
}
else
{
if (EnsureInterface("RDF Writer", value, typeof(IRdfWriter)))
{
_rdfWriterType = value;
}
}
}
}
/// <summary>
/// Gets/Sets the Type to use to writer RDF Dataets (or null if not applicable).
/// </summary>
public Type RdfDatasetWriterType
{
get
{
return _rdfDatasetWriterType;
}
set
{
if (value == null)
{
_rdfDatasetWriterType = value;
}
else
{
if (EnsureInterface("RDF Dataset Writer", value, typeof(IStoreWriter)))
{
_rdfDatasetWriterType = value;
}
}
}
}
/// <summary>
/// Gets/Sets the Type to use to write SPARQL Results (or null if not applicable).
/// </summary>
public Type SparqlResultsWriterType
{
get
{
return _sparqlResultsWriterType;
}
set
{
if (value == null)
{
_sparqlResultsWriterType = value;
}
else
{
if (EnsureInterface("SPARQL Results Writer", value, typeof(ISparqlResultsWriter)))
{
_sparqlResultsWriterType = value;
}
}
}
}
/// <summary>
/// Gets whether this definition can instantiate a Parser that can parse RDF.
/// </summary>
public bool CanParseRdf
{
get
{
return (_rdfParserType != null);
}
}
/// <summary>
/// Gets whether this definition can instantiate a Parser that can parse RDF Datasets.
/// </summary>
public bool CanParseRdfDatasets
{
get
{
return (_rdfDatasetParserType != null);
}
}
/// <summary>
/// Gets whether this definition can instantiate a Parser that can parse SPARQL Results.
/// </summary>
public bool CanParseSparqlResults
{
get
{
return (_sparqlResultsParserType != null);
}
}
/// <summary>
/// Gets whether the definition provides a RDF Writer.
/// </summary>
public bool CanWriteRdf
{
get
{
return (_rdfWriterType != null);
}
}
/// <summary>
/// Gets whether the Definition provides a RDF Dataset Writer.
/// </summary>
public bool CanWriteRdfDatasets
{
get
{
return (_rdfDatasetWriterType != null);
}
}
/// <summary>
/// Gets whether the Definition provides a SPARQL Results Writer.
/// </summary>
public bool CanWriteSparqlResults
{
get
{
return (_sparqlResultsWriterType != null);
}
}
/// <summary>
/// Gets an instance of a RDF parser.
/// </summary>
/// <returns></returns>
public IRdfReader GetRdfParser()
{
if (_rdfParserType != null)
{
return (IRdfReader)Activator.CreateInstance(_rdfParserType);
}
else
{
throw new RdfParserSelectionException("There is no RDF Parser available for the Syntax " + _name);
}
}
/// <summary>
/// Gets an instance of a RDF writer.
/// </summary>
/// <returns></returns>
public IRdfWriter GetRdfWriter()
{
if (_rdfWriterType != null)
{
return (IRdfWriter)Activator.CreateInstance(_rdfWriterType);
}
else
{
throw new RdfWriterSelectionException("There is no RDF Writer available for the Syntax " + _name);
}
}
/// <summary>
/// Gets an instance of a RDF Dataset parser.
/// </summary>
/// <returns></returns>
public IStoreReader GetRdfDatasetParser()
{
if (_rdfDatasetParserType != null)
{
return (IStoreReader)Activator.CreateInstance(_rdfDatasetParserType);
}
else
{
throw new RdfParserSelectionException("There is no RDF Dataset Parser available for the Syntax " + _name);
}
}
/// <summary>
/// Gets an instance of a RDF Dataset writer.
/// </summary>
/// <returns></returns>
public IStoreWriter GetRdfDatasetWriter()
{
if (_rdfDatasetWriterType != null)
{
return (IStoreWriter)Activator.CreateInstance(_rdfDatasetWriterType);
}
else
{
throw new RdfWriterSelectionException("There is no RDF Dataset Writer available for the Syntax " + _name);
}
}
/// <summary>
/// Gets an instance of a SPARQL Results parser.
/// </summary>
/// <returns></returns>
public ISparqlResultsReader GetSparqlResultsParser()
{
if (_sparqlResultsParserType != null)
{
return (ISparqlResultsReader)Activator.CreateInstance(_sparqlResultsParserType);
}
else if (_rdfParserType != null)
{
return new SparqlRdfParser((IRdfReader)Activator.CreateInstance(_rdfParserType));
}
else
{
throw new RdfParserSelectionException("There is no SPARQL Results Parser available for the Syntax " + _name);
}
}
/// <summary>
/// Gets an instance of a SPARQL Results writer.
/// </summary>
/// <returns></returns>
public ISparqlResultsWriter GetSparqlResultsWriter()
{
if (_sparqlResultsWriterType != null)
{
return (ISparqlResultsWriter)Activator.CreateInstance(_sparqlResultsWriterType);
}
else if (_rdfWriterType != null)
{
return new SparqlRdfWriter((IRdfWriter)Activator.CreateInstance(_rdfWriterType));
}
else
{
throw new RdfWriterSelectionException("There is no SPARQL Results Writer available for the Syntax " + _name);
}
}
/// <summary>
/// Gets whether a particular Type of Object can be parsed.
/// </summary>
/// <typeparam name="T">Object Type.</typeparam>
/// <returns></returns>
public bool CanParseObject<T>()
{
return _objectParserTypes.ContainsKey(typeof(T));
}
/// <summary>
/// Gets an Object Parser for the given Type.
/// </summary>
/// <typeparam name="T">Object Type.</typeparam>
/// <returns></returns>
public Type GetObjectParserType<T>()
{
Type t = typeof(T);
Type result;
if (_objectParserTypes.TryGetValue(t, out result))
{
return result;
}
else
{
return null;
}
}
/// <summary>
/// Sets an Object Parser for the given Type.
/// </summary>
/// <typeparam name="T">Object Type.</typeparam>
/// <param name="parserType">Parser Type.</param>
public void SetObjectParserType<T>(Type parserType)
{
Type t = typeof(T);
if (_objectParserTypes.ContainsKey(t))
{
if (parserType == null)
{
_objectParserTypes.Remove(t);
}
else
{
if (EnsureObjectParserInterface(parserType, t))
{
_objectParserTypes[t] = parserType;
}
}
}
else if (parserType != null)
{
if (EnsureObjectParserInterface(parserType, t))
{
_objectParserTypes.Add(t, parserType);
}
}
}
/// <summary>
/// Gets an Object Parser for the given Type.
/// </summary>
/// <typeparam name="T">Object Type.</typeparam>
/// <returns></returns>
public IObjectParser<T> GetObjectParser<T>()
{
if (_objectParserTypes.ContainsKey(typeof(T)))
{
Type parserType = _objectParserTypes[typeof(T)];
return (IObjectParser<T>)Activator.CreateInstance(parserType);
}
else
{
throw new RdfParserSelectionException("There is no Object Parser available for the Type " + typeof(T).FullName);
}
}
/// <summary>
/// Gets the registered Object Parser Types.
/// </summary>
public IEnumerable<KeyValuePair<Type, Type>> ObjectParserTypes
{
get
{
return _objectParserTypes;
}
}
#endregion
}
/// <summary>
/// Selector used in selecting which MIME type to use.
/// </summary>
public sealed class MimeTypeSelector
: IComparable<MimeTypeSelector>
{
private String _type, _rangeType, _charset;
private double _quality = 1.0d;
private int _order;
private bool _isSpecific = false, _isRange = false, _isAny = false, _isInvalid = false;
/// <summary>
/// Creates a MIME Type selector.
/// </summary>
/// <param name="contentType">MIME Type.</param>
/// <param name="order">Order the selector appears in the input.</param>
/// <returns></returns>
public static MimeTypeSelector Create(String contentType, int order)
{
if (contentType.Contains(';'))
{
String[] parts = contentType.Split(';');
String type = parts[0].Trim().ToLowerInvariant();
double quality = 1.0d;
String charset = null;
for (int i = 1; i < parts.Length; i++)
{
String[] data = parts[i].Split('=');
if (data.Length == 1) continue;
switch (data[0].Trim().ToLowerInvariant())
{
case "charset":
charset = data[1].Trim();
break;
case "q":
if (!Double.TryParse(data[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out quality))
{
quality = 1.0d;
}
break;
}
}
return new MimeTypeSelector(type, charset, quality, order);
}
else
{
return new MimeTypeSelector(contentType.Trim().ToLowerInvariant(), null, 1.0d, order);
}
}
/// <summary>
/// Creates an enumeration of MIME type selectors.
/// </summary>
/// <param name="ctypes">MIME Types.</param>
/// <returns></returns>
public static IEnumerable<MimeTypeSelector> CreateSelectors(IEnumerable<String> ctypes)
{
List<MimeTypeSelector> selectors = new List<MimeTypeSelector>();
// Convert types into selectors
if (ctypes != null)
{
int order = 1;
foreach (String type in ctypes)
{
selectors.Add(Create(type, order));
order++;
}
}
// Adjust resulting selectors appropriately
if (selectors.Count == 0)
{
// If no MIME types treat as if a single any selector
selectors.Add(new MimeTypeSelector(MimeTypesHelper.Any, null, 1.0d, 1));
}
else
{
// Sort the selectors
selectors.Sort();
}
return selectors;
}
/// <summary>
/// Creates a new MIME Type Selector.
/// </summary>
/// <param name="type">MIME Type to match.</param>
/// <param name="charset">Charset.</param>
/// <param name="quality">Quality (in range 0.0-1.0).</param>
/// <param name="order">Order of appearance (used as precendence tiebreaker where necessary).</param>
public MimeTypeSelector(String type, String charset, double quality, int order)
{
if (type == null) throw new ArgumentNullException("type", "Type cannot be null");
_type = type.Trim().ToLowerInvariant();
_charset = charset != null ? charset.Trim() : null;
_quality = quality;
_order = order;
// Validate parameters
if (_quality < 0) _quality = 0;
if (_quality > 1) _quality = 1;
if (_order < 1) _order = 1;
// Check what type of selector this is
if (!MimeTypesHelper.IsValidMimeType(_type))
{
// Invalid
_isInvalid = true;
}
else if (_type.Equals(MimeTypesHelper.Any))
{
// Is a */* any
_isAny = true;
}
else if (_type.EndsWith("/*"))
{
// Is a blah/* range
_isRange = true;
_rangeType = _type.Substring(0, _type.Length - 1);
}
else if (_type.Contains('*'))
{
// If it contains a * and is not */* or blah/* it is invalid
_isInvalid = true;
}
else
{
// Must be a specific type
_isSpecific = true;
}
}
/// <summary>
/// Gets the selected type.
/// </summary>
/// <returns>A type string of the form <strong>type/subtype</strong> assuming the type if valid.</returns>
public String Type
{
get
{
return _type;
}
}
/// <summary>
/// Gets the range type if this is a range selector.
/// </summary>
/// <returns>A type string of the form <strong>type/</strong> if this is a range selector, otherwise null.</returns>
public String RangeType
{
get
{
return _rangeType;
}
}
/// <summary>
/// Gets the Charset for the selector (may be null if none specified).
/// </summary>
public String Charset
{
get
{
return _charset;
}
}
/// <summary>
/// Gets the quality for the selector (range of 0.0-1.0).
/// </summary>
public double Quality
{
get
{
return _quality;
}
}
/// <summary>
/// Gets the order of apperance for the selector (used as precedence tiebreaker where necessary).
/// </summary>
public int Order
{
get
{
return _order;
}
}
/// <summary>
/// Gets whether the selector if for a */* pattern i.e. accept any.
/// </summary>
public bool IsAny
{
get
{
return _isAny;
}
}
/// <summary>
/// Gets whether the selector is for a type/* pattern i.e. accept any sub-type of the given type.
/// </summary>
public bool IsRange
{
get
{
return _isRange;
}
}
/// <summary>
/// Gets whether the selector is invalid.
/// </summary>
public bool IsInvalid
{
get
{
return _isInvalid;
}
}
/// <summary>
/// Gets whether the selector is for a specific MIME type e.g. type/sub-type.
/// </summary>
public bool IsSpecific
{
get
{
return _isSpecific;
}
}
/// <summary>
/// Sorts the selector in precedence order according to the content negotiation rules from the relevant RFCs.
/// </summary>
/// <param name="other">Selector to compare against.</param>
/// <returns></returns>
public int CompareTo(MimeTypeSelector other)
{
if (other == null)
{
// We're always greater than a null
return -1;
}
if (_isInvalid)
{
if (other.IsInvalid)
{
// If both invalid use order
return Order.CompareTo(other.Order);
}
else
{
// Invalid types are less than valid types
return 1;
}
}
else if (other.IsInvalid)
{
// Valid types are greater than invalid types
return -1;
}
if (_isAny)
{
if (other.IsAny)
{
// If both Any use quality
int c = -1 * Quality.CompareTo(other.Quality);
if (c == 0)
{
// If same quality use order
c = Order.CompareTo(other.Order);
}
return c;
}
else
{
// Any is less than range/specific type
return 1;
}
}
else if (_isRange)
{
if (other.IsAny)
{
// Range types are greater than Any
return -1;
}
else if (other.IsRange)
{
// If both Range use quality
int c = -1 * Quality.CompareTo(other.Quality);
if (c == 0)
{
// If same quality use order
c = Order.CompareTo(other.Order);
}
return c;
}
else
{
// Range is less that specific type
return 1;
}
}
else
{
if (other.IsAny || other.IsRange)
{
// Specific types are greater than Any/Range
return -1;
}
else
{
// Both specific so use quality
int c = -1 * Quality.CompareTo(other.Quality);
if (c == 0)
{
// If same quality use order
c = Order.CompareTo(other.Order);
}
return c;
}
}
}
/// <summary>
/// Gets the string representation of the selector as it would appear in an Accept header.
/// </summary>
/// <returns></returns>
/// <remarks>
/// Unless this is an invalid selector this will always be a valid selector that could be appended to a MIME type header.
/// </remarks>
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append(_type);
if (_quality != 1.0d)
{
builder.Append("; q=" + _quality.ToString("g3"));
}
if (_charset != null)
{
builder.Append("; charset=" + _charset);
}
return builder.ToString();
}
}
}
| 33.503797 | 291 | 0.488489 | [
"MIT"
] | blackwork/dotnetrdf | Libraries/dotNetRDF/Core/MimeTypeDefinition.cs | 39,702 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class CMSModules_Ecommerce_Pages_Tools_Orders_Order_Edit_Billing {
/// <summary>
/// editOrderBilling control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CMS.PortalEngine.Web.UI.UIForm editOrderBilling;
}
| 33.173913 | 82 | 0.513761 | [
"MIT"
] | CMeeg/kentico-contrib | src/CMS/CMSModules/Ecommerce/Pages/Tools/Orders/Order_Edit_Billing.aspx.designer.cs | 765 | C# |
namespace Plugin
{
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.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
}
#endregion
}
}
| 28.225 | 107 | 0.554473 | [
"Apache-2.0"
] | JaeNuguid/Kids-Portal-Version-2 | Plugin/Form1.Designer.cs | 1,131 | C# |
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2020 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace GameFramework.ObjectPool
{
internal sealed partial class ObjectPoolManager : GameFrameworkModule, IObjectPoolManager
{
/// <summary>
/// 对象池。
/// </summary>
/// <typeparam name="T">对象类型。</typeparam>
private sealed class ObjectPool<T> : ObjectPoolBase, IObjectPool<T> where T : ObjectBase
{
private readonly Dictionary<string, List<Object<T>>> m_Objects;
private readonly Dictionary<object, Object<T>> m_ObjectMap;
private readonly ReleaseObjectFilterCallback<T> m_DefaultReleaseObjectFilterCallback;
private readonly List<T> m_CachedCanReleaseObjects;
private readonly List<T> m_CachedToReleaseObjects;
private readonly bool m_AllowMultiSpawn;
private float m_AutoReleaseInterval;
private int m_Capacity;
private float m_ExpireTime;
private int m_Priority;
private float m_AutoReleaseTime;
/// <summary>
/// 初始化对象池的新实例。
/// </summary>
/// <param name="name">对象池名称。</param>
/// <param name="allowMultiSpawn">是否允许对象被多次获取。</param>
/// <param name="autoReleaseInterval">对象池自动释放可释放对象的间隔秒数。</param>
/// <param name="capacity">对象池的容量。</param>
/// <param name="expireTime">对象池对象过期秒数。</param>
/// <param name="priority">对象池的优先级。</param>
public ObjectPool(string name, bool allowMultiSpawn, float autoReleaseInterval, int capacity, float expireTime, int priority)
: base(name)
{
m_Objects = new Dictionary<string, List<Object<T>>>();
m_ObjectMap = new Dictionary<object, Object<T>>();
m_DefaultReleaseObjectFilterCallback = DefaultReleaseObjectFilterCallback;
m_CachedCanReleaseObjects = new List<T>();
m_CachedToReleaseObjects = new List<T>();
m_AllowMultiSpawn = allowMultiSpawn;
m_AutoReleaseInterval = autoReleaseInterval;
Capacity = capacity;
ExpireTime = expireTime;
m_Priority = priority;
m_AutoReleaseTime = 0f;
}
/// <summary>
/// 获取对象池对象类型。
/// </summary>
public override Type ObjectType
{
get
{
return typeof(T);
}
}
/// <summary>
/// 获取对象池中对象的数量。
/// </summary>
public override int Count
{
get
{
return m_ObjectMap.Count;
}
}
/// <summary>
/// 获取对象池中能被释放的对象的数量。
/// </summary>
public override int CanReleaseCount
{
get
{
GetCanReleaseObjects(m_CachedCanReleaseObjects);
return m_CachedCanReleaseObjects.Count;
}
}
/// <summary>
/// 获取是否允许对象被多次获取。
/// </summary>
public override bool AllowMultiSpawn
{
get
{
return m_AllowMultiSpawn;
}
}
/// <summary>
/// 获取或设置对象池自动释放可释放对象的间隔秒数。
/// </summary>
public override float AutoReleaseInterval
{
get
{
return m_AutoReleaseInterval;
}
set
{
m_AutoReleaseInterval = value;
}
}
/// <summary>
/// 获取或设置对象池的容量。
/// </summary>
public override int Capacity
{
get
{
return m_Capacity;
}
set
{
if (value < 0)
{
throw new GameFrameworkException("Capacity is invalid.");
}
if (m_Capacity == value)
{
return;
}
m_Capacity = value;
Release();
}
}
/// <summary>
/// 获取或设置对象池对象过期秒数。
/// </summary>
public override float ExpireTime
{
get
{
return m_ExpireTime;
}
set
{
if (value < 0f)
{
throw new GameFrameworkException("ExpireTime is invalid.");
}
if (ExpireTime == value)
{
return;
}
m_ExpireTime = value;
Release();
}
}
/// <summary>
/// 获取或设置对象池的优先级。
/// </summary>
public override int Priority
{
get
{
return m_Priority;
}
set
{
m_Priority = value;
}
}
/// <summary>
/// 创建对象。
/// </summary>
/// <param name="obj">对象。</param>
/// <param name="spawned">对象是否已被获取。</param>
public void Register(T obj, bool spawned)
{
if (obj == null)
{
throw new GameFrameworkException("Object is invalid.");
}
List<Object<T>> objects = GetObjects(obj.Name);
if (objects == null)
{
objects = new List<Object<T>>();
m_Objects.Add(obj.Name, objects);
}
Object<T> internalObject = Object<T>.Create(obj, spawned);
objects.Add(internalObject);
m_ObjectMap.Add(obj.Target, internalObject);
if (Count > m_Capacity)
{
Release();
}
}
/// <summary>
/// 检查对象。
/// </summary>
/// <returns>要检查的对象是否存在。</returns>
public bool CanSpawn()
{
return CanSpawn(string.Empty);
}
/// <summary>
/// 检查对象。
/// </summary>
/// <param name="name">对象名称。</param>
/// <returns>要检查的对象是否存在。</returns>
public bool CanSpawn(string name)
{
List<Object<T>> objects = GetObjects(name);
if (objects != null)
{
foreach (Object<T> internalObject in objects)
{
if (m_AllowMultiSpawn || !internalObject.IsInUse)
{
return true;
}
}
}
return false;
}
/// <summary>
/// 获取对象。
/// </summary>
/// <returns>要获取的对象。</returns>
public T Spawn()
{
return Spawn(string.Empty);
}
/// <summary>
/// 获取对象。
/// </summary>
/// <param name="name">对象名称。</param>
/// <returns>要获取的对象。</returns>
public T Spawn(string name)
{
List<Object<T>> objects = GetObjects(name);
if (objects != null)
{
foreach (Object<T> internalObject in objects)
{
if (m_AllowMultiSpawn || !internalObject.IsInUse)
{
return internalObject.Spawn();
}
}
}
return null;
}
/// <summary>
/// 回收对象。
/// </summary>
/// <param name="obj">要回收的对象。</param>
public void Unspawn(T obj)
{
if (obj == null)
{
throw new GameFrameworkException("Object is invalid.");
}
Unspawn(obj.Target);
}
/// <summary>
/// 回收对象。
/// </summary>
/// <param name="target">要回收的对象。</param>
public void Unspawn(object target)
{
if (target == null)
{
throw new GameFrameworkException("Target is invalid.");
}
Object<T> internalObject = GetObject(target);
if (internalObject != null)
{
internalObject.Unspawn();
if (Count > m_Capacity && internalObject.SpawnCount <= 0)
{
Release();
}
}
else
{
throw new GameFrameworkException(Utility.Text.Format("Can not find target in object pool '{0}', target type is '{1}', target value is '{2}'.", Utility.Text.GetFullName<T>(Name), target.GetType().FullName, target.ToString()));
}
}
/// <summary>
/// 设置对象是否被加锁。
/// </summary>
/// <param name="obj">要设置被加锁的对象。</param>
/// <param name="locked">是否被加锁。</param>
public void SetLocked(T obj, bool locked)
{
if (obj == null)
{
throw new GameFrameworkException("Object is invalid.");
}
SetLocked(obj.Target, locked);
}
/// <summary>
/// 设置对象是否被加锁。
/// </summary>
/// <param name="target">要设置被加锁的对象。</param>
/// <param name="locked">是否被加锁。</param>
public void SetLocked(object target, bool locked)
{
if (target == null)
{
throw new GameFrameworkException("Target is invalid.");
}
Object<T> internalObject = GetObject(target);
if (internalObject != null)
{
internalObject.Locked = locked;
}
else
{
throw new GameFrameworkException(Utility.Text.Format("Can not find target in object pool '{0}', target type is '{1}', target value is '{2}'.", Utility.Text.GetFullName<T>(Name), target.GetType().FullName, target.ToString()));
}
}
/// <summary>
/// 设置对象的优先级。
/// </summary>
/// <param name="obj">要设置优先级的对象。</param>
/// <param name="priority">优先级。</param>
public void SetPriority(T obj, int priority)
{
if (obj == null)
{
throw new GameFrameworkException("Object is invalid.");
}
SetPriority(obj.Target, priority);
}
/// <summary>
/// 设置对象的优先级。
/// </summary>
/// <param name="target">要设置优先级的对象。</param>
/// <param name="priority">优先级。</param>
public void SetPriority(object target, int priority)
{
if (target == null)
{
throw new GameFrameworkException("Target is invalid.");
}
Object<T> internalObject = GetObject(target);
if (internalObject != null)
{
internalObject.Priority = priority;
}
else
{
throw new GameFrameworkException(Utility.Text.Format("Can not find target in object pool '{0}', target type is '{1}', target value is '{2}'.", Utility.Text.GetFullName<T>(Name), target.GetType().FullName, target.ToString()));
}
}
/// <summary>
/// 释放对象池中的可释放对象。
/// </summary>
public override void Release()
{
Release(Count - m_Capacity, m_DefaultReleaseObjectFilterCallback);
}
/// <summary>
/// 释放对象池中的可释放对象。
/// </summary>
/// <param name="toReleaseCount">尝试释放对象数量。</param>
public override void Release(int toReleaseCount)
{
Release(toReleaseCount, m_DefaultReleaseObjectFilterCallback);
}
/// <summary>
/// 释放对象池中的可释放对象。
/// </summary>
/// <param name="releaseObjectFilterCallback">释放对象筛选函数。</param>
public void Release(ReleaseObjectFilterCallback<T> releaseObjectFilterCallback)
{
Release(Count - m_Capacity, releaseObjectFilterCallback);
}
/// <summary>
/// 释放对象池中的可释放对象。
/// </summary>
/// <param name="toReleaseCount">尝试释放对象数量。</param>
/// <param name="releaseObjectFilterCallback">释放对象筛选函数。</param>
public void Release(int toReleaseCount, ReleaseObjectFilterCallback<T> releaseObjectFilterCallback)
{
if (releaseObjectFilterCallback == null)
{
throw new GameFrameworkException("Release object filter callback is invalid.");
}
if (toReleaseCount < 0)
{
toReleaseCount = 0;
}
DateTime expireTime = DateTime.MinValue;
if (m_ExpireTime < float.MaxValue)
{
expireTime = DateTime.Now.AddSeconds(-m_ExpireTime);
}
m_AutoReleaseTime = 0f;
GetCanReleaseObjects(m_CachedCanReleaseObjects);
List<T> toReleaseObjects = releaseObjectFilterCallback(m_CachedCanReleaseObjects, toReleaseCount, expireTime);
if (toReleaseObjects == null || toReleaseObjects.Count <= 0)
{
return;
}
foreach (T toReleaseObject in toReleaseObjects)
{
ReleaseObject(toReleaseObject);
}
}
/// <summary>
/// 释放对象池中的所有未使用对象。
/// </summary>
public override void ReleaseAllUnused()
{
m_AutoReleaseTime = 0f;
GetCanReleaseObjects(m_CachedCanReleaseObjects);
foreach (T toReleaseObject in m_CachedCanReleaseObjects)
{
ReleaseObject(toReleaseObject);
}
}
/// <summary>
/// 获取所有对象信息。
/// </summary>
/// <returns>所有对象信息。</returns>
public override ObjectInfo[] GetAllObjectInfos()
{
List<ObjectInfo> results = new List<ObjectInfo>();
foreach (KeyValuePair<string, List<Object<T>>> objects in m_Objects)
{
foreach (Object<T> internalObject in objects.Value)
{
results.Add(new ObjectInfo(internalObject.Name, internalObject.Locked, internalObject.CustomCanReleaseFlag, internalObject.Priority, internalObject.LastUseTime, internalObject.SpawnCount));
}
}
return results.ToArray();
}
internal override void Update(float elapseSeconds, float realElapseSeconds)
{
m_AutoReleaseTime += realElapseSeconds;
if (m_AutoReleaseTime < m_AutoReleaseInterval)
{
return;
}
Release();
}
internal override void Shutdown()
{
foreach (KeyValuePair<object, Object<T>> objectInMap in m_ObjectMap)
{
objectInMap.Value.Release(true);
ReferencePool.Release(objectInMap.Value);
}
m_Objects.Clear();
m_ObjectMap.Clear();
}
private List<Object<T>> GetObjects(string name)
{
if (name == null)
{
throw new GameFrameworkException("Name is invalid.");
}
List<Object<T>> objects = null;
if (m_Objects.TryGetValue(name, out objects))
{
return objects;
}
return null;
}
private Object<T> GetObject(object target)
{
if (target == null)
{
throw new GameFrameworkException("Target is invalid.");
}
Object<T> internalObject = null;
if (m_ObjectMap.TryGetValue(target, out internalObject))
{
return internalObject;
}
return null;
}
private void ReleaseObject(T obj)
{
if (obj == null)
{
throw new GameFrameworkException("Object is invalid.");
}
List<Object<T>> objects = GetObjects(obj.Name);
Object<T> internalObject = GetObject(obj.Target);
if (objects != null && internalObject != null)
{
objects.Remove(internalObject);
m_ObjectMap.Remove(obj.Target);
if (objects.Count <= 0)
{
m_Objects.Remove(obj.Name);
}
internalObject.Release(false);
ReferencePool.Release(internalObject);
return;
}
throw new GameFrameworkException("Can not release object which is not found.");
}
private void GetCanReleaseObjects(List<T> results)
{
if (results == null)
{
throw new GameFrameworkException("Results is invalid.");
}
results.Clear();
foreach (KeyValuePair<object, Object<T>> objectInMap in m_ObjectMap)
{
Object<T> internalObject = objectInMap.Value;
if (internalObject.IsInUse || internalObject.Locked || !internalObject.CustomCanReleaseFlag)
{
continue;
}
results.Add(internalObject.Peek());
}
}
private List<T> DefaultReleaseObjectFilterCallback(List<T> candidateObjects, int toReleaseCount, DateTime expireTime)
{
m_CachedToReleaseObjects.Clear();
if (expireTime > DateTime.MinValue)
{
for (int i = candidateObjects.Count - 1; i >= 0; i--)
{
if (candidateObjects[i].LastUseTime <= expireTime)
{
m_CachedToReleaseObjects.Add(candidateObjects[i]);
candidateObjects.RemoveAt(i);
continue;
}
}
toReleaseCount -= m_CachedToReleaseObjects.Count;
}
for (int i = 0; toReleaseCount > 0 && i < candidateObjects.Count; i++)
{
for (int j = i + 1; j < candidateObjects.Count; j++)
{
if (candidateObjects[i].Priority > candidateObjects[j].Priority
|| candidateObjects[i].Priority == candidateObjects[j].Priority && candidateObjects[i].LastUseTime > candidateObjects[j].LastUseTime)
{
T temp = candidateObjects[i];
candidateObjects[i] = candidateObjects[j];
candidateObjects[j] = temp;
}
}
m_CachedToReleaseObjects.Add(candidateObjects[i]);
toReleaseCount--;
}
return m_CachedToReleaseObjects;
}
}
}
}
| 33.670906 | 245 | 0.435479 | [
"MIT"
] | GameDeveloperS001/GameFramework | GameFramework/ObjectPool/ObjectPoolManager.ObjectPool.cs | 22,224 | C# |
using UnityEngine;
namespace MBaske.Sensors.Grid
{
/// <summary>
/// Detects gameobjects located on a plane.
/// </summary>
public class GameObjectDetector2D : GameObjectDetector
{
/// <summary>
/// Whether and how to rotate detection bounds with the sensor component.
/// </summary>
public enum SensorRotationType
{
AgentY, AgentXYZ, None
}
/// <summary>
/// Whether and how to rotate detection bounds with the sensor component.
/// </summary>
public SensorRotationType RotationType
{
set { m_RotationType = value; }
}
private SensorRotationType m_RotationType;
/// <summary>
/// The world rotation to use if <see cref="Detector2DRotationType"/>
/// is set to <see cref="Detector2DRotationType.None"/>.
/// </summary>
public Quaternion WorldRotation
{
set { m_WorldRotation = value; }
}
private Quaternion m_WorldRotation;
/// <summary>
/// Constraint for box / 2D detection.
/// </summary>
public DetectionConstraint2D Constraint
{
set
{
m_Constraint = value;
m_BoundsCenter = value.Bounds.center;
m_BoundsExtents = value.Bounds.extents;
}
}
private DetectionConstraint2D m_Constraint;
private Vector3 m_BoundsCenter;
private Vector3 m_BoundsExtents;
/// <inheritdoc/>
public override void OnSensorUpdate()
{
base.OnSensorUpdate();
Quaternion rotation = m_WorldRotation;
switch (m_RotationType)
{
case SensorRotationType.AgentY:
rotation = Quaternion.AngleAxis(m_Transform.eulerAngles.y, Vector3.up);
break;
case SensorRotationType.AgentXYZ:
rotation = m_Transform.rotation;
break;
}
Vector3 position = m_Transform.position;
Matrix4x4 worldToLocalMatrix = Matrix4x4.TRS(position, rotation, Vector3.one).inverse;
int numFound = 0;
do
{
ValidateColliderBufferSize(numFound);
numFound = Physics.OverlapBoxNonAlloc(
position + rotation * m_BoundsCenter,
m_BoundsExtents,
m_ColliderBuffer,
rotation,
m_LayerMask);
}
while (numFound == m_ColliderBufferSize);
ParseColliders(numFound, m_Constraint, worldToLocalMatrix);
}
}
}
| 30.555556 | 98 | 0.542909 | [
"MIT"
] | mbaske/grid-sensor | Assets/Scripts/Sensors/Grid/GameObject/Detection/GameObjectDetector2D.cs | 2,750 | C# |
using System;
using System.ComponentModel.Composition;
using System.Waf.Applications;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Waf.DotNetPad.Applications.ViewModels;
using Waf.DotNetPad.Applications.Views;
using Waf.DotNetPad.Domain;
namespace Waf.DotNetPad.Presentation.Views
{
[Export(typeof(IErrorListView))]
public partial class ErrorListView : UserControl, IErrorListView
{
private readonly Lazy<ErrorListViewModel> viewModel;
public ErrorListView()
{
InitializeComponent();
viewModel = new Lazy<ErrorListViewModel>(() => ViewHelper.GetViewModel<ErrorListViewModel>(this));
}
public ErrorListViewModel ViewModel => viewModel.Value;
private void ErrorListDoubleClick(object sender, MouseButtonEventArgs e)
{
var element = e.OriginalSource as FrameworkElement;
if (element?.DataContext is ErrorListItem)
{
ViewModel.GotoErrorCommand.Execute(null);
}
}
}
}
| 28.897436 | 111 | 0.659272 | [
"MIT"
] | cnark/dotnetpad | src/DotNetPad/DotNetPad.Presentation/Views/ErrorListView.xaml.cs | 1,129 | 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("Workflow")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Workflow")]
[assembly: AssemblyCopyright("Copyright © 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("9791b0cf-c14f-4a93-9a4c-a82728888715")]
// 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")]
| 36.578947 | 84 | 0.743165 | [
"Apache-2.0"
] | kanewanggit/MbTcsClone | Core/Workflow/Properties/AssemblyInfo.cs | 1,393 | C# |
using System;
using UnityEngine;
using XLua;
namespace XLuaTest
{
[Hotfix(HotfixFlag.Stateless)]
public class StatefullTest
{
public StatefullTest()
{
}
public StatefullTest(int a, int b)
{
if (a > 0)
{
return;
}
Debug.Log("a=" + a.ToString());
if (b > 0)
{
return;
}
if (a + b > 0)
{
return;
}
Debug.Log("b=" + b.ToString());
}
public int AProp { get; set; }
public event Action<int, double> AEvent;
public int this[string field]
{
get
{
return 1;
}
set
{
}
}
public void Start()
{
}
private void Update()
{
}
public void GenericTest<T>(T a)
{
}
public static void StaticFunc(int a, int b)
{
}
public static void StaticFunc(string a, int b, int c)
{
}
~StatefullTest()
{
Debug.Log("~StatefullTest");
}
}
}
| 11.657534 | 55 | 0.551116 | [
"Apache-2.0"
] | Shadowrabbit/BigBiaDecompilation | Source/Assembly-CSharp/XLuaTest/StatefullTest.cs | 853 | C# |
using System;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
namespace DevRocks.Ocelot.MultiFileConfiguration
{
public static class ConfigurationBuilderExtensions
{
public static void AddOcelotConfig(this IConfigurationBuilder configurationBuilder, string path)
{
configurationBuilder.AddJsonFile("ocelot.json", false, true);
var files = new DirectoryInfo(path)
.EnumerateFiles("ocelot.*.json")
.ToList();
int offset = 1000;
foreach (var file in files)
{
configurationBuilder.AddJsonArrayFile(file.Name, offset, false, true);
offset += 1000;
}
}
private static void AddJsonArrayFile(this IConfigurationBuilder builder, string path, int offset,
bool optional,
bool reloadOnChange)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (string.IsNullOrEmpty(path))
{
throw new ArgumentException("File path must be a non-empty string", nameof(path));
}
builder.Add((Action<JsonArrayConfigurationSource>)(s =>
{
s.FileProvider = null;
s.Path = path;
s.Optional = optional;
s.ReloadOnChange = reloadOnChange;
s.Offset = offset;
s.ResolveFileProvider();
}));
}
}
}
| 30.941176 | 105 | 0.553232 | [
"MIT"
] | Serj-Tm/DevRocks.Ocelot.Extensions | DevRocks.Ocelot.MultiFileConfiguration/ConfigurationBuilderExtensions.cs | 1,580 | C# |
namespace FluentBehaviourTree
{
/// <summary>
/// Represents time. Used to pass time values to behaviour tree nodes.
/// </summary>
public struct TimeData
{
public TimeData(float deltaTime)
{
this.deltaTime = deltaTime;
}
public float deltaTime;
}
}
| 20 | 74 | 0.58125 | [
"MIT"
] | brock555/Fluent-Behaviour-Tree | src/TimeData.cs | 322 | C# |
using System.Linq;
using SharpSqlBuilder.Extensions;
using SharpSqlBuilder.Operators;
namespace SharpSqlBuilder.Blocks
{
/// <summary>
/// <example>SET ... = ..., ... = ...</example>
/// </summary>
public class UpdateColumnsBlock : CollectionBlock<UpdateColumnBlock>
{
public override string BuildSql(SqlOptions sqlOptions)
{
var entities = Entities.Select(c => $"{c.BuildSql(sqlOptions, FlowOptions.Construct(this))}");
var columns = string.Join($",{sqlOptions.NewLine()}{sqlOptions.Indent()}", entities);
var command = sqlOptions.Command("SET");
return $"{command}{sqlOptions.NewLine()}{sqlOptions.Indent()}{columns}";
}
}
} | 36.2 | 106 | 0.631215 | [
"MIT"
] | Zelenov/SharpSqlBuilder | SharpSqlBuilder/Blocks/UpdateColumnsBlock.cs | 726 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.