content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ServiceStack.Redis;
namespace KB.Tool.Redis
{
public class RedisSentinelProvider : IRedisProvider
{
private readonly ILoggerFactory _loggerFactory;
private readonly RedisSentinelOptions _options;
public RedisSentinelProvider(IOptions<RedisSentinelOptions> options, ILoggerFactory loggerFactory)
{
_options = options.Value;
_loggerFactory = loggerFactory;
}
public IRedisClientsManager CreateRedisClientsManager()
{
var sentinel = new Sentinel(_options.Hosts, _options.MasterName, _options.HostFilter, _loggerFactory);
return sentinel.GetRedisClientsManager(_options.ManualConnectionTimeout.GetValueOrDefault());
}
}
}
| 32.96 | 114 | 0.718447 | [
"Apache-2.0"
] | KunpengNovelSite/KBCMS | src/KB.Tool/Redis/RedisSentinelProvider.cs | 826 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sesv2-2019-09-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SimpleEmailV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleEmailV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// CreateDedicatedIpPool Request Marshaller
/// </summary>
public class CreateDedicatedIpPoolRequestMarshaller : IMarshaller<IRequest, CreateDedicatedIpPoolRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((CreateDedicatedIpPoolRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(CreateDedicatedIpPoolRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.SimpleEmailV2");
request.Headers["Content-Type"] = "application/json";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-09-27";
request.HttpMethod = "POST";
request.ResourcePath = "/v2/email/dedicated-ip-pools";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetPoolName())
{
context.Writer.WritePropertyName("PoolName");
context.Writer.Write(publicRequest.PoolName);
}
if(publicRequest.IsSetTags())
{
context.Writer.WritePropertyName("Tags");
context.Writer.WriteArrayStart();
foreach(var publicRequestTagsListValue in publicRequest.Tags)
{
context.Writer.WriteObjectStart();
var marshaller = TagMarshaller.Instance;
marshaller.Marshall(publicRequestTagsListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static CreateDedicatedIpPoolRequestMarshaller _instance = new CreateDedicatedIpPoolRequestMarshaller();
internal static CreateDedicatedIpPoolRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateDedicatedIpPoolRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.957627 | 157 | 0.614424 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/SimpleEmailV2/Generated/Model/Internal/MarshallTransformations/CreateDedicatedIpPoolRequestMarshaller.cs | 4,243 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace AskMe.Services.DTOs
{
public class CategoryDTO
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
}
}
| 15.25 | 41 | 0.70082 | [
"MIT"
] | rebelde96/AskMe | AskMe.Services/DTOs/CategoryDTO.cs | 246 | C# |
using System;
namespace DataCollection.Areas.HelpPage
{
/// <summary>
/// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class.
/// </summary>
public class InvalidSample
{
public InvalidSample(string errorMessage)
{
if (errorMessage == null)
{
throw new ArgumentNullException("errorMessage");
}
ErrorMessage = errorMessage;
}
public string ErrorMessage { get; private set; }
public override bool Equals(object obj)
{
InvalidSample other = obj as InvalidSample;
return other != null && ErrorMessage == other.ErrorMessage;
}
public override int GetHashCode()
{
return ErrorMessage.GetHashCode();
}
public override string ToString()
{
return ErrorMessage;
}
}
} | 26.378378 | 134 | 0.576844 | [
"MIT"
] | rohansen/Code-Examples | Security/Security - XSS SQL Injection Examples/DataCollection/DataCollection/Areas/HelpPage/SampleGeneration/InvalidSample.cs | 976 | C# |
using Npgsql;
namespace Tourist
{
public class AbstractTransaction
{
public NpgsqlTransaction transaction { get; set; }
public void Commit()
{
transaction.Commit();
}
public void Rollback()
{
transaction.Rollback();
}
}
}
| 15.9 | 58 | 0.525157 | [
"MIT"
] | betanets/tourist | Tourist/AbstractTransaction.cs | 320 | C# |
using System;
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// OtherLiability
/// </summary>
[Entity(SerializeWholeListWhenDirty = true)]
public sealed partial class OtherLiability : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _altId;
private DirtyValue<string?>? _attention;
private DirtyValue<decimal?>? _balance;
private DirtyValue<StringEnumValue<Owner>>? _borrowerType;
private DirtyValue<EntityReference?>? _contact;
private DirtyValue<string?>? _country;
private DirtyValue<decimal?>? _creditLimit;
private DirtyValue<DateTime?>? _depositoryRequestDate;
private DirtyValue<bool?>? _entityDeleted;
private DirtyValue<bool?>? _foreignAddressIndicator;
private DirtyValue<string?>? _holderAddressCity;
private DirtyValue<string?>? _holderAddressPostalCode;
private DirtyValue<StringEnumValue<State>>? _holderAddressState;
private DirtyValue<string?>? _holderAddressStreetLine1;
private DirtyValue<string?>? _holderEmail;
private DirtyValue<string?>? _holderFax;
private DirtyValue<string?>? _holderName;
private DirtyValue<string?>? _holderPhone;
private DirtyValue<string?>? _id;
private DirtyValue<StringEnumValue<LiabilityOrExpenseType>>? _liabilityOrExpenseType;
private DirtyValue<decimal?>? _monthlyPayment;
private DirtyValue<int?>? _monthsLeft;
private DirtyValue<string?>? _otherDescription;
private DirtyValue<bool?>? _printAttachmentIndicator;
private DirtyValue<bool?>? _printUserJobTitleIndicator;
private DirtyValue<bool?>? _printUserNameIndicator;
private DirtyValue<string?>? _title;
private DirtyValue<string?>? _titleFax;
private DirtyValue<string?>? _titlePhone;
/// <summary>
/// Other Liabilities ID [URLAROLNN99]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public string? AltId { get => _altId; set => SetField(ref _altId, value); }
/// <summary>
/// Depository Attention Contact [URLAROLNN06]
/// </summary>
public string? Attention { get => _attention; set => SetField(ref _attention, value); }
/// <summary>
/// Other Liabilities Balance [URLAROLNN20]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_2)]
public decimal? Balance { get => _balance; set => SetField(ref _balance, value); }
/// <summary>
/// Other Liabilities Borrower Type [URLAROLNN01]
/// </summary>
public StringEnumValue<Owner> BorrowerType { get => _borrowerType; set => SetField(ref _borrowerType, value); }
/// <summary>
/// OtherLiability Contact
/// </summary>
public EntityReference? Contact { get => _contact; set => SetField(ref _contact, value); }
/// <summary>
/// Other Liabilities Country [URLAROLNN22]
/// </summary>
public string? Country { get => _country; set => SetField(ref _country, value); }
/// <summary>
/// Other Liabilities Credit Limit [URLAROLNN21]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_2)]
public decimal? CreditLimit { get => _creditLimit; set => SetField(ref _creditLimit, value); }
/// <summary>
/// Depository Request Date [URLAROLNN98]
/// </summary>
public DateTime? DepositoryRequestDate { get => _depositoryRequestDate; set => SetField(ref _depositoryRequestDate, value); }
/// <summary>
/// OtherLiability EntityDeleted
/// </summary>
public bool? EntityDeleted { get => _entityDeleted; set => SetField(ref _entityDeleted, value); }
/// <summary>
/// Depository Foreign Address Indicator [URLAROLNN23]
/// </summary>
public bool? ForeignAddressIndicator { get => _foreignAddressIndicator; set => SetField(ref _foreignAddressIndicator, value); }
/// <summary>
/// Depository Attention City [URLAROLNN08]
/// </summary>
public string? HolderAddressCity { get => _holderAddressCity; set => SetField(ref _holderAddressCity, value); }
/// <summary>
/// Depository Attention Zipcode [URLAROLNN10]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)]
public string? HolderAddressPostalCode { get => _holderAddressPostalCode; set => SetField(ref _holderAddressPostalCode, value); }
/// <summary>
/// Depository Attention State [URLAROLNN09]
/// </summary>
public StringEnumValue<State> HolderAddressState { get => _holderAddressState; set => SetField(ref _holderAddressState, value); }
/// <summary>
/// Depository Address [URLAROLNN07]
/// </summary>
public string? HolderAddressStreetLine1 { get => _holderAddressStreetLine1; set => SetField(ref _holderAddressStreetLine1, value); }
/// <summary>
/// Depository Email [URLAROLNN13]
/// </summary>
public string? HolderEmail { get => _holderEmail; set => SetField(ref _holderEmail, value); }
/// <summary>
/// Depository Fax [URLAROLNN12]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? HolderFax { get => _holderFax; set => SetField(ref _holderFax, value); }
/// <summary>
/// Depository Name [URLAROLNN05]
/// </summary>
public string? HolderName { get => _holderName; set => SetField(ref _holderName, value); }
/// <summary>
/// Depository Phone [URLAROLNN11]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? HolderPhone { get => _holderPhone; set => SetField(ref _holderPhone, value); }
/// <summary>
/// OtherLiability Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Other Liabilities Liability or Expense Type [URLAROLNN02]
/// </summary>
public StringEnumValue<LiabilityOrExpenseType> LiabilityOrExpenseType { get => _liabilityOrExpenseType; set => SetField(ref _liabilityOrExpenseType, value); }
/// <summary>
/// Other Liabilities Monthly Payment [URLAROLNN03]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_2)]
public decimal? MonthlyPayment { get => _monthlyPayment; set => SetField(ref _monthlyPayment, value); }
/// <summary>
/// Months Left [URLAROLNN19]
/// </summary>
public int? MonthsLeft { get => _monthsLeft; set => SetField(ref _monthsLeft, value); }
/// <summary>
/// Other Liabilities Other Description [URLAROLNN04]
/// </summary>
public string? OtherDescription { get => _otherDescription; set => SetField(ref _otherDescription, value); }
/// <summary>
/// Depository Print - See Attached Authorization [URLAROLNN18]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Print \\\"See attached borrower's authorization\\\" on signature line.\"}")]
public bool? PrintAttachmentIndicator { get => _printAttachmentIndicator; set => SetField(ref _printAttachmentIndicator, value); }
/// <summary>
/// Depository Print User Job Title [URLAROLNN64]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Print user's job title\"}")]
public bool? PrintUserJobTitleIndicator { get => _printUserJobTitleIndicator; set => SetField(ref _printUserJobTitleIndicator, value); }
/// <summary>
/// Depository Print User Name as Title [URLAROLNN15]
/// </summary>
[LoanFieldProperty(OptionsJson = "{\"Y\":\"Print user's name as title\"}")]
public bool? PrintUserNameIndicator { get => _printUserNameIndicator; set => SetField(ref _printUserNameIndicator, value); }
/// <summary>
/// Depository From Title [URLAROLNN14]
/// </summary>
public string? Title { get => _title; set => SetField(ref _title, value); }
/// <summary>
/// Depository From Fax [URLAROLNN17]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? TitleFax { get => _titleFax; set => SetField(ref _titleFax, value); }
/// <summary>
/// Depository From Phone [URLAROLNN16]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? TitlePhone { get => _titlePhone; set => SetField(ref _titlePhone, value); }
}
} | 44.17 | 166 | 0.634367 | [
"MIT"
] | Oxymoron290/EncompassRest | src/EncompassRest/Loans/OtherLiability.cs | 8,834 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/**
* SceneAppearanceRules extends AppearanceRules by making sure the platform section transitions aling up with any section changes
*/
public class PlatformAppearanceRules : AppearanceRules {
private PlatformObject platformObject;
public override void init()
{
base.init();
platformObject = GetComponent<PlatformObject>();
}
// distance is the scene distance
public override bool canSpawnObject(float distance, ObjectSpawnData spawnData)
{
if (!base.canSpawnObject(distance, spawnData))
return false;
// If section transition is true a transition object must be found
if (spawnData.sectionTransition) {
if (platformObject.sectionTransition) {
// any transition is a section transition if there are no specific section transitions defined
if (platformObject.fromSection.Count == 0) {
return true;
}
// return true if the from section equals the previous section and matches up with the to section which equals the current section
// fromSection and toSection must be equal in size
for (int i = 0; i < platformObject.fromSection.Count; ++i) {
if (platformObject.fromSection[i] == spawnData.prevSection && platformObject.toSection[i] == spawnData.section) {
return true;
}
}
}
return false;
}
return !platformObject.sectionTransition;
}
}
| 36.326087 | 147 | 0.623579 | [
"MIT"
] | sundayliu/Unity-Runner | Assets/Infinite Runner/Scripts/InfiniteGenerator/PlatformAppearanceRules.cs | 1,671 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
namespace Microsoft.Diagnostics.Runtime
{
/// <summary>
/// The type of frame the ClrStackFrame represents.
/// </summary>
public enum ClrStackFrameType
{
/// <summary>
/// Indicates this stack frame is unknown
/// </summary>
Unknown = -1,
/// <summary>
/// Indicates this stack frame is a standard managed method.
/// </summary>
ManagedMethod = 0,
/// <summary>
/// Indicates this stack frame is a special stack marker that the Clr runtime leaves on the stack.
/// Note that the ClrStackFrame may still have a ClrMethod associated with the marker.
/// </summary>
Runtime = 1
}
/// <summary>
/// A frame in a managed stack trace. Note you can call ToString on an instance of this object to get the
/// function name (or clr!Frame name) similar to SOS's !clrstack output.
/// </summary>
public abstract class ClrStackFrame
{
/// <summary>
/// Returns the thread this stack frame came from.
/// </summary>
public abstract ClrThread Thread { get; }
/// <summary>
/// The instruction pointer of this frame.
/// </summary>
public abstract ulong InstructionPointer { get; }
/// <summary>
/// The stack pointer of this frame.
/// </summary>
public abstract ulong StackPointer { get; }
/// <summary>
/// The type of frame (managed or internal).
/// </summary>
public abstract ClrStackFrameType Kind { get; }
/// <summary>
/// The string to display in a stack trace. Similar to !clrstack output.
/// </summary>
public abstract string DisplayString { get; }
/// <summary>
/// Returns the ClrMethod which corresponds to the current stack frame. This may be null if the
/// current frame is actually a CLR "Internal Frame" representing a marker on the stack, and that
/// stack marker does not have a managed method associated with it.
/// </summary>
public abstract ClrMethod Method { get; }
/// <summary>
/// Returns the module name to use for building the stack trace.
/// </summary>
public virtual string ModuleName
{
get
{
if (Method == null || Method.Type == null || Method.Type.Module == null)
return UnknownModuleName;
string result = Method.Type.Module.Name;
try
{
return Path.GetFileNameWithoutExtension(result);
}
catch
{
return result;
}
}
}
/// <summary>
/// The default name used when a module name cannot be calculated.
/// </summary>
public static string UnknownModuleName = "UNKNOWN";
}
} | 33.3125 | 110 | 0.565041 | [
"MIT"
] | TylerAP/clrmd | src/Microsoft.Diagnostics.Runtime/src/Common/ClrStackFrame.cs | 3,200 | C# |
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using GraphQL.Language.AST;
using GraphQLParser;
using GraphQLParser.AST;
using OperationTypeParser = GraphQLParser.AST.OperationType;
using OperationType = GraphQL.Language.AST.OperationType;
namespace GraphQL.Language
{
public class CoreToVanillaConverter
{
private readonly ISource _body;
private CoreToVanillaConverter(string body)
{
_body = new Source(body);
}
public static Document Convert(string body, GraphQLDocument source)
{
var converter = new CoreToVanillaConverter(body);
var target = new Document();
converter.AddDefinitions(source, target);
return target;
}
public void AddDefinitions(GraphQLDocument source, Document target)
{
source.Definitions.Apply(def =>
{
if (def is GraphQLOperationDefinition op)
{
target.AddDefinition(Operation(op));
}
if (def is GraphQLFragmentDefinition frag)
{
target.AddDefinition(Fragment(frag));
}
});
}
public Operation Operation(GraphQLOperationDefinition source)
{
var name = source.Name != null ? Name(source.Name) : null;
var op = new Operation(name).WithLocation(source, _body);
op.OperationType = ToOperationType(source.Operation);
op.SelectionSet = SelectionSet(source.SelectionSet);
op.Variables = VariableDefinitions(source.VariableDefinitions);
op.Directives = Directives(source.Directives);
return op;
}
public FragmentDefinition Fragment(GraphQLFragmentDefinition source)
{
var frag = new FragmentDefinition(Name(source.Name)).WithLocation(source, _body);
frag.Type = NamedType(source.TypeCondition);
frag.SelectionSet = SelectionSet(source.SelectionSet);
frag.Directives = Directives(source.Directives);
return frag;
}
public FragmentSpread FragmentSpread(GraphQLFragmentSpread source)
{
var name = source.Name != null ? Name(source.Name) : null;
var spread = new FragmentSpread(name).WithLocation(source, _body);
spread.Directives = Directives(source.Directives);
return spread;
}
public InlineFragment InlineFragment(GraphQLInlineFragment source)
{
var frag = new InlineFragment().WithLocation(source, _body);
frag.Type = source.TypeCondition != null ? NamedType(source.TypeCondition) : null;
frag.Directives = Directives(source.Directives);
frag.SelectionSet = SelectionSet(source.SelectionSet);
return frag;
}
public VariableDefinitions VariableDefinitions(IEnumerable<GraphQLVariableDefinition> source)
{
var defs = new VariableDefinitions();
var list = source?.Select(VariableDefinition);
list?.Apply(defs.Add);
return defs;
}
public VariableDefinition VariableDefinition(GraphQLVariableDefinition source)
{
var def = new VariableDefinition(Name(source.Variable.Name)).WithLocation(source, _body);
def.Type = Type(source.Type);
if (source.DefaultValue is GraphQLValue val)
{
def.DefaultValue = Value(val);
}
else if (source.DefaultValue != null && !(source.DefaultValue is GraphQLValue))
{
throw new ExecutionError($"Unknown default value: {source.DefaultValue}");
}
return def;
}
public SelectionSet SelectionSet(GraphQLSelectionSet source)
{
var set = new SelectionSet().WithLocation(source, _body);
source?.Selections.Apply(s =>
{
set.Add(Selection(s));
});
return set;
}
public ISelection Selection(ASTNode source)
{
switch (source.Kind)
{
case ASTNodeKind.Field:
{
return Field((GraphQLFieldSelection) source);
}
case ASTNodeKind.FragmentSpread:
{
return FragmentSpread((GraphQLFragmentSpread) source);
}
case ASTNodeKind.InlineFragment:
{
return InlineFragment((GraphQLInlineFragment) source);
}
}
throw new ExecutionError($"Unmapped selection {source.Kind}");
}
public Field Field(GraphQLFieldSelection source)
{
var alias = source.Alias != null ? Name(source.Alias) : null;
var field = new Field(alias, Name(source.Name)).WithLocation(source, _body);
field.Arguments = Arguments(source.Arguments);
field.Directives = Directives(source.Directives);
field.SelectionSet = SelectionSet(source.SelectionSet);
return field;
}
public Directives Directives(IEnumerable<GraphQLDirective> directives)
{
var target = new Directives();
directives?.Apply(d =>
{
var dir = new Directive(Name(d.Name)).WithLocation(d, _body);
dir.Arguments = Arguments(d.Arguments);
target.Add(dir);
});
return target;
}
public Arguments Arguments(IEnumerable<GraphQLArgument> source)
{
var target = new Arguments();
source.Apply(s =>
{
var arg = new Argument(Name(s.Name)).WithLocation(s.Name, _body);
arg.Value = Value(s.Value);
target.Add(arg);
});
return target;
}
public IValue Value(GraphQLValue source)
{
switch (source.Kind)
{
case ASTNodeKind.StringValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
return new StringValue(str.Value).WithLocation(str, _body);
}
case ASTNodeKind.IntValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
if (int.TryParse(str.Value, out var intResult))
{
var val = new IntValue(intResult).WithLocation(str, _body);
return val;
}
// If the value doesn't fit in an integer, revert to using long...
if (long.TryParse(str.Value, out var longResult))
{
var val = new LongValue(longResult).WithLocation(str, _body);
return val;
}
throw new ExecutionError($"Invalid number {str.Value}");
}
case ASTNodeKind.FloatValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
return new FloatValue(ValueConverter.ConvertTo<double>(str.Value)).WithLocation(str, _body);
}
case ASTNodeKind.BooleanValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
return new BooleanValue(ValueConverter.ConvertTo<bool>(str.Value)).WithLocation(str, _body);
}
case ASTNodeKind.EnumValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
return new EnumValue(str.Value).WithLocation(str, _body);
}
case ASTNodeKind.Variable:
{
var vari = source as GraphQLVariable;
Debug.Assert(vari != null, nameof(vari) + " != null");
return new VariableReference(Name(vari.Name)).WithLocation(vari, _body);
}
case ASTNodeKind.ObjectValue:
{
var obj = source as GraphQLObjectValue;
Debug.Assert(obj != null, nameof(obj) + " != null");
var fields = obj.Fields.Select(ObjectField);
return new ObjectValue(fields).WithLocation(obj, _body);
}
case ASTNodeKind.ListValue:
{
var list = source as GraphQLListValue;
Debug.Assert(list != null, nameof(list) + " != null");
var values = list.Values.Select(Value);
return new ListValue(values).WithLocation(list, _body);
}
case ASTNodeKind.NullValue:
{
var str = source as GraphQLScalarValue;
return new NullValue().WithLocation(str, _body);
}
}
throw new ExecutionError($"Unmapped value type {source.Kind}");
}
public ObjectField ObjectField(GraphQLObjectField source)
{
var field = new ObjectField(Name(source.Name), Value(source.Value)).WithLocation(source, _body);
return field;
}
public NamedType NamedType(GraphQLNamedType source)
{
var type = new NamedType(Name(source.Name)).WithLocation(source, _body);
return type;
}
public IType Type(GraphQLType type)
{
switch (type.Kind)
{
case ASTNodeKind.NamedType:
{
var name = (GraphQLNamedType) type;
return new NamedType(Name(name.Name)).WithLocation(name, _body);
}
case ASTNodeKind.NonNullType:
{
var nonNull = (GraphQLNonNullType) type;
return new NonNullType(Type(nonNull.Type)).WithLocation(nonNull, _body);
}
case ASTNodeKind.ListType:
{
var list = (GraphQLListType) type;
return new ListType(Type(list.Type)).WithLocation(list, _body);
}
}
throw new ExecutionError($"Unmapped type {type.Kind}");
}
public NameNode Name(GraphQLName name)
{
return new NameNode(name.Value).WithLocation(name, _body);
}
public static OperationType ToOperationType(OperationTypeParser type)
{
switch (type)
{
case OperationTypeParser.Query:
return OperationType.Query;
case OperationTypeParser.Mutation:
return OperationType.Mutation;
case OperationTypeParser.Subscription:
return OperationType.Subscription;
}
throw new ExecutionError($"Unmapped operation type {type}");
}
}
public static class AstNodeExtensions
{
public static T WithLocation<T>(this T node, ASTNode astNode, ISource source)
where T : AbstractNode
{
return node.WithLocation(0, 0, astNode?.Location.Start ?? -1, astNode?.Location.End ?? -1);
}
}
}
| 36.847826 | 112 | 0.533839 | [
"MIT"
] | Bill-Manning/graphql-dotnet | src/GraphQL/Language/CoreToVanillaConverter.cs | 11,865 | C# |
namespace OpenQA.Selenium.DevTools.Runtime
{
using Newtonsoft.Json;
/// <summary>
/// Add handler to promise with given promise object id.
/// </summary>
public sealed class AwaitPromiseCommandSettings : ICommand
{
private const string DevToolsRemoteInterface_CommandName = "Runtime.awaitPromise";
[JsonIgnore]
public string CommandName
{
get { return DevToolsRemoteInterface_CommandName; }
}
/// <summary>
/// Identifier of the promise.
/// </summary>
[JsonProperty("promiseObjectId")]
public string PromiseObjectId
{
get;
set;
}
/// <summary>
/// Whether the result is expected to be a JSON object that should be sent by value.
/// </summary>
[JsonProperty("returnByValue", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool? ReturnByValue
{
get;
set;
}
/// <summary>
/// Whether preview should be generated for the result.
/// </summary>
[JsonProperty("generatePreview", DefaultValueHandling = DefaultValueHandling.Ignore)]
public bool? GeneratePreview
{
get;
set;
}
}
public sealed class AwaitPromiseCommandResponse : ICommandResponse<AwaitPromiseCommandSettings>
{
/// <summary>
/// Promise result. Will contain rejected value if promise was rejected.
///</summary>
[JsonProperty("result")]
public RemoteObject Result
{
get;
set;
}
/// <summary>
/// Exception details if stack strace is available.
///</summary>
[JsonProperty("exceptionDetails", DefaultValueHandling = DefaultValueHandling.Ignore)]
public ExceptionDetails ExceptionDetails
{
get;
set;
}
}
} | 29.117647 | 99 | 0.569697 | [
"Apache-2.0"
] | 418sec/selenium | dotnet/src/webdriver/DevTools/AutoGenerated/Runtime/AwaitPromiseCommand.cs | 1,980 | C# |
using AudioReminderCore.Model;
using AudioReminderService.Persistence;
using AudioReminderService.Scheduler.TimerBased.DateTimeArithmetic;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace AudioReminderService.Scheduler.TimerBased.ReminderScheduling
{
//TODO: optimize later so that one dismiss does not cause recreating of all timers
//TODO: draw detailed state diagram for all this...
//TODO: check again if same timestamp is everwhere passed and used in complete algorightm to prevent contradicting situations that some condition is true and few lines later the same condition is false
//TODO: subscribing to and handlign system clock changes, especially when we go back in time
//TODO: add more unit tests, and plotting of methods as graph f(x) = y to find edge cases
//TODO: After e.g. 1 year of not using service shoud we show that all recuring reminders are missed?
//TODO: review logging at method start and end after work is broken to threads
class ReminderScheduler
{
public event Action<string> RingingNeeded;
protected NextReminderNotifier NextReminderNotifier { get; set; }
protected UserInteractionManager UserInteractionManager { get; set; }
protected bool IsEnabled { get; set; }
public ReminderScheduler()
{
Log.Logger.Information($"Creating ReminderScheduler");
IsEnabled = false;
NextReminderNotifier = new NextReminderNotifier();
UserInteractionManager = new UserInteractionManager();
NextReminderNotifier.ReminderElapsed += UserInteractionManager.OnReminderElapsed;
UserInteractionManager.RingingNeeded += OnRingingNeeded;
Log.Logger.Information($"Creating ReminderScheduler done");
}
protected void OnRingingNeeded(string reminderName)
{
RingingNeeded?.Invoke(reminderName);
}
public void Start()
{
Log.Logger.Information("Starting ReminderScheduler");
//good to be constant in a variable during this analysis in method so that it doesn't change during analysis. It could make some kind of timer deadlock where timer would never ring.
//TODO: should we change IsEnabled to Start/Stop methods so that we can pass this
DateTime now = DateTime.UtcNow;
if (IsEnabled)
{
Log.Logger.Warning("ReminderScheduler is already running.");
return;
}
IsEnabled = true;
NextReminderNotifier.IsEnabled = true;
UserInteractionManager.IsEnabled = true;
Log.Logger.Information("Starting ReminderScheduler done");
}
public void Stop()
{
Log.Logger.Information("Stopping ReminderScheduler");
if (!IsEnabled)
{
Log.Logger.Warning("ReminderScheduler is already stopped.");
return;
}
IsEnabled = false;
NextReminderNotifier.IsEnabled = false;
UserInteractionManager.IsEnabled = false;
Log.Logger.Information("Stopping ReminderScheduler done");
}
public void DismissReminder(ReminderEntity reminderEntity)
{
UserInteractionManager.DismissReminder(reminderEntity);
}
public void SnoozeReminder(ReminderEntity reminderEntity)
{
UserInteractionManager.SnoozeReminder(reminderEntity);
}
public void UpdateReminderList(IList<ReminderEntity> upToDateReminders)
{
NextReminderNotifier.UpdateReminderList(upToDateReminders);
//UserInteractionManager is indirectly updated from events of NextReminderNotifier. When a reminder is changed it will fire a new event for it.
//UserInteractionManager.UpdateReminderList(upToDateReminders);
}
/// <summary>
/// Returns false when reminder is elapsed but not yet dismissed
/// </summary>
public bool IsOkToModifyReminder(string reminderName)
{
return UserInteractionManager.IsOkToModifyReminder(reminderName);
}
public virtual void ConfigureSnooze(bool snoozeEnabled, int snoozeIntervalMinutes)
{
UserInteractionManager.ConfigureSnooze(snoozeEnabled, snoozeIntervalMinutes);
}
}
}
| 36.878049 | 205 | 0.67284 | [
"MIT"
] | dupop/audio-reminder | AudioReminderService/Scheduler/TimerBased/ReminderScheduling/ReminderScheduler.cs | 4,538 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CustomUI.BeatSaber;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Collections;
namespace SaberForge
{
class HelpMainViewController : CustomViewController
{
protected override void DidActivate(bool firstActivation, ActivationType type)
{
base.DidActivate(firstActivation, type);
if (firstActivation) FirstActivation();
}
private void FirstActivation()
{
string helpText = "<size=150%><b>Instructions</b> \n" +
"\n" +
"<size=120%>1 - Adjust your sabers using the options provided in Saber Forge.\n" +
"\n" +
"2 - Open the Custom Sabers mod menu and choose the 'Saber Forge' sabers. \n" +
"\n" +
"3 - Hit bloq"
;
RectTransform verticalLayout = UIFunctions.CreateVerticalLayoutObj(new RectOffset(6, 6, 6, 6), 1, TextAnchor.UpperCenter);
UIFunctions.SetRect(verticalLayout, transform, new Vector2(0, 1), new Vector2(0, 1), new Vector2(85, -40), new Vector2(150, 80));
TextMeshProUGUI matLabelText = BeatSaberUI.CreateText(verticalLayout, helpText, new Vector2(0, 0), new Vector2(100, 80));
//format
matLabelText.alignment = TextAlignmentOptions.Top;
//donate button
Button donate = BeatSaberUI.CreateUIButton(transform as RectTransform, "PlayButton", new Vector2(-50, -33), new Vector2(50, 16), null, "DONATE <3");
donate.onClick.AddListener(() => { GoTo("https://ko-fi.com/frostdragonliz", donate); });
BeatSaberUI.AddHintText(donate.transform as RectTransform, "Kofi $$ will go towards future mod and part development, ta!");
//reload assets button TO DO
// Button reload = BeatSaberUI.CreateUIButton(transform as RectTransform, "PlayButton", new Vector2(0, -33), new Vector2(50, 16), null, "USER TEXTURES");
// reload.onClick.AddListener(() => { Plugin.ReloadAssets(); });
// BeatSaberUI.AddHintText(reload.transform as RectTransform, "Force a reload of SaberForge Assets");
//tutes button
Button tutorials = BeatSaberUI.CreateUIButton(transform as RectTransform, "PlayButton", new Vector2(8, -33), new Vector2(50, 16), null, "TUTORIALS");
tutorials.onClick.AddListener(() => { GoTo("https://www.youtube.com/playlist?list=PLyJh_4G6B76PPdL-rAmb44-475D0_0UBs", tutorials); });
BeatSaberUI.AddHintText(tutorials.transform as RectTransform, "YouTube Tutorials");
//github button
Button github = BeatSaberUI.CreateUIButton(transform as RectTransform, "PlayButton", new Vector2(60, -33), new Vector2(50, 16), null, "SOURCE");
github.onClick.AddListener(() => { GoTo("https://github.com/lizfrost/SaberForge", github); });
BeatSaberUI.AddHintText(github.transform as RectTransform, "Source and mod info");
}
//Counters plus yoinked :3
private void GoTo(string url, Button button)
{
button.interactable = false;
TextMeshProUGUI reminder = BeatSaberUI.CreateText(transform as RectTransform, "Link opened in your browser!", new Vector2(0, -25), new Vector2(16, 16));
reminder.fontSize = 4;
reminder.alignment = TextAlignmentOptions.Center;
this.StartCoroutine(SecondRemove(reminder.gameObject, button));
System.Diagnostics.Process.Start(url);
}
private IEnumerator SecondRemove(GameObject go, Button button)
{
yield return new WaitForSeconds(5);
Destroy(go);
button.interactable = true;
}
}
}
| 40.87234 | 164 | 0.641333 | [
"MIT"
] | lizfrost/SaberForge | SaberForge/UI/HelpMainViewController.cs | 3,844 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Azure.Storage.Sas
{
/// <summary>
/// Defines the protocols permitted for Storage requests made with a shared
/// access signature.
/// </summary>
public enum SasProtocol
{
/// <summary>
/// No protocol has been specified. If no value is specified,
/// the service will default to HttpsAndHttp.
/// </summary>
None = 0,
/// <summary>
/// Only requests issued over HTTPS or HTTP will be permitted.
/// </summary>
HttpsAndHttp = 1,
/// <summary>
/// Only requests issued over HTTPS will be permitted.
/// </summary>
Https = 2
}
/// <summary>
/// Extension methods for AccountSasResourceTypes enum
/// </summary>
internal static partial class SasExtensions
{
private const string NoneName = null;
private const string HttpsName = "https";
private const string HttpsAndHttpName = "https,http";
/// <summary>
/// Gets a string representation of the protocol.
/// </summary>
/// <returns>A string representation of the protocol.</returns>
internal static string ToProtocolString(this SasProtocol protocol)
{
switch (protocol)
{
case SasProtocol.Https:
return HttpsName;
case SasProtocol.HttpsAndHttp:
return HttpsAndHttpName;
case SasProtocol.None:
default:
return null;
}
}
/// <summary>
/// Parse a string representation of a protocol.
/// </summary>
/// <param name="s">A string representation of a protocol.</param>
/// <returns>A <see cref="SasProtocol"/>.</returns>
public static SasProtocol ParseProtocol(string s)
{
switch (s)
{
case NoneName:
case "":
return SasProtocol.None;
case HttpsName:
return SasProtocol.Https;
case HttpsAndHttpName:
return SasProtocol.HttpsAndHttp;
default:
throw Errors.InvalidSasProtocol(nameof(s), nameof(SasProtocol));
}
}
}
}
| 31.532468 | 84 | 0.537068 | [
"MIT"
] | Azkel/azure-sdk-for-net | sdk/storage/Azure.Storage.Common/src/Sas/SasProtocol.cs | 2,430 | C# |
namespace P01_StudentSystem.Data.Models.Configurations
{
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class StudentsCoursesConfiguration : IEntityTypeConfiguration<StudentCourse>
{
public void Configure(EntityTypeBuilder<StudentCourse> builder)
{
builder
.ToTable("StudentsCourses")
.HasKey(sc => new { sc.StudentId, sc.CourseId });
builder
.HasOne(sc => sc.Student)
.WithMany(s => s.CourseEnrollments)
.HasForeignKey(sc => sc.StudentId);
builder
.HasOne(sc => sc.Course)
.WithMany(c => c.StudentsEnrolled)
.HasForeignKey(sc => sc.CourseId);
}
}
}
| 31.307692 | 87 | 0.584767 | [
"MIT"
] | Pazzobg/03.01.CSharp-DB-Advanced-Entity-Framework | 08. EF Core Entity Relations-Exercise/P01_StudentSystem.Data/Models/Configurations/StudentCoursesConfiguration.cs | 816 | C# |
using System;
using System.ComponentModel;
using GraphQL;
using GraphQL.DI;
using Shouldly;
using Xunit;
namespace DIObjectGraphTypeTests
{
public class Graph : DIObjectGraphTypeTestBase
{
[Fact]
public void GraphName()
{
Configure<CGraphName, object>().Name.ShouldBe("TestGraphName");
}
[Name("TestGraphName")]
public class CGraphName : DIObjectGraphBase { }
[Fact]
public void GraphDefaultName()
{
Configure<CGraphDefaultName, object>().Name.ShouldBe("CGraphDefaultName");
new DIObjectGraphType<CGraphDefaultName>().Name.ShouldBe("CGraphDefaultName");
}
public class CGraphDefaultName : DIObjectGraphBase { }
[Fact]
public void GraphDefaultName2()
{
Configure<CGraphDefaultName2, Class1>().Name.ShouldBe("CGraphDefaultName2");
}
[Fact]
public void GraphDefaultName3()
{
Configure<CGraphDefaultNameGraph, object>().Name.ShouldBe("CGraphDefaultName");
new DIObjectGraphType<CGraphDefaultNameGraph>().Name.ShouldBe("CGraphDefaultName");
}
public class CGraphDefaultNameGraph : DIObjectGraphBase { }
public class CGraphDefaultName2 : DIObjectGraphBase<Class1> { }
public class Class1 { }
[Fact]
public void GraphDescription()
{
Configure<CGraphDescription, object>().Description.ShouldBe("TestGraphDescription");
}
[Description("TestGraphDescription")]
public class CGraphDescription : DIObjectGraphBase { }
[Fact]
public void GraphObsolete()
{
#pragma warning disable CS0618 // Member is obsolete
Configure<CGraphObsolete, object>().DeprecationReason.ShouldBe("TestDeprecationReason");
#pragma warning restore CS0618 // Member is obsolete
}
[Obsolete("TestDeprecationReason")]
public class CGraphObsolete : DIObjectGraphBase { }
[Fact]
public void GraphMetadata()
{
Configure<CGraphMetadata, object>().GetMetadata<string>("test").ShouldBe("value");
}
[Metadata("test", "value")]
public class CGraphMetadata : DIObjectGraphBase { }
public class CCanOverrideMembers : DIObjectGraphBase
{
public static string Field1() => "hello";
}
}
}
| 29.204819 | 100 | 0.62995 | [
"MIT"
] | Shane32/GraphQL.MVC | src/Tests/DIObjectGraphTypeTests/Graph.cs | 2,424 | C# |
namespace Blobfish
{
/// <summary>
/// Base class for all signable items with name and source data location. Implements ISignableItemWithName, ISourceDataLocation and ISignableItem indirectly through ISignableItemWithName.
/// </summary>
public abstract class ISignableItemWithNameAndISourceDataLocationBase : ISignableItemWithName, ISourceDataLocation
{
/// <summary>
/// Anchor point for digital signature. This identifier is referred to from the "Reference" element in a Signature. Unique per document.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Plain-text name of this item.
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// Points to the original data source. May be a file name, uri, database ID, etc.
/// </summary>
public string SourceDataLocation { get; set; }
}
}
| 39.291667 | 191 | 0.653234 | [
"Apache-2.0"
] | theigner/Blobfish | src/Blobfish/src/Interfaces/ISignableItemWithNameAndISourceDataLocationBase.cs | 945 | C# |
using System.Collections.Generic;
namespace GroupDocs.Viewer.UI.Core.Entities
{
public class DocumentInfo
{
public bool PrintAllowed { get; set; }
public IEnumerable<PageInfo> Pages { get; set; }
}
} | 21.818182 | 57 | 0.641667 | [
"MIT"
] | groupdocs-viewer/GroupDocs.Viewer-for-.NET-UI | src/GroupDocs.Viewer.UI.Core/Entities/DocumentInfo.cs | 242 | C# |
using CSharpWars.Validator.Helpers;
using CSharpWars.Validator.Helpers.Interfaces;
using CSharpWars.Validator.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace CSharpWars.Validator
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IScriptValidationHelper, ScriptValidationHelper>();
services.AddGrpc();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<ScriptValidatorService>();
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
});
endpoints.MapGet("/status", async context =>
{
await context.Response.WriteAsync(string.Empty);
});
});
}
}
} | 32.222222 | 215 | 0.615172 | [
"Unlicense"
] | Djohnnie/BuildCloudNativeApplicationsWithDotNet5-DotNetDeveloperDays-2020 | csharpwars/backend/CSharpWars/CSharpWars.Validator/Startup.cs | 1,452 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Square;
using Square.Utilities;
namespace Square.Models
{
public class ListSubscriptionEventsRequest
{
public ListSubscriptionEventsRequest(string cursor = null,
int? limit = null)
{
Cursor = cursor;
Limit = limit;
}
/// <summary>
/// A pagination cursor returned by a previous call to this endpoint.
/// Provide this to retrieve the next set of results for the original query.
/// For more information, see [Pagination](https://developer.squareup.com/docs/working-with-apis/pagination).
/// </summary>
[JsonProperty("cursor", NullValueHandling = NullValueHandling.Ignore)]
public string Cursor { get; }
/// <summary>
/// The upper limit on the number of subscription events to return
/// in the response.
/// Default: `200`
/// </summary>
[JsonProperty("limit", NullValueHandling = NullValueHandling.Ignore)]
public int? Limit { get; }
public override string ToString()
{
var toStringOutput = new List<string>();
this.ToString(toStringOutput);
return $"ListSubscriptionEventsRequest : ({string.Join(", ", toStringOutput)})";
}
protected void ToString(List<string> toStringOutput)
{
toStringOutput.Add($"Cursor = {(Cursor == null ? "null" : Cursor == string.Empty ? "" : Cursor)}");
toStringOutput.Add($"Limit = {(Limit == null ? "null" : Limit.ToString())}");
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (obj == this)
{
return true;
}
return obj is ListSubscriptionEventsRequest other &&
((Cursor == null && other.Cursor == null) || (Cursor?.Equals(other.Cursor) == true)) &&
((Limit == null && other.Limit == null) || (Limit?.Equals(other.Limit) == true));
}
public override int GetHashCode()
{
int hashCode = -1791054325;
if (Cursor != null)
{
hashCode += Cursor.GetHashCode();
}
if (Limit != null)
{
hashCode += Limit.GetHashCode();
}
return hashCode;
}
public Builder ToBuilder()
{
var builder = new Builder()
.Cursor(Cursor)
.Limit(Limit);
return builder;
}
public class Builder
{
private string cursor;
private int? limit;
public Builder Cursor(string cursor)
{
this.cursor = cursor;
return this;
}
public Builder Limit(int? limit)
{
this.limit = limit;
return this;
}
public ListSubscriptionEventsRequest Build()
{
return new ListSubscriptionEventsRequest(cursor,
limit);
}
}
}
} | 28.612903 | 118 | 0.5031 | [
"Apache-2.0"
] | HostMeApp/square-dotnet-sdk | Square/Models/ListSubscriptionEventsRequest.cs | 3,548 | C# |
using System;
using System.Globalization;
using System.Threading.Tasks;
using Qmmands;
namespace Disqord.Bot.Parsers
{
public sealed class ColorTypeParser : TypeParser<Color>
{
public static ColorTypeParser Instance => _instance ?? (_instance = new ColorTypeParser());
private static ColorTypeParser _instance;
private ColorTypeParser()
{ }
public override ValueTask<TypeParserResult<Color>> ParseAsync(Parameter parameter, string value, CommandContext context)
{
var valueSpan = value.AsSpan();
if (valueSpan.Length > 2)
{
var valid = false;
if (valueSpan[0] == '0' && (valueSpan[1] == 'x' || valueSpan[1] == 'X') && valueSpan.Length == 8)
{
valid = true;
valueSpan = valueSpan.Slice(2);
}
else if (value[0] == '#' && value.Length == 7)
{
valid = true;
valueSpan = valueSpan.Slice(1);
}
if (valid && int.TryParse(valueSpan, NumberStyles.HexNumber, null, out var result))
return TypeParserResult<Color>.Successful(result);
}
return TypeParserResult<Color>.Unsuccessful("Invalid color hex value provided.");
}
}
}
| 33.738095 | 129 | 0.527876 | [
"MIT"
] | GitNguyen/MudaeFarm | Disqord/src/Disqord.Bot/Commands/Parsers/ColorTypeParser.cs | 1,419 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, 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 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.451)
// Version 5.451.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Drawing.Design;
using System.ComponentModel;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Storage for label content value information.
/// </summary>
public class LabelValues : Storage,
IContentValues
{
#region Static Fields
private const string _defaultText = "Label";
private static readonly string _defaultExtraText = string.Empty;
#endregion
#region Instance Fields
private Image _image;
private Color _transparent;
private string _text;
private string _extraText;
#endregion
#region Events
/// <summary>
/// Occures when the value of the Text property changes.
/// </summary>
public event EventHandler TextChanged;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the LabelValues class.
/// </summary>
/// <param name="needPaint">Delegate for notifying paint requests.</param>
public LabelValues(NeedPaintHandler needPaint)
{
// Store the provided paint notification delegate
NeedPaint = needPaint;
// Set initial values
_image = null;
_transparent = Color.Empty;
_text = _defaultText;
_extraText = _defaultExtraText;
}
#endregion
#region IsDefault
/// <summary>
/// Gets a value indicating if all values are default.
/// </summary>
[Browsable(false)]
public override bool IsDefault => ((Image == null) &&
(ImageTransparentColor == Color.Empty) &&
(Text == _defaultText) &&
(ExtraText == _defaultExtraText));
#endregion
#region Image
/// <summary>
/// Gets and sets the label image.
/// </summary>
[Localizable(true)]
[Category("Visuals")]
[Description("Label image.")]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public Image Image
{
get => _image;
set
{
if (_image != value)
{
_image = value;
PerformNeedPaint(true);
}
}
}
private bool ShouldSerializeImage()
{
return Image != null;
}
/// <summary>
/// Resets the Image property to its default value.
/// </summary>
public void ResetImage()
{
Image = null;
}
/// <summary>
/// Gets the content image.
/// </summary>
/// <param name="state">The state for which the image is needed.</param>
/// <returns>Image value.</returns>
public Image GetImage(PaletteState state)
{
return Image;
}
#endregion
#region ImageTransparentColor
/// <summary>
/// Gets and sets the label image transparent color.
/// </summary>
[Localizable(true)]
[Category("Visuals")]
[Description("Label image transparent color.")]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[KryptonDefaultColorAttribute()]
public Color ImageTransparentColor
{
get => _transparent;
set
{
if (_transparent != value)
{
_transparent = value;
PerformNeedPaint(true);
}
}
}
private bool ShouldSerializeImageTransparentColor()
{
return ImageTransparentColor != Color.Empty;
}
/// <summary>
/// Resets the ImageTransparentColor property to its default value.
/// </summary>
public void ResetImageTransparentColor()
{
ImageTransparentColor = Color.Empty;
}
/// <summary>
/// Gets the content image transparent color.
/// </summary>
/// <param name="state">The state for which the image color is needed.</param>
/// <returns>Color value.</returns>
public Color GetImageTransparentColor(PaletteState state)
{
return ImageTransparentColor;
}
#endregion
#region Text
/// <summary>
/// Gets and sets the label text.
/// </summary>
[Localizable(true)]
[Category("Visuals")]
[Description("Label text.")]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public string Text
{
get => _text;
set
{
if (_text != value)
{
_text = value;
PerformNeedPaint(true);
TextChanged?.Invoke(this, EventArgs.Empty);
}
}
}
private bool ShouldSerializeText()
{
return Text != _defaultText;
}
/// <summary>
/// Resets the Text property to its default value.
/// </summary>
public void ResetText()
{
Text = _defaultText;
}
/// <summary>
/// Gets the content short text.
/// </summary>
public string GetShortText()
{
return Text;
}
#endregion
#region ExtraText
/// <summary>
/// Gets and sets the label extra text.
/// </summary>
[Localizable(true)]
[Category("Visuals")]
[Description("Label extra text.")]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
[DefaultValue("")]
public string ExtraText
{
get => _extraText;
set
{
if (_extraText != value)
{
_extraText = value;
PerformNeedPaint(true);
}
}
}
private bool ShouldSerializeExtraText()
{
return ExtraText != _defaultExtraText;
}
/// <summary>
/// Resets the Description property to its default value.
/// </summary>
public void ResetExtraText()
{
ExtraText = ExtraText;
}
/// <summary>
/// Gets the content long text.
/// </summary>
public string GetLongText()
{
return ExtraText;
}
#endregion
}
}
| 30.088462 | 174 | 0.519494 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.451 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Values/LabelValues.cs | 7,826 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the apigatewayv2-2018-11-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ApiGatewayV2.Model
{
/// <summary>
/// This is the response object from the ImportApi operation.
/// </summary>
public partial class ImportApiResponse : AmazonWebServiceResponse
{
private string _apiEndpoint;
private bool? _apiGatewayManaged;
private string _apiId;
private string _apiKeySelectionExpression;
private Cors _corsConfiguration;
private DateTime? _createdDate;
private string _description;
private bool? _disableExecuteApiEndpoint;
private bool? _disableSchemaValidation;
private List<string> _importInfo = new List<string>();
private string _name;
private ProtocolType _protocolType;
private string _routeSelectionExpression;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
private string _version;
private List<string> _warnings = new List<string>();
/// <summary>
/// Gets and sets the property ApiEndpoint.
/// <para>
/// The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The stage
/// name is typically appended to this URI to form a complete path to a deployed API stage.
/// </para>
/// </summary>
public string ApiEndpoint
{
get { return this._apiEndpoint; }
set { this._apiEndpoint = value; }
}
// Check to see if ApiEndpoint property is set
internal bool IsSetApiEndpoint()
{
return this._apiEndpoint != null;
}
/// <summary>
/// Gets and sets the property ApiGatewayManaged.
/// <para>
/// Specifies whether an API is managed by API Gateway. You can't update or delete a managed
/// API by using API Gateway. A managed API can be deleted only through the tooling or
/// service that created it.
/// </para>
/// </summary>
public bool ApiGatewayManaged
{
get { return this._apiGatewayManaged.GetValueOrDefault(); }
set { this._apiGatewayManaged = value; }
}
// Check to see if ApiGatewayManaged property is set
internal bool IsSetApiGatewayManaged()
{
return this._apiGatewayManaged.HasValue;
}
/// <summary>
/// Gets and sets the property ApiId.
/// <para>
/// The API ID.
/// </para>
/// </summary>
public string ApiId
{
get { return this._apiId; }
set { this._apiId = value; }
}
// Check to see if ApiId property is set
internal bool IsSetApiId()
{
return this._apiId != null;
}
/// <summary>
/// Gets and sets the property ApiKeySelectionExpression.
/// <para>
/// An API key selection expression. Supported only for WebSocket APIs. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions">API
/// Key Selection Expressions</a>.
/// </para>
/// </summary>
public string ApiKeySelectionExpression
{
get { return this._apiKeySelectionExpression; }
set { this._apiKeySelectionExpression = value; }
}
// Check to see if ApiKeySelectionExpression property is set
internal bool IsSetApiKeySelectionExpression()
{
return this._apiKeySelectionExpression != null;
}
/// <summary>
/// Gets and sets the property CorsConfiguration.
/// <para>
/// A CORS configuration. Supported only for HTTP APIs.
/// </para>
/// </summary>
public Cors CorsConfiguration
{
get { return this._corsConfiguration; }
set { this._corsConfiguration = value; }
}
// Check to see if CorsConfiguration property is set
internal bool IsSetCorsConfiguration()
{
return this._corsConfiguration != null;
}
/// <summary>
/// Gets and sets the property CreatedDate.
/// <para>
/// The timestamp when the API was created.
/// </para>
/// </summary>
public DateTime CreatedDate
{
get { return this._createdDate.GetValueOrDefault(); }
set { this._createdDate = value; }
}
// Check to see if CreatedDate property is set
internal bool IsSetCreatedDate()
{
return this._createdDate.HasValue;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of the API.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property DisableExecuteApiEndpoint.
/// <para>
/// Specifies whether clients can invoke your API by using the default execute-api endpoint.
/// By default, clients can invoke your API with the default https://{api_id}.execute-api.{region}.amazonaws.com
/// endpoint. To require that clients use a custom domain name to invoke your API, disable
/// the default endpoint.
/// </para>
/// </summary>
public bool DisableExecuteApiEndpoint
{
get { return this._disableExecuteApiEndpoint.GetValueOrDefault(); }
set { this._disableExecuteApiEndpoint = value; }
}
// Check to see if DisableExecuteApiEndpoint property is set
internal bool IsSetDisableExecuteApiEndpoint()
{
return this._disableExecuteApiEndpoint.HasValue;
}
/// <summary>
/// Gets and sets the property DisableSchemaValidation.
/// <para>
/// Avoid validating models when creating a deployment. Supported only for WebSocket APIs.
/// </para>
/// </summary>
public bool DisableSchemaValidation
{
get { return this._disableSchemaValidation.GetValueOrDefault(); }
set { this._disableSchemaValidation = value; }
}
// Check to see if DisableSchemaValidation property is set
internal bool IsSetDisableSchemaValidation()
{
return this._disableSchemaValidation.HasValue;
}
/// <summary>
/// Gets and sets the property ImportInfo.
/// <para>
/// The validation information during API import. This may include particular properties
/// of your OpenAPI definition which are ignored during import. Supported only for HTTP
/// APIs.
/// </para>
/// </summary>
public List<string> ImportInfo
{
get { return this._importInfo; }
set { this._importInfo = value; }
}
// Check to see if ImportInfo property is set
internal bool IsSetImportInfo()
{
return this._importInfo != null && this._importInfo.Count > 0;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the API.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property ProtocolType.
/// <para>
/// The API protocol.
/// </para>
/// </summary>
public ProtocolType ProtocolType
{
get { return this._protocolType; }
set { this._protocolType = value; }
}
// Check to see if ProtocolType property is set
internal bool IsSetProtocolType()
{
return this._protocolType != null;
}
/// <summary>
/// Gets and sets the property RouteSelectionExpression.
/// <para>
/// The route selection expression for the API. For HTTP APIs, the routeSelectionExpression
/// must be ${request.method} ${request.path}. If not provided, this will be the default
/// for HTTP APIs. This property is required for WebSocket APIs.
/// </para>
/// </summary>
public string RouteSelectionExpression
{
get { return this._routeSelectionExpression; }
set { this._routeSelectionExpression = value; }
}
// Check to see if RouteSelectionExpression property is set
internal bool IsSetRouteSelectionExpression()
{
return this._routeSelectionExpression != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// A collection of tags associated with the API.
/// </para>
/// </summary>
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property Version.
/// <para>
/// A version identifier for the API.
/// </para>
/// </summary>
public string Version
{
get { return this._version; }
set { this._version = value; }
}
// Check to see if Version property is set
internal bool IsSetVersion()
{
return this._version != null;
}
/// <summary>
/// Gets and sets the property Warnings.
/// <para>
/// The warning messages reported when failonwarnings is turned on during API import.
/// </para>
/// </summary>
public List<string> Warnings
{
get { return this._warnings; }
set { this._warnings = value; }
}
// Check to see if Warnings property is set
internal bool IsSetWarnings()
{
return this._warnings != null && this._warnings.Count > 0;
}
}
} | 32.886686 | 264 | 0.574899 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/ApiGatewayV2/Generated/Model/ImportApiResponse.cs | 11,609 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using nulloader;
using System.Windows.Forms;
using System.Drawing;
using System.Text.RegularExpressions;
namespace calculus
{
public class UserAction : Attribute
{
public string Name { get; private set; }
public UserAction()
{
Name = null;
}
public UserAction(string Name)
{
this.Name = Name;
}
}
public class Calculus : Plugin, IPluginIcon
{
public Calculus()
{
//expressions = (RichTextBox)FindControlByName("expressionTextBox");
OperateOnControl(CreateEditorTab("Calculus"), tab =>
{
var calculuspanel = new CalculusPanel { Parent = tab, Dock = DockStyle.Fill };
Expressions.CurrentChanged += (s, e) =>
{
calculuspanel.textBox1.Text = Expressions.CurrentExpression;
};
foreach (var method_attrs in GetType().GetMethods()
.Select(x => new { Method = x, Attr = x.GetCustomAttributes(typeof(UserAction), true).FirstOrDefault() as UserAction })
.Where(x => x.Attr != null))
{
var method = method_attrs.Method;
var button = new Button { Text = method_attrs.Attr.Name ?? method.Name, Width = 120 };
button.Click += (s, e) => method.Invoke(this, new object[0]);
calculuspanel.flowLayoutPanel1.Controls.Add(button);
}
});
TwoDimensionalGraph.RegisterDrawHook(DrawHook);
TwoDimensionalGraph.GetControl().DoubleClick += Calculus_DoubleClick;
}
void Calculus_DoubleClick(object sender, EventArgs e)
{
if (tracing != null)
{
Expressions.Add(FindTangentLine(tracing, (decimal)tracing_x));
}
}
[UserAction("Find Tangent")]
public void Tangent()
{
var dlg = new Tangent(Expressions.CurrentExpression);
dlg.Ok += Tangent_Ok;
dlg.ShowDialog();
}
string tracing = null;
float tracing_x;
[UserAction("Trace Tangent")]
public void TraceTangent()
{
if (tracing == null)
tracing = Expressions.CurrentExpression;
else
tracing = null;
(FindControlByName("tracingCheckBox")as CheckBox).Checked = tracing != null;
}
void DrawHook(Graphics g)
{
if (tracing == null)
return;
var window = TwoDimensionalGraph.Window;
foreach(var expr in (FindControlByName("tracingTextBox") as TextBox).Lines
.Where(s => s.Contains(tracing))
.Select(s => Regex.Split(s, "=>").Select(spl => spl.Trim()))
.Select(sa => new { Expression = sa.First(), Point = sa.Last() }))
{
var match = Regex.Match(expr.Point, @"([\-0-9.]+)\s*,\s*([\-0-9.]+)");
if (!match.Success)
continue;
var x = tracing_x = float.Parse(match.Groups[1].Value);
var y = float.Parse(match.Groups[2].Value);
Func<PointF,PointF> tsc = TwoDimensionalGraph.TranslateToScreenCoords;
var tang = FindTangentLine(expr.Expression, (decimal)x).Replace("y=","");
PointF topleft = new PointF(x - window.Width, (float)Expressions.Evaluate(Expressions.SubIn(tang, "x", (x - window.Width).ToString())));
PointF bottomright = new PointF(x + window.Width, (float)Expressions.Evaluate(Expressions.SubIn(tang, "x", (x + window.Width).ToString())));
g.DrawLine(Pens.Red, tsc(topleft), tsc(bottomright));
}
}
void Tangent_Ok(Tangent.TangentDialogResponse Response)
{
Expressions.Add(FindTangentLine(Response.Expression, Response.X));
}
string FindTangentLine(string Expression, decimal X)
{
var derivative = Expressions.SubIn(Derive(Expression), "x", X.ToString());
var y = Expressions.Evaluate(Expressions.SubIn(Expression, "x", X.ToString()).Replace("y=", ""));
var gradient = Expressions.Evaluate(derivative.Replace("y=", ""));
return "y=" + gradient + "x-" + (gradient * (float)X - y);
}
[UserAction]
public void Derive()
{
Expressions.Add(Derive(Expressions.CurrentExpression));
}
[UserAction("Find Stationary Points")]
public void FindStationaryPoints()
{
Expressions.Add((Derive(Expressions.CurrentExpression).Replace("y=", "0=")));
(FindControlByName("intersectionsCheckBox") as CheckBox).Checked = true;
}
[UserAction]
public void Antiderive()
{
Expressions.Add(Antiderive(Expressions.CurrentExpression));
}
[UserAction]
public void Integrate()
{
var dlg = new Integrate(Expressions.CurrentExpression);
dlg.Ok += Integrate_Ok;
dlg.ShowDialog();
}
void Integrate_Ok(Integrate.IntegrationDialogResponse Response)
{
var antiderivative = Antiderive(Response.Expression).Replace("y=", "");
// pretty highlighting
Expressions.Add(string.Format("y<({0})&y>0&x>{1}&x<{2}", Response.Expression, Response.XMin, Response.XMax));
Expressions.Add(string.Format("y>({0})&y<0&x>{1}&x<{2}", Response.Expression, Response.XMin, Response.XMax));
// calculating the signed area bound by the x axis
var min_sub_in = Expressions.SubIn(antiderivative, "x", Response.XMin.ToString());
var max_sub_in = Expressions.SubIn(antiderivative, "x", Response.XMax.ToString());
Expressions.Add(string.Format("({0})-({1})", max_sub_in, min_sub_in));
}
string Antiderive(string Expression)
{
return Regex.Replace(Expressions.MakeFirstDegreeExplicit(Expressions.MakeConstantExplicit(Expression)), @"([0-9\.]*)x\^([0-9\.]+)", m =>
{
var coefficient = decimal.Parse(string.IsNullOrEmpty(m.Groups[1].Value) ? "1" : m.Groups[1].Value);
var degree = decimal.Parse(m.Groups[2].Value);
return (coefficient / (degree + 1)) + "x^" + (degree + 1).ToString();
},
RegexOptions.Compiled);
}
string Derive(string Expression)
{
return Regex.Replace(Expressions.MakeFirstDegreeExplicit(Expressions.MakeConstantExplicit(Expression)), @"([0-9\.]*)x\^([0-9\.]+)", m =>
{
var coefficient = decimal.Parse(string.IsNullOrEmpty(m.Groups[1].Value) ? "1" : m.Groups[1].Value);
var degree = decimal.Parse(m.Groups[2].Value);
//if (degree == 0)
// return "0";
return coefficient + "(" + degree + ")x^" + (degree - 1).ToString();
},
RegexOptions.Compiled);
}
public Image GetIcon()
{
return Properties.Resources.chart_curve;
}
}
}
| 36.88835 | 157 | 0.536123 | [
"Unlicense"
] | haileys/nulloader | calculus/calculus.cs | 7,601 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UrlParser.cs" company="James Jackson-South">
// Copyright (c) James Jackson-South.
// Licensed under the Apache License, Version 2.0.
// </copyright>
// <summary>
// A helper class for decoding and parsing request urls.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System.Text;
namespace ImageProcessor.Web.Helpers
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
using ImageProcessor.Web.Extensions;
/// <summary>
/// A helper class for decoding and parsing request URLs.
/// </summary>
public static class UrlParser
{
/// <summary>
/// Parses the given URL adjusting the request path to a value that can then be interpreted by an image service.
/// </summary>
/// <param name="url">The url.</param>
/// <param name="servicePrefix">The service prefix.</param>
/// <param name="requestPath">The request path.</param>
/// <param name="queryString">The query string.</param>
public static void ParseUrl(string url, string servicePrefix, out string requestPath, out string queryString)
{
// Remove any service identifier prefixes from the url.
if (!string.IsNullOrWhiteSpace(servicePrefix))
{
// Handle when prefix is contained in filename.
string[] split = Regex.Split(url, Regex.Escape(servicePrefix), RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
if (split.Length > 1)
{
url = string.Join(servicePrefix, split.Skip(1).ToArray()).TrimStart("?");
}
else
{
url = split[0].TrimStart("?");
}
}
// Workaround for handling entirely encoded path for https://github.com/JimBobSquarePants/ImageProcessor/issues/478
// If url does not contain a query delimiter but does contain an encoded questionmark,
// treat the last encoded questionmark as the query delimiter
if (url.IndexOf('?') == -1 && url.IndexOf("%3F", StringComparison.Ordinal) > 0)
{
int idx = url.LastIndexOf("%3F", StringComparison.Ordinal);
url = url.Remove(idx, 3).Insert(idx, "?");
}
// Identify each part of the incoming request.
int queryCount = url.Count(f => f == '?');
bool hasParams = queryCount > 0;
bool hasMultiParams = queryCount > 1;
string[] splitPath = url.Split('?');
// Ensure we include any relevent querystring parameters into our request path for third party requests.
// Url decode passed request path #506
// Use Uri.UnescapeDataString instead of HttpUtility.UrlDecode to maintain plus-characters (+)
requestPath = Uri.UnescapeDataString(splitPath[0]);
queryString = hasParams ? splitPath[splitPath.Length - 1] : string.Empty;
// Certain Facebook requests require ony the first part to be decoded.
if (hasMultiParams)
{
var sb = new StringBuilder(requestPath);
for (int i = 1; i < splitPath.Length - 1; i++)
{
sb.AppendFormat("?{0}", splitPath[i]);
}
requestPath = sb.ToString();
}
}
}
} | 44.457831 | 167 | 0.544715 | [
"Apache-2.0"
] | ImranDoet/ImageProcessor | src/ImageProcessor.Web/Helpers/UrlParser.cs | 3,692 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Jekbot.Utility
{
public interface IFactory<TResource>
{
TResource Create(ResourceEnvironment environment);
}
public abstract class PreparableResource<TSelf, TFactory>
where TSelf : PreparableResource<TSelf, TFactory>
where TFactory : IFactory<TSelf>, new()
{
public static TSelf Prepare()
{
return factory.Create(environment);
}
private static readonly TFactory factory = new();
private static ResourceEnvironment environment = new();
}
}
| 24.777778 | 63 | 0.67713 | [
"MIT"
] | jacobalbano/Jekbot | Utility/PreparableResource.cs | 671 | C# |
/*
* FactSet Estimates
*
* Gain access to 20+ years of comprehensive estimates and statistics of over 250+ estimated metrics, including financial statement items, product segments, geosegments, and industry metrics. FactSet's consensus estimates are aggregated from a wide base of over 800+ contributors and cover over 19,000 active companies across 90+ countries. Data returned can be accessed on the data frequencies based on quarterly, fiscal years, and calendar years. FactSet Estimates updates on a real time basis intraday (every 5 minutes). Updating times vary based on earning season vs. non-earning season but the goal is to have the data available to the client within a few hours that FactSet receives updated information. Often times updates times can be much faster as FactSet has always been known as one of the fastest estimate providers in the market.
*
* The version of the OpenAPI document: 2.3.0
* Contact: api@factset.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Newtonsoft.Json.Converters;
namespace FactSet.SDK.FactSetEstimates.Client
{
/// <summary>
/// Formatter for 'date' openapi formats ss defined by full-date - RFC3339
/// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types
/// </summary>
public class OpenAPIDateConverter : IsoDateTimeConverter
{
/// <summary>
/// Initializes a new instance of the <see cref="OpenAPIDateConverter" /> class.
/// </summary>
public OpenAPIDateConverter()
{
// full-date = date-fullyear "-" date-month "-" date-mday
DateTimeFormat = "yyyy-MM-dd";
}
}
}
| 54.967742 | 844 | 0.724765 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/FactSetEstimates/v2/src/FactSet.SDK.FactSetEstimates/Client/OpenAPIDateConverter.cs | 1,704 | C# |
using System.IO;
namespace Praetorium
{
public interface ISerializer
{
T Clone<T>(T instance);
T Deserialize<T>(byte[] data);
T Deserialize<T>(Stream stream);
void Serialize<T>(Stream stream, T instance);
byte[] Serialize<T>(T instance);
}
}
| 16.05 | 54 | 0.554517 | [
"Apache-2.0"
] | jasonreimer/Praetorium | Source/Praetorium/ISerializer.cs | 323 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectsManage9 : MonoBehaviour {
private DisplayImage9 currentDisplay;
public GameObject[] ObjectsToMange;
public GameObject[] UIRenderObjects;
void Start()
{
currentDisplay = GameObject.Find("displayImage").GetComponent<DisplayImage9>();
RenderUI();
}
void Update()
{
MangeObjects();
}
void MangeObjects()
{
for (int i = 0; i < ObjectsToMange.Length; i++)
{
if (ObjectsToMange[i].name == currentDisplay.GetComponent<SpriteRenderer>().sprite.name)
{
ObjectsToMange[i].SetActive(true);
}
else
{
ObjectsToMange[i].SetActive(false);
}
}
}
void RenderUI()
{
for (int i = 0; i < UIRenderObjects.Length; i++)
{
UIRenderObjects[i].SetActive(false);
}
}
}
| 21.652174 | 100 | 0.557229 | [
"MIT"
] | asleshapokhrel/Escape-Lab | Assets/NewResources/Level9/ObjectsManage9.cs | 998 | C# |
using System;
namespace essentialMix.Comparers
{
[Serializable]
public class NullOrEmptyStringComparer : StringComparer, IGenericComparer<string>
{
public static NullOrEmptyStringComparer Default { get; } = new NullOrEmptyStringComparer();
/// <inheritdoc />
public NullOrEmptyStringComparer()
{
}
/// <inheritdoc />
public override int Compare(string x, string y)
{
if (!string.IsNullOrEmpty(x)) return -1;
return string.IsNullOrEmpty(y)
? 0
: 1;
}
/// <inheritdoc />
public override bool Equals(string x, string y) { return OrdinalIgnoreCase.Equals(x, y); }
/// <inheritdoc />
public override int GetHashCode(string obj) { return OrdinalIgnoreCase.GetHashCode(obj); }
}
} | 24.166667 | 93 | 0.702069 | [
"MIT"
] | asm2025/asm | Standard/essentialMix/Comparers/NullOrEmptyStringComparer.cs | 725 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, 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 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-Toolkit-Suite-NET-Core)
// Version 5.500.0.0 www.ComponentFactory.com
// *****************************************************************************
using ComponentFactory.Krypton.Navigator;
using ComponentFactory.Krypton.Workspace;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Xml;
// ReSharper disable MemberCanBeInternal
namespace ComponentFactory.Krypton.Docking
{
/// <summary>
/// Implements base docking element functionality.
/// </summary>
public abstract class DockingElement : Component,
IDockingElement
{
#region Instance Fields
private IDockingElement _parent;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the DockingElement class.
/// </summary>
/// <param name="name">Initial name of the element.</param>
public DockingElement(string name)
{
// Do not allow null, use empty string instead
Name = name ?? string.Empty;
}
#endregion
#region Public
/// <summary>
/// Gets and sets the name of the docking element.
/// </summary>
[Browsable(false)]
public string Name { get; }
/// <summary>
/// Gets a comma separated list of names leading to this element.
/// </summary>
[Browsable(false)]
public string Path
{
get
{
StringBuilder path = new StringBuilder();
IDockingElement element = this;
while (element != null)
{
// Need to comma separate element names
if (path.Length > 0)
{
path.Insert(0, ',');
}
// Prepend the elements name
path.Insert(0, element.Name);
// Walk up the chain of elements
element = element.Parent;
}
return path.ToString();
}
}
/// <summary>
/// Resolve the provided path.
/// </summary>
/// <param name="path">Comma separated list of names to resolve.</param>
/// <returns>IDockingElement reference if path was resolved with success; otherwise null.</returns>
public virtual IDockingElement ResolvePath(string path)
{
// Cannot resolve a null reference
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
// Path names cannot be zero length
if (path.Length == 0)
{
throw new ArgumentException("path");
}
// Extract the first name in the path
int comma = path.IndexOf(',');
string firstName = (comma == -1 ? path : path.Substring(0, comma));
// If the first name matches ourself...
if (firstName == Name)
{
// If there are no other names then we are the target
if (firstName.Length == path.Length)
{
return this;
}
else
{
// Extract the remainder of the path
string remainder = path.Substring(comma, path.Length - comma);
// Give each child a chance to resolve the remainder of the path
foreach (IDockingElement child in this)
{
IDockingElement ret = child.ResolvePath(remainder);
if (ret != null)
{
return ret;
}
}
}
}
return null;
}
/// <summary>
/// Gets and sets access to the parent docking element.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IDockingElement Parent
{
get => _parent;
set
{
// We do not allow the same name to occur twice in a collection (so check new parent collection)
if (value?[Name] != null)
{
throw new ArgumentNullException(@"Parent provided already has our Name in its collection.");
}
_parent = value;
}
}
/// <summary>
/// Propagates an action request down the hierarchy of docking elements.
/// </summary>
/// <param name="action">Action that is requested to be performed.</param>
/// <param name="uniqueNames">Array of unique names of the pages the action relates to.</param>
public virtual void PropogateAction(DockingPropogateAction action, string[] uniqueNames)
{
// Propagate the action request to all the child elements
// (use reverse order so if element removes itself we still have a valid loop)
for (int i = Count - 1; i >= 0; i--)
{
this[i].PropogateAction(action, uniqueNames);
}
}
/// <summary>
/// Propagates an action request down the hierarchy of docking elements.
/// </summary>
/// <param name="action">Action that is requested to be performed.</param>
/// <param name="pages">Array of pages the action relates to.</param>
public virtual void PropogateAction(DockingPropogateAction action, KryptonPage[] pages)
{
// Propagate the action request to all the child elements
// (use reverse order so if element removes itself we still have a valid loop)
for (int i = Count - 1; i >= 0; i--)
{
this[i].PropogateAction(action, pages);
}
}
/// <summary>
/// Propagates an action request down the hierarchy of docking elements.
/// </summary>
/// <param name="action">Action that is requested to be performed.</param>
/// <param name="value">Integer value associated with the request.</param>
public virtual void PropogateAction(DockingPropogateAction action, int value)
{
// Propagate the action request to all the child elements
// (use reverse order so if element removes itself we still have a valid loop)
for (int i = Count - 1; i >= 0; i--)
{
this[i].PropogateAction(action, value);
}
}
/// <summary>
/// Propagates a boolean state request down the hierarchy of docking elements.
/// </summary>
/// <param name="state">Boolean state that is requested to be recovered.</param>
/// <param name="uniqueName">Unique name of the page the request relates to.</param>
/// <returns>True/False if state is known; otherwise null indicating no information available.</returns>
public virtual bool? PropogateBoolState(DockingPropogateBoolState state, string uniqueName)
{
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
// If the child knows the exact answer then return it now
bool? ret = this[i].PropogateBoolState(state, uniqueName);
if (ret.HasValue)
{
return ret;
}
}
return null;
}
/// <summary>
/// Propagates an integer state request down the hierarchy of docking elements.
/// </summary>
/// <param name="state">Integer state that is requested to be recovered.</param>
/// <param name="value">Value discovered from matching </param>
public virtual void PropogateIntState(DockingPropogateIntState state, ref int value)
{
// Propagate the request to all the child elements
for (int i = Count - 1; i >= 0; i--)
{
this[i].PropogateIntState(state, ref value);
}
}
/// <summary>
/// Propagates a page request down the hierarchy of docking elements.
/// </summary>
/// <param name="state">Request that should result in a page reference if found.</param>
/// <param name="uniqueName">Unique name of the page the request relates to.</param>
/// <returns>Reference to page that matches the request; otherwise null.</returns>
public virtual KryptonPage PropogatePageState(DockingPropogatePageState state, string uniqueName)
{
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
// If the child knows the answer then return it now
KryptonPage page = this[i].PropogatePageState(state, uniqueName);
if (page != null)
{
return page;
}
}
return null;
}
/// <summary>
/// Propagates a page list request down the hierarchy of docking elements.
/// </summary>
/// <param name="state">Request that should result in pages collection being modified.</param>
/// <param name="pages">Pages collection for modification by the docking elements.</param>
public virtual void PropogatePageList(DockingPropogatePageList state, KryptonPageCollection pages)
{
// Propagate the action request to all the child elements
// (use reverse order so if element removes itself we still have a valid loop)
for (int i = Count - 1; i >= 0; i--)
{
this[i].PropogatePageList(state, pages);
}
}
/// <summary>
/// Propagates a workspace cell list request down the hierarchy of docking elements.
/// </summary>
/// <param name="state">Request that should result in the cells collection being modified.</param>
/// <param name="cells">Cells collection for modification by the docking elements.</param>
public virtual void PropogateCellList(DockingPropogateCellList state, KryptonWorkspaceCellList cells)
{
// Propagate the action request to all the child elements
// (use reverse order so if element removes itself we still have a valid loop)
for (int i = Count - 1; i >= 0; i--)
{
this[i].PropogateCellList(state, cells);
}
}
/// <summary>
/// Propagates a request for drag targets down the hierarchy of docking elements.
/// </summary>
/// <param name="floatingWindow">Reference to window being dragged.</param>
/// <param name="dragData">Set of pages being dragged.</param>
/// <param name="targets">Collection of drag targets.</param>
public virtual void PropogateDragTargets(KryptonFloatingWindow floatingWindow,
PageDragEndData dragData,
DragTargetList targets)
{
// Propagate the request to all child elements
foreach (IDockingElement child in this)
{
child.PropogateDragTargets(floatingWindow, dragData, targets);
}
}
/// <summary>
/// Find the docking location of the named page.
/// </summary>
/// <param name="uniqueName">Unique name of the page.</param>
/// <returns>Enumeration value indicating docking location.</returns>
public virtual DockingLocation FindPageLocation(string uniqueName)
{
// Default to not finding the page
DockingLocation location = DockingLocation.None;
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
location = this[i].FindPageLocation(uniqueName);
if (location != DockingLocation.None)
{
break;
}
}
return location;
}
/// <summary>
/// Find the docking element that contains the named page.
/// </summary>
/// <param name="uniqueName">Unique name of the page.</param>
/// <returns>IDockingElement reference if page is found; otherwise null.</returns>
public virtual IDockingElement FindPageElement(string uniqueName)
{
// Default to not finding the element
IDockingElement dockingElement = null;
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
dockingElement = this[i].FindPageElement(uniqueName);
if (dockingElement != null)
{
break;
}
}
return dockingElement;
}
/// <summary>
/// Find the docking element that contains the location specific store page for the named page.
/// </summary>
/// <param name="location">Location to be searched.</param>
/// <param name="uniqueName">Unique name of the page to be found.</param>
/// <returns>IDockingElement reference if store page is found; otherwise null.</returns>
public virtual IDockingElement FindStorePageElement(DockingLocation location, string uniqueName)
{
// Default to not finding the element
IDockingElement dockingElement = null;
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
dockingElement = this[i].FindStorePageElement(location, uniqueName);
if (dockingElement != null)
{
break;
}
}
return dockingElement;
}
/// <summary>
/// Find a floating docking element by searching the hierarchy.
/// </summary>
/// <param name="uniqueName">Named page for which a suitable floating element is required.</param>
/// <returns>KryptonDockingFloating reference if found; otherwise false.</returns>
public virtual KryptonDockingFloating FindDockingFloating(string uniqueName)
{
// Default to not finding the element
KryptonDockingFloating floatingElement = null;
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
floatingElement = this[i].FindDockingFloating(uniqueName);
if (floatingElement != null)
{
break;
}
}
return floatingElement;
}
/// <summary>
/// Find a edge docked element by searching the hierarchy.
/// </summary>
/// <param name="uniqueName">Named page for which a suitable docking edge element is required.</param>
/// <returns>KryptonDockingEdgeDocked reference if found; otherwise false.</returns>
public virtual KryptonDockingEdgeDocked FindDockingEdgeDocked(string uniqueName)
{
// Default to not finding the element
KryptonDockingEdgeDocked edgeDockedElement = null;
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
edgeDockedElement = this[i].FindDockingEdgeDocked(uniqueName);
if (edgeDockedElement != null)
{
break;
}
}
return edgeDockedElement;
}
/// <summary>
/// Find a edge auto hidden element by searching the hierarchy.
/// </summary>
/// <param name="uniqueName">Named page for which a suitable auto hidden edge element is required.</param>
/// <returns>KryptonDockingEdgeAutoHidden reference if found; otherwise false.</returns>
public virtual KryptonDockingEdgeAutoHidden FindDockingEdgeAutoHidden(string uniqueName)
{
// Default to not finding the element
KryptonDockingEdgeAutoHidden edgeAutoHiddenElement = null;
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
edgeAutoHiddenElement = this[i].FindDockingEdgeAutoHidden(uniqueName);
if (edgeAutoHiddenElement != null)
{
break;
}
}
return edgeAutoHiddenElement;
}
/// <summary>
/// Find a workspace element by searching the hierarchy.
/// </summary>
/// <param name="uniqueName">Named page for which a suitable workspace element is required.</param>
/// <returns>KryptonDockingWorkspace reference if found; otherwise false.</returns>
public virtual KryptonDockingWorkspace FindDockingWorkspace(string uniqueName)
{
// Default to not finding the element
KryptonDockingWorkspace workspaceElement = null;
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
workspaceElement = this[i].FindDockingWorkspace(uniqueName);
if (workspaceElement != null)
{
break;
}
}
return workspaceElement;
}
/// <summary>
/// Find a navigator element by searching the hierarchy.
/// </summary>
/// <param name="uniqueName">Named page for which a suitable navigator element is required.</param>
/// <returns>KryptonDockingNavigator reference if found; otherwise false.</returns>
public virtual KryptonDockingNavigator FindDockingNavigator(string uniqueName)
{
// Default to not finding the element
KryptonDockingNavigator navigatorElement = null;
// Search all child docking elements
for (int i = 0; i < Count; i++)
{
navigatorElement = this[i].FindDockingNavigator(uniqueName);
if (navigatorElement != null)
{
break;
}
}
return navigatorElement;
}
/// <summary>
/// Saves docking configuration information using a provider xml writer.
/// </summary>
/// <param name="xmlWriter">Xml writer object.</param>
public virtual void SaveElementToXml(XmlWriter xmlWriter)
{
// Output docking element
xmlWriter.WriteStartElement(XmlElementName);
xmlWriter.WriteAttributeString(@"N", Name);
xmlWriter.WriteAttributeString(@"C", Count.ToString());
// Output an element per child
foreach (IDockingElement child in this)
{
child.SaveElementToXml(xmlWriter);
}
// Terminate the workspace element
xmlWriter.WriteFullEndElement();
}
/// <summary>
/// Loads docking configuration information using a provider xml reader.
/// </summary>
/// <param name="xmlReader">Xml reader object.</param>
/// <param name="pages">Collection of available pages for adding.</param>
public virtual void LoadElementFromXml(XmlReader xmlReader, KryptonPageCollection pages)
{
// Is it the expected xml element name?
if (xmlReader.Name != XmlElementName)
{
throw new ArgumentException($@"Element name '{XmlElementName}' was expected but found '{xmlReader.Name}' instead.");
}
// Grab the element attributes
string elementName = xmlReader.GetAttribute(@"N");
string elementCount = xmlReader.GetAttribute(@"C");
// Check the name matches up
if (elementName != Name)
{
throw new ArgumentException($@"Attribute 'N' value '{Name}' was expected but found '{elementName}' instead.");
}
// Let derived class perform element specific persistence
LoadDockingElement(xmlReader, pages);
// If there are children then move over them
int count = int.Parse(elementCount);
if (count > 0)
{
for (int i = 0; i < count; i++)
{
// Read to the next element
if (!xmlReader.Read())
{
throw new ArgumentException(@"An element was expected but could not be read in.");
}
// Find a child docking element with the matching name
IDockingElement child = this[xmlReader.GetAttribute(@"N")];
// Let derived class perform child element specific processing
LoadChildDockingElement(xmlReader, pages, child);
}
}
// Read past this element to the end element
if (!xmlReader.Read())
{
throw new ArgumentException(@"An element was expected but could not be read in.");
}
}
/// <summary>
/// Checks that the provided set of pages are not already present in the docking hierarchy.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public void DemandPagesNotBePresent(KryptonPage[] pages)
{
// We need a docking manager in order to perform testing
DemandDockingManager();
// We always allow store pages but check that others are not already present in the docking hierarchy
if (pages.Any(page => !(page is KryptonStorePage) && DockingManager.ContainsPage(page)))
{
throw new ArgumentOutOfRangeException(nameof(pages), @"Cannot perform operation with a page that is already present inside docking hierarchy");
}
}
/// <summary>
/// Checks that this element has access to a docking manager, throwing exception if not.
/// </summary>
/// <exception cref="ApplicationException"></exception>
public void DemandDockingManager()
{
if (!HasDockManager)
{
throw new ApplicationException(@"Cannot perform this operation when there is no access to a KryptonDockingManager.");
}
}
/// <summary>
/// Returns a value indicating if this docking element has access to a parent docking manager.
/// </summary>
[Browsable(false)]
public bool HasDockManager => (DockingManager != null);
/// <summary>
/// Finds the KryptonDockingManager instance that owns this part of the docking hierarchy.
/// </summary>
[Browsable(false)]
public KryptonDockingManager DockingManager
{
get
{
// Searching from this element upwards
IDockingElement parent = this;
while (parent != null)
{
// If we find a match then we are done
if (parent is KryptonDockingManager manager)
{
return manager;
}
// Keep going up the parent chain
parent = parent.Parent;
}
// No match found
return null;
}
}
/// <summary>
/// Search up the parent chain looking for the specified type of object.
/// </summary>
/// <param name="findType">Type of the instance we are searching for.</param>
/// <returns>Object reference if found and it implements IDockingElement; otherwise null.</returns>
public IDockingElement GetParentType(Type findType)
{
// Searching from this element upwards
IDockingElement parent = this;
while (parent != null)
{
// If we find a match then we are done
if (parent.GetType() == findType)
{
return parent;
}
// Keep going up the parent chain
parent = parent.Parent;
}
// No match found
return null;
}
/// <summary>
/// Gets the number of child docking elements.
/// </summary>
[Browsable(false)]
public virtual int Count => 0;
/// <summary>
/// Gets the docking element at the specified index.
/// </summary>
/// <param name="index">Index.</param>
/// <returns>Docking element at specified index.</returns>
public virtual IDockingElement this[int index] => null;
/// <summary>
/// Gets the docking element with the specified name.
/// </summary>
/// <param name="name">Name of element.</param>
/// <returns>Docking element with specified name.</returns>
public virtual IDockingElement this[string name] => null;
/// <summary>
/// Shallow enumerate over child docking elements.
/// </summary>
/// <returns>Enumerator instance.</returns>
public virtual IEnumerator<IDockingElement> GetEnumerator()
{
yield break;
}
/// <summary>
/// Enumerate using non-generic interface.
/// </summary>
/// <returns>Enumerator instance.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Protected
/// <summary>
/// Gets the xml element name to use when saving.
/// </summary>
protected abstract string XmlElementName { get; }
/// <summary>
/// Perform docking element specific actions based on the loading xml.
/// </summary>
/// <param name="xmlReader">Xml reader object.</param>
/// <param name="pages">Collection of available pages.</param>
protected virtual void LoadDockingElement(XmlReader xmlReader, KryptonPageCollection pages)
{
}
/// <summary>
/// Perform docking element specific actions for loading a child xml.
/// </summary>
/// <param name="xmlReader">Xml reader object.</param>
/// <param name="pages">Collection of available pages.</param>
/// <param name="child">Optional reference to existing child docking element.</param>
protected virtual void LoadChildDockingElement(XmlReader xmlReader,
KryptonPageCollection pages,
IDockingElement child)
{
if (child != null)
{
child.LoadElementFromXml(xmlReader, pages);
}
else
{
string nodeName = xmlReader.Name;
do
{
// Read past this element
if (!xmlReader.Read())
{
throw new ArgumentException(@"An element was expected but could not be read in.");
}
// Finished when we hit the end element matching the incoming one
if ((xmlReader.NodeType == XmlNodeType.EndElement) && (xmlReader.Name == nodeName))
{
break;
}
} while (true);
}
}
#endregion
}
}
| 38.73755 | 170 | 0.544368 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-NET-Core | Source/Krypton Components/ComponentFactory.Krypton.Docking/Elements Base/DockingElement.cs | 28,785 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using POSH.sys.parse;
using POSH.sys.events;
namespace POSH.sys.strict
{
/// <summary>
/// A drive priority element, containing drive elements.
/// </summary>
public class DrivePriorityElement : ElementCollection
{
private List<DriveElement> elements;
TimerBase timer;
private Agent agent;
private List<Behaviour> behaviours;
/// <summary>
/// Initialises the drive priority element.
///
/// The log domain is set to [AgentName].DP.[drive_name]
/// </summary>
/// <param name="agent">The element's agent.</param>
/// <param name="driveName">The name of the associated drive.</param>
/// <param name="elements">The drive elements of the priority element.</param>
public DrivePriorityElement(Agent agent, string driveName, DriveElement [] elements)
: base(string.Format("DP.{0}", driveName), agent)
{
name = driveName;
this.elements = new List<DriveElement>(elements);
timer = agent.getTimer();
this.agent = agent;
log.Debug("Created");
}
/// <summary>
/// Resets all drive elements in the priority element.
/// </summary>
public override void reset()
{
log.Debug("Reset");
foreach (DriveElement elem in elements)
elem.reset();
}
/// <summary>
/// Fires the drive prority element.
///
/// This method fires the first ready drive element in its
/// list and returns FireResult(False, None). If no
/// drive element was ready, then None is returned.
/// </summary>
/// <returns>The result of firing the element.</returns>
public override FireResult fire()
{
log.Debug("Fired");
long timeStamp = timer.Time();
elements = LAPParser.ShuffleList(elements);
FireArgs args = new FireArgs();
if (elements.Contains(agent.dc.lastTriggeredElement))
if (agent.dc.lastTriggeredElement.isReady(timeStamp))
{
//if not self.agent._dc.last_triggered_element._behaviours[0].wants_to_interrupt():
// for element in new_elements:
// if element.isReady(timestamp) and element._behaviours[0].wants_to_interrupt():#and element!=self.agent._dc.last_triggered_element
// self.agent._dc.last_triggered_element=element
// element.fire()
// return FireResult(False, None)
agent.dc.lastTriggeredElement.fire();
args.FireResult = false;
args.Time = DateTime.Now;
BroadCastFireEvent(args);
return new FireResult(false, null);
}
// for element in new_elements:
foreach (DriveElement element in elements)
{
if (element.isReady(timeStamp))
{
if (element != agent.dc.lastTriggeredElement)
if (agent.dc.lastTriggeredElement == null)
{
if (element.isLatched)
agent.dc.lastTriggeredElement = element;
}
else if (!agent.dc.lastTriggeredElement.isReady(timeStamp))
// event finished natually
agent.dc.lastTriggeredElement = null;
else
{
behaviours = agent.dc.lastTriggeredElement.behaviours;
// TODO: check this latching behaviour thing
foreach (Behaviour b in behaviours)
if ( b.GetType().IsSubclassOf(typeof(LatchedBehaviour)))
((LatchedBehaviour)b).signalInterrupt();
if (element.isLatched)
agent.dc.lastTriggeredElement = element;
else
agent.dc.lastTriggeredElement = null;
}
element.fire();
args.FireResult = false;
args.Time = DateTime.Now;
BroadCastFireEvent(args);
return new FireResult(false, null);
}
}
args.FireResult = false;
args.Time = DateTime.Now;
BroadCastFireEvent(args);
return null;
}
public List<DriveElement> getSortedDrive()
{
// List<DriveElement> allElements;
// TODO: if this is really needed it must be implemented
throw new NotImplementedException();
// def get_sorted_drive(self):
// all_elements=[]
// for index,element in enumerate(self._elements):
// if element.is_latched:
// all_elements.append((element._behaviours[0].get_urgency(),index))
// else:
// all_elements.append((0,index))
// all_elements.sort()
// new_elements=[]
// for pair in all_elements:
// new_elements.append(self._elements[pair[1]])
// return new_elements
}
/// <summary>
/// Is never supposed to be called and raises an error.
/// </summary>
/// <returns>DrivePriorityElement.copy() is never supposed to be called</returns>
public override CopiableElement copy()
{
throw new NotImplementedException("DrivePriorityElement.copy() is never supposed to be called");
}
public override string ToSerialize(Dictionary<string, string> elements)
{
string plan = string.Empty;
elements = (elements is Dictionary<string, string>) ? elements : new Dictionary<string, string>();
// taking appart the senses and putting them into the right form
foreach (DriveElement elem in this.elements)
{
plan += "\t(" + elem.ToSerialize(elements) + ")";
}
return plan;
}
}
} | 39.550898 | 159 | 0.512491 | [
"MIT"
] | domhauton/CM30229-UT2004-Bot | core/sys/strict/DrivePriorityElement.cs | 6,607 | C# |
// Copyright (C) 2014 dot42
//
// Original filename: Org.W3c.Dom.Ls.cs
//
// 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 1717
namespace Org.W3c.Dom.Ls
{
/// <java-name>
/// org/w3c/dom/ls/LSSerializer
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/LSSerializer", AccessFlags = 1537)]
public partial interface ILSSerializer
/* scope: __dot42__ */
{
/// <java-name>
/// getDomConfig
/// </java-name>
[Dot42.DexImport("getDomConfig", "()Lorg/w3c/dom/DOMConfiguration;", AccessFlags = 1025)]
global::Org.W3c.Dom.IDOMConfiguration GetDomConfig() /* MethodBuilder.Create */ ;
/// <java-name>
/// getNewLine
/// </java-name>
[Dot42.DexImport("getNewLine", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetNewLine() /* MethodBuilder.Create */ ;
/// <java-name>
/// setNewLine
/// </java-name>
[Dot42.DexImport("setNewLine", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetNewLine(string @string) /* MethodBuilder.Create */ ;
/// <java-name>
/// write
/// </java-name>
[Dot42.DexImport("write", "(Lorg/w3c/dom/Node;Lorg/w3c/dom/ls/LSOutput;)Z", AccessFlags = 1025)]
bool Write(global::Org.W3c.Dom.INode node, global::Org.W3c.Dom.Ls.ILSOutput lSOutput) /* MethodBuilder.Create */ ;
/// <java-name>
/// writeToURI
/// </java-name>
[Dot42.DexImport("writeToURI", "(Lorg/w3c/dom/Node;Ljava/lang/String;)Z", AccessFlags = 1025)]
bool WriteToURI(global::Org.W3c.Dom.INode node, string @string) /* MethodBuilder.Create */ ;
/// <java-name>
/// writeToString
/// </java-name>
[Dot42.DexImport("writeToString", "(Lorg/w3c/dom/Node;)Ljava/lang/String;", AccessFlags = 1025)]
string WriteToString(global::Org.W3c.Dom.INode node) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><span><code>DOMImplementationLS</code> contains the factory methods for creating</span> Load and Save objects. </para><para>The expectation is that an instance of the <code>DOMImplementationLS</code> interface can be obtained by using binding-specific casting methods on an instance of the <code>DOMImplementation</code> interface or, if the <code>Document</code> supports the feature <code>"Core"</code> version <code>"3.0"</code> defined in [] , by using the method <code>DOMImplementation.getFeature</code> with parameter values <code>"LS"</code> (or <code>"LS-Async"</code>) and <code>"3.0"</code> (respectively). </para><para>See also the . </para>
/// </summary>
/// <java-name>
/// org/w3c/dom/ls/DOMImplementationLS
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/DOMImplementationLS", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IDOMImplementationLSConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Create a synchronous <code>LSParser</code>. </para>
/// </summary>
/// <java-name>
/// MODE_SYNCHRONOUS
/// </java-name>
[Dot42.DexImport("MODE_SYNCHRONOUS", "S", AccessFlags = 25)]
public const short MODE_SYNCHRONOUS = 1;
/// <summary>
/// <para>Create an asynchronous <code>LSParser</code>. </para>
/// </summary>
/// <java-name>
/// MODE_ASYNCHRONOUS
/// </java-name>
[Dot42.DexImport("MODE_ASYNCHRONOUS", "S", AccessFlags = 25)]
public const short MODE_ASYNCHRONOUS = 2;
}
/// <summary>
/// <para><span><code>DOMImplementationLS</code> contains the factory methods for creating</span> Load and Save objects. </para><para>The expectation is that an instance of the <code>DOMImplementationLS</code> interface can be obtained by using binding-specific casting methods on an instance of the <code>DOMImplementation</code> interface or, if the <code>Document</code> supports the feature <code>"Core"</code> version <code>"3.0"</code> defined in [] , by using the method <code>DOMImplementation.getFeature</code> with parameter values <code>"LS"</code> (or <code>"LS-Async"</code>) and <code>"3.0"</code> (respectively). </para><para>See also the . </para>
/// </summary>
/// <java-name>
/// org/w3c/dom/ls/DOMImplementationLS
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/DOMImplementationLS", AccessFlags = 1537)]
public partial interface IDOMImplementationLS
/* scope: __dot42__ */
{
/// <summary>
/// <para>Create a new <code>LSParser</code>. The newly constructed parser may then be configured by means of its <code>DOMConfiguration</code> object, and used to parse documents by means of its <code>parse</code> method. <b>Note:</b> For W3C XML Schema [] , applications must use the value <code>"http://www.w3.org/2001/XMLSchema"</code>. For XML DTD [], applications must use the value <code>"http://www.w3.org/TR/REC-xml"</code>. Other Schema languages are outside the scope of the W3C and therefore should recommend an absolute URI in order to use this method. <b>Note:</b> By default, the newly created <code>LSParser</code> does not contain a <code>DOMErrorHandler</code>, i.e. the value of the "<a href='http://www.w3.org/TR/DOM-Level-3-Core/core.html#parameter-error-handler'> error-handler</a>" configuration parameter is <code>null</code>. However, implementations may provide a default error handler at creation time. In that case, the initial value of the <code>"error-handler"</code> configuration parameter on the new <code>LSParser</code> object contains a reference to the default error handler. </para>
/// </summary>
/// <returns>
/// <para>The newly created <code>LSParser</code> object. This <code>LSParser</code> is either synchronous or asynchronous depending on the value of the <code>mode</code> argument. </para>
/// </returns>
/// <java-name>
/// createLSParser
/// </java-name>
[Dot42.DexImport("createLSParser", "(SLjava/lang/String;)Lorg/w3c/dom/ls/LSParser;", AccessFlags = 1025)]
global::Org.W3c.Dom.Ls.ILSParser CreateLSParser(short mode, string schemaType) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create a new <code>LSSerializer</code> object. <b>Note:</b> By default, the newly created <code>LSSerializer</code> has no <code>DOMErrorHandler</code>, i.e. the value of the <code>"error-handler"</code> configuration parameter is <code>null</code>. However, implementations may provide a default error handler at creation time. In that case, the initial value of the <code>"error-handler"</code> configuration parameter on the new <code>LSSerializer</code> object contains a reference to the default error handler. </para>
/// </summary>
/// <returns>
/// <para>The newly created <code>LSSerializer</code> object. </para>
/// </returns>
/// <java-name>
/// createLSSerializer
/// </java-name>
[Dot42.DexImport("createLSSerializer", "()Lorg/w3c/dom/ls/LSSerializer;", AccessFlags = 1025)]
global::Org.W3c.Dom.Ls.ILSSerializer CreateLSSerializer() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create a new empty input source object where <code>LSInput.characterStream</code>, <code>LSInput.byteStream</code> , <code>LSInput.stringData</code> <code>LSInput.systemId</code>, <code>LSInput.publicId</code>, <code>LSInput.baseURI</code>, and <code>LSInput.encoding</code> are null, and <code>LSInput.certifiedText</code> is false. </para>
/// </summary>
/// <returns>
/// <para>The newly created input object. </para>
/// </returns>
/// <java-name>
/// createLSInput
/// </java-name>
[Dot42.DexImport("createLSInput", "()Lorg/w3c/dom/ls/LSInput;", AccessFlags = 1025)]
global::Org.W3c.Dom.Ls.ILSInput CreateLSInput() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create a new empty output destination object where <code>LSOutput.characterStream</code>, <code>LSOutput.byteStream</code>, <code>LSOutput.systemId</code>, <code>LSOutput.encoding</code> are null. </para>
/// </summary>
/// <returns>
/// <para>The newly created output object. </para>
/// </returns>
/// <java-name>
/// createLSOutput
/// </java-name>
[Dot42.DexImport("createLSOutput", "()Lorg/w3c/dom/ls/LSOutput;", AccessFlags = 1025)]
global::Org.W3c.Dom.Ls.ILSOutput CreateLSOutput() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><span>Parser or write operations may throw an <code>LSException</code> if the</span> processing is stopped. The processing can be stopped due to a <code>DOMError</code> with a severity of <code>DOMError.SEVERITY_FATAL_ERROR</code> or a non recovered <code>DOMError.SEVERITY_ERROR</code>, or if <code>DOMErrorHandler.handleError()</code> returned <code>false</code>. </para><para><b>Note:</b> As suggested in the definition of the constants in the <code>DOMError</code> interface, a DOM implementation may choose to continue after a fatal error, but the resulting DOM tree is then implementation dependent. </para><para>See also the . </para>
/// </summary>
/// <java-name>
/// org/w3c/dom/ls/LSException
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/LSException", AccessFlags = 33)]
public partial class LSException : global::System.SystemException
/* scope: __dot42__ */
{
/// <java-name>
/// code
/// </java-name>
[Dot42.DexImport("code", "S", AccessFlags = 1)]
public short Code;
/// <summary>
/// <para>If an attempt was made to load a document, or an XML Fragment, using <code>LSParser</code> and the processing has been stopped. </para>
/// </summary>
/// <java-name>
/// PARSE_ERR
/// </java-name>
[Dot42.DexImport("PARSE_ERR", "S", AccessFlags = 25)]
public const short PARSE_ERR = 81;
/// <summary>
/// <para>If an attempt was made to serialize a <code>Node</code> using <code>LSSerializer</code> and the processing has been stopped. </para>
/// </summary>
/// <java-name>
/// SERIALIZE_ERR
/// </java-name>
[Dot42.DexImport("SERIALIZE_ERR", "S", AccessFlags = 25)]
public const short SERIALIZE_ERR = 82;
[Dot42.DexImport("<init>", "(SLjava/lang/String;)V", AccessFlags = 1)]
public LSException(short code, string message) /* MethodBuilder.Create */
{
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal LSException() /* TypeBuilder.AddDefaultConstructor */
{
}
}
/// <summary>
/// <para><span><code>LSParserFilter</code>s provide applications the ability to examine</span> nodes as they are being constructed while parsing. As each node is examined, it may be modified or removed, or the entire parse may be terminated early. </para><para>At the time any of the filter methods are called by the parser, the owner Document and DOMImplementation objects exist and are accessible. The document element is never passed to the <code>LSParserFilter</code> methods, i.e. it is not possible to filter out the document element. <code>Document</code>, <code>DocumentType</code>, <code>Notation</code>, <code>Entity</code>, and <code>Attr</code> nodes are never passed to the <code>acceptNode</code> method on the filter. The child nodes of an <code>EntityReference</code> node are passed to the filter if the parameter "<a href='http://www.w3.org/TR/DOM-Level-3-Core/core.html#parameter-entities'> entities</a>" is set to <code>false</code>. Note that, as described by the parameter "<a href='http://www.w3.org/TR/DOM-Level-3-Core/core.html#parameter-entities'> entities</a>", unexpanded entity reference nodes are never discarded and are always passed to the filter. </para><para>All validity checking while parsing a document occurs on the source document as it appears on the input stream, not on the DOM document as it is built in memory. With filters, the document in memory may be a subset of the document on the stream, and its validity may have been affected by the filtering. </para><para>All default attributes must be present on elements when the elements are passed to the filter methods. All other default content must be passed to the filter methods. </para><para>DOM applications must not raise exceptions in a filter. The effect of throwing exceptions from a filter is DOM implementation dependent. </para><para>See also the . </para>
/// </summary>
/// <java-name>
/// org/w3c/dom/ls/LSParserFilter
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/LSParserFilter", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ILSParserFilterConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>Accept the node. </para>
/// </summary>
/// <java-name>
/// FILTER_ACCEPT
/// </java-name>
[Dot42.DexImport("FILTER_ACCEPT", "S", AccessFlags = 25)]
public const short FILTER_ACCEPT = 1;
/// <summary>
/// <para>Reject the node and its children. </para>
/// </summary>
/// <java-name>
/// FILTER_REJECT
/// </java-name>
[Dot42.DexImport("FILTER_REJECT", "S", AccessFlags = 25)]
public const short FILTER_REJECT = 2;
/// <summary>
/// <para>Skip this single node. The children of this node will still be considered. </para>
/// </summary>
/// <java-name>
/// FILTER_SKIP
/// </java-name>
[Dot42.DexImport("FILTER_SKIP", "S", AccessFlags = 25)]
public const short FILTER_SKIP = 3;
/// <summary>
/// <para>Interrupt the normal processing of the document. </para>
/// </summary>
/// <java-name>
/// FILTER_INTERRUPT
/// </java-name>
[Dot42.DexImport("FILTER_INTERRUPT", "S", AccessFlags = 25)]
public const short FILTER_INTERRUPT = 4;
}
/// <summary>
/// <para><span><code>LSParserFilter</code>s provide applications the ability to examine</span> nodes as they are being constructed while parsing. As each node is examined, it may be modified or removed, or the entire parse may be terminated early. </para><para>At the time any of the filter methods are called by the parser, the owner Document and DOMImplementation objects exist and are accessible. The document element is never passed to the <code>LSParserFilter</code> methods, i.e. it is not possible to filter out the document element. <code>Document</code>, <code>DocumentType</code>, <code>Notation</code>, <code>Entity</code>, and <code>Attr</code> nodes are never passed to the <code>acceptNode</code> method on the filter. The child nodes of an <code>EntityReference</code> node are passed to the filter if the parameter "<a href='http://www.w3.org/TR/DOM-Level-3-Core/core.html#parameter-entities'> entities</a>" is set to <code>false</code>. Note that, as described by the parameter "<a href='http://www.w3.org/TR/DOM-Level-3-Core/core.html#parameter-entities'> entities</a>", unexpanded entity reference nodes are never discarded and are always passed to the filter. </para><para>All validity checking while parsing a document occurs on the source document as it appears on the input stream, not on the DOM document as it is built in memory. With filters, the document in memory may be a subset of the document on the stream, and its validity may have been affected by the filtering. </para><para>All default attributes must be present on elements when the elements are passed to the filter methods. All other default content must be passed to the filter methods. </para><para>DOM applications must not raise exceptions in a filter. The effect of throwing exceptions from a filter is DOM implementation dependent. </para><para>See also the . </para>
/// </summary>
/// <java-name>
/// org/w3c/dom/ls/LSParserFilter
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/LSParserFilter", AccessFlags = 1537)]
public partial interface ILSParserFilter
/* scope: __dot42__ */
{
/// <summary>
/// <para>The parser will call this method after each <code>Element</code> start tag has been scanned, but before the remainder of the <code>Element</code> is processed. The intent is to allow the element, including any children, to be efficiently skipped. Note that only element nodes are passed to the <code>startElement</code> function. <br></br>The element node passed to <code>startElement</code> for filtering will include all of the Element's attributes, but none of the children nodes. The Element may not yet be in place in the document being constructed (it may not have a parent node.) <br></br>A <code>startElement</code> filter function may access or change the attributes for the Element. Changing Namespace declarations will have no effect on namespace resolution by the parser. <br></br>For efficiency, the Element node passed to the filter may not be the same one as is actually placed in the tree if the node is accepted. And the actual node (node object identity) may be reused during the process of reading in and filtering a document. </para>
/// </summary>
/// <returns>
/// <para><ul><li><para><code>FILTER_ACCEPT</code> if the <code>Element</code> should be included in the DOM document being built. </para></li><li><para><code>FILTER_REJECT</code> if the <code>Element</code> and all of its children should be rejected. </para></li><li><para><code>FILTER_SKIP</code> if the <code>Element</code> should be skipped. All of its children are inserted in place of the skipped <code>Element</code> node. </para></li><li><para><code>FILTER_INTERRUPT</code> if the filter wants to stop the processing of the document. Interrupting the processing of the document does no longer guarantee that the resulting DOM tree is XML well-formed. The <code>Element</code> is rejected. </para></li></ul>Returning any other values will result in unspecified behavior. </para>
/// </returns>
/// <java-name>
/// startElement
/// </java-name>
[Dot42.DexImport("startElement", "(Lorg/w3c/dom/Element;)S", AccessFlags = 1025)]
short StartElement(global::Org.W3c.Dom.IElement elementArg) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>This method will be called by the parser at the completion of the parsing of each node. The node and all of its descendants will exist and be complete. The parent node will also exist, although it may be incomplete, i.e. it may have additional children that have not yet been parsed. Attribute nodes are never passed to this function. <br></br>From within this method, the new node may be freely modified - children may be added or removed, text nodes modified, etc. The state of the rest of the document outside this node is not defined, and the affect of any attempt to navigate to, or to modify any other part of the document is undefined. <br></br>For validating parsers, the checks are made on the original document, before any modification by the filter. No validity checks are made on any document modifications made by the filter. <br></br>If this new node is rejected, the parser might reuse the new node and any of its descendants. </para>
/// </summary>
/// <returns>
/// <para><ul><li><para><code>FILTER_ACCEPT</code> if this <code>Node</code> should be included in the DOM document being built. </para></li><li><para><code>FILTER_REJECT</code> if the <code>Node</code> and all of its children should be rejected. </para></li><li><para><code>FILTER_SKIP</code> if the <code>Node</code> should be skipped and the <code>Node</code> should be replaced by all the children of the <code>Node</code>. </para></li><li><para><code>FILTER_INTERRUPT</code> if the filter wants to stop the processing of the document. Interrupting the processing of the document does no longer guarantee that the resulting DOM tree is XML well-formed. The <code>Node</code> is accepted and will be the last completely parsed node. </para></li></ul></para>
/// </returns>
/// <java-name>
/// acceptNode
/// </java-name>
[Dot42.DexImport("acceptNode", "(Lorg/w3c/dom/Node;)S", AccessFlags = 1025)]
short AcceptNode(global::Org.W3c.Dom.INode nodeArg) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Tells the <code>LSParser</code> what types of nodes to show to the method <code>LSParserFilter.acceptNode</code>. If a node is not shown to the filter using this attribute, it is automatically included in the DOM document being built. See <code>NodeFilter</code> for definition of the constants. The constants <code>SHOW_ATTRIBUTE</code> , <code>SHOW_DOCUMENT</code>, <code>SHOW_DOCUMENT_TYPE</code>, <code>SHOW_NOTATION</code>, <code>SHOW_ENTITY</code>, and <code>SHOW_DOCUMENT_FRAGMENT</code> are meaningless here. Those nodes will never be passed to <code>LSParserFilter.acceptNode</code>. <br></br> The constants used here are defined in []</para>
/// </summary>
/// <java-name>
/// getWhatToShow
/// </java-name>
[Dot42.DexImport("getWhatToShow", "()I", AccessFlags = 1025)]
int GetWhatToShow() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><span><code>LSResourceResolver</code> provides a way for applications to</span> redirect references to external resources. </para><para>Applications needing to implement custom handling for external resources can implement this interface and register their implementation by setting the "resource-resolver" parameter of <code>DOMConfiguration</code> objects attached to <code>LSParser</code> and <code>LSSerializer</code>. It can also be register on <code>DOMConfiguration</code> objects attached to <code>Document</code> if the "LS" feature is supported. </para><para>The <code>LSParser</code> will then allow the application to intercept any external entities, including the external DTD subset and external parameter entities, before including them. The top-level document entity is never passed to the <code>resolveResource</code> method. </para><para>Many DOM applications will not need to implement this interface, but it will be especially useful for applications that build XML documents from databases or other specialized input sources, or for applications that use URNs. </para><para><b>Note:</b> <code>LSResourceResolver</code> is based on the SAX2 [] <code>EntityResolver</code> interface. </para><para>See also the . </para>
/// </summary>
/// <java-name>
/// org/w3c/dom/ls/LSResourceResolver
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/LSResourceResolver", AccessFlags = 1537)]
public partial interface ILSResourceResolver
/* scope: __dot42__ */
{
/// <summary>
/// <para>Allow the application to resolve external resources. <br></br> The <code>LSParser</code> will call this method before opening any external resource, including the external DTD subset, external entities referenced within the DTD, and external entities referenced within the document element (however, the top-level document entity is not passed to this method). The application may then request that the <code>LSParser</code> resolve the external resource itself, that it use an alternative URI, or that it use an entirely different input source. <br></br> Application writers can use this method to redirect external system identifiers to secure and/or local URI, to look up public identifiers in a catalogue, or to read an entity from a database or other input source (including, for example, a dialog box). </para>
/// </summary>
/// <returns>
/// <para>A <code>LSInput</code> object describing the new input source, or <code>null</code> to request that the parser open a regular URI connection to the resource. </para>
/// </returns>
/// <java-name>
/// resolveResource
/// </java-name>
[Dot42.DexImport("resolveResource", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/la" +
"ng/String;)Lorg/w3c/dom/ls/LSInput;", AccessFlags = 1025)]
global::Org.W3c.Dom.Ls.ILSInput ResolveResource(string type, string namespaceURI, string publicId, string systemId, string baseURI) /* MethodBuilder.Create */ ;
}
/// <java-name>
/// org/w3c/dom/ls/LSParser
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/LSParser", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ILSParserConstants
/* scope: __dot42__ */
{
/// <java-name>
/// ACTION_APPEND_AS_CHILDREN
/// </java-name>
[Dot42.DexImport("ACTION_APPEND_AS_CHILDREN", "S", AccessFlags = 25)]
public const short ACTION_APPEND_AS_CHILDREN = 1;
/// <java-name>
/// ACTION_REPLACE_CHILDREN
/// </java-name>
[Dot42.DexImport("ACTION_REPLACE_CHILDREN", "S", AccessFlags = 25)]
public const short ACTION_REPLACE_CHILDREN = 2;
/// <java-name>
/// ACTION_INSERT_BEFORE
/// </java-name>
[Dot42.DexImport("ACTION_INSERT_BEFORE", "S", AccessFlags = 25)]
public const short ACTION_INSERT_BEFORE = 3;
/// <java-name>
/// ACTION_INSERT_AFTER
/// </java-name>
[Dot42.DexImport("ACTION_INSERT_AFTER", "S", AccessFlags = 25)]
public const short ACTION_INSERT_AFTER = 4;
/// <java-name>
/// ACTION_REPLACE
/// </java-name>
[Dot42.DexImport("ACTION_REPLACE", "S", AccessFlags = 25)]
public const short ACTION_REPLACE = 5;
}
/// <java-name>
/// org/w3c/dom/ls/LSParser
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/LSParser", AccessFlags = 1537)]
public partial interface ILSParser
/* scope: __dot42__ */
{
/// <java-name>
/// getDomConfig
/// </java-name>
[Dot42.DexImport("getDomConfig", "()Lorg/w3c/dom/DOMConfiguration;", AccessFlags = 1025)]
global::Org.W3c.Dom.IDOMConfiguration GetDomConfig() /* MethodBuilder.Create */ ;
/// <java-name>
/// getFilter
/// </java-name>
[Dot42.DexImport("getFilter", "()Lorg/w3c/dom/ls/LSParserFilter;", AccessFlags = 1025)]
global::Org.W3c.Dom.Ls.ILSParserFilter GetFilter() /* MethodBuilder.Create */ ;
/// <java-name>
/// setFilter
/// </java-name>
[Dot42.DexImport("setFilter", "(Lorg/w3c/dom/ls/LSParserFilter;)V", AccessFlags = 1025)]
void SetFilter(global::Org.W3c.Dom.Ls.ILSParserFilter lSParserFilter) /* MethodBuilder.Create */ ;
/// <java-name>
/// getAsync
/// </java-name>
[Dot42.DexImport("getAsync", "()Z", AccessFlags = 1025)]
bool GetAsync() /* MethodBuilder.Create */ ;
/// <java-name>
/// getBusy
/// </java-name>
[Dot42.DexImport("getBusy", "()Z", AccessFlags = 1025)]
bool GetBusy() /* MethodBuilder.Create */ ;
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/w3c/dom/ls/LSInput;)Lorg/w3c/dom/Document;", AccessFlags = 1025)]
global::Org.W3c.Dom.IDocument Parse(global::Org.W3c.Dom.Ls.ILSInput lSInput) /* MethodBuilder.Create */ ;
/// <java-name>
/// parseURI
/// </java-name>
[Dot42.DexImport("parseURI", "(Ljava/lang/String;)Lorg/w3c/dom/Document;", AccessFlags = 1025)]
global::Org.W3c.Dom.IDocument ParseURI(string @string) /* MethodBuilder.Create */ ;
/// <java-name>
/// parseWithContext
/// </java-name>
[Dot42.DexImport("parseWithContext", "(Lorg/w3c/dom/ls/LSInput;Lorg/w3c/dom/Node;S)Lorg/w3c/dom/Node;", AccessFlags = 1025)]
global::Org.W3c.Dom.INode ParseWithContext(global::Org.W3c.Dom.Ls.ILSInput lSInput, global::Org.W3c.Dom.INode node, short int16) /* MethodBuilder.Create */ ;
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1025)]
void Abort() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><span>This interface represents an input source for data.</span> </para><para>This interface allows an application to encapsulate information about an input source in a single object, which may include a public identifier, a system identifier, a byte stream (possibly with a specified encoding), a base URI, and/or a character stream. </para><para>The exact definitions of a byte stream and a character stream are binding dependent. </para><para>The application is expected to provide objects that implement this interface whenever such objects are needed. The application can either provide its own objects that implement this interface, or it can use the generic factory method <code>DOMImplementationLS.createLSInput()</code> to create objects that implement this interface. </para><para>The <code>LSParser</code> will use the <code>LSInput</code> object to determine how to read data. The <code>LSParser</code> will look at the different inputs specified in the <code>LSInput</code> in the following order to know which one to read from, the first one that is not null and not an empty string will be used: <ol><li><para><code>LSInput.characterStream</code> </para></li><li><para><code>LSInput.byteStream</code> </para></li><li><para><code>LSInput.stringData</code> </para></li><li><para><code>LSInput.systemId</code> </para></li><li><para><code>LSInput.publicId</code> </para></li></ol></para><para>If all inputs are null, the <code>LSParser</code> will report a <code>DOMError</code> with its <code>DOMError.type</code> set to <code>"no-input-specified"</code> and its <code>DOMError.severity</code> set to <code>DOMError.SEVERITY_FATAL_ERROR</code>. </para><para><code>LSInput</code> objects belong to the application. The DOM implementation will never modify them (though it may make copies and modify the copies, if necessary). </para><para>See also the . </para>
/// </summary>
/// <java-name>
/// org/w3c/dom/ls/LSInput
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/LSInput", AccessFlags = 1537)]
public partial interface ILSInput
/* scope: __dot42__ */
{
/// <summary>
/// <para>An attribute of a language and binding dependent type that represents a stream of 16-bit units. The application must encode the stream using UTF-16 (defined in [Unicode] and in [ISO/IEC 10646]). It is not a requirement to have an XML declaration when using character streams. If an XML declaration is present, the value of the encoding attribute will be ignored. </para>
/// </summary>
/// <java-name>
/// getCharacterStream
/// </java-name>
[Dot42.DexImport("getCharacterStream", "()Ljava/io/Reader;", AccessFlags = 1025)]
global::Java.Io.Reader GetCharacterStream() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>An attribute of a language and binding dependent type that represents a stream of 16-bit units. The application must encode the stream using UTF-16 (defined in [Unicode] and in [ISO/IEC 10646]). It is not a requirement to have an XML declaration when using character streams. If an XML declaration is present, the value of the encoding attribute will be ignored. </para>
/// </summary>
/// <java-name>
/// setCharacterStream
/// </java-name>
[Dot42.DexImport("setCharacterStream", "(Ljava/io/Reader;)V", AccessFlags = 1025)]
void SetCharacterStream(global::Java.Io.Reader characterStream) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>An attribute of a language and binding dependent type that represents a stream of bytes. <br></br> If the application knows the character encoding of the byte stream, it should set the encoding attribute. Setting the encoding in this way will override any encoding specified in an XML declaration in the data. </para>
/// </summary>
/// <java-name>
/// getByteStream
/// </java-name>
[Dot42.DexImport("getByteStream", "()Ljava/io/InputStream;", AccessFlags = 1025)]
global::Java.Io.InputStream GetByteStream() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>An attribute of a language and binding dependent type that represents a stream of bytes. <br></br> If the application knows the character encoding of the byte stream, it should set the encoding attribute. Setting the encoding in this way will override any encoding specified in an XML declaration in the data. </para>
/// </summary>
/// <java-name>
/// setByteStream
/// </java-name>
[Dot42.DexImport("setByteStream", "(Ljava/io/InputStream;)V", AccessFlags = 1025)]
void SetByteStream(global::Java.Io.InputStream byteStream) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>String data to parse. If provided, this will always be treated as a sequence of 16-bit units (UTF-16 encoded characters). It is not a requirement to have an XML declaration when using <code>stringData</code>. If an XML declaration is present, the value of the encoding attribute will be ignored. </para>
/// </summary>
/// <java-name>
/// getStringData
/// </java-name>
[Dot42.DexImport("getStringData", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetStringData() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>String data to parse. If provided, this will always be treated as a sequence of 16-bit units (UTF-16 encoded characters). It is not a requirement to have an XML declaration when using <code>stringData</code>. If an XML declaration is present, the value of the encoding attribute will be ignored. </para>
/// </summary>
/// <java-name>
/// setStringData
/// </java-name>
[Dot42.DexImport("setStringData", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetStringData(string stringData) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The system identifier, a URI reference [], for this input source. The system identifier is optional if there is a byte stream, a character stream, or string data. It is still useful to provide one, since the application will use it to resolve any relative URIs and can include it in error messages and warnings. (The LSParser will only attempt to fetch the resource identified by the URI reference if there is no other input available in the input source.) <br></br> If the application knows the character encoding of the object pointed to by the system identifier, it can set the encoding using the <code>encoding</code> attribute. <br></br> If the specified system ID is a relative URI reference (see section 5 in []), the DOM implementation will attempt to resolve the relative URI with the <code>baseURI</code> as the base, if that fails, the behavior is implementation dependent. </para>
/// </summary>
/// <java-name>
/// getSystemId
/// </java-name>
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetSystemId() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The system identifier, a URI reference [], for this input source. The system identifier is optional if there is a byte stream, a character stream, or string data. It is still useful to provide one, since the application will use it to resolve any relative URIs and can include it in error messages and warnings. (The LSParser will only attempt to fetch the resource identified by the URI reference if there is no other input available in the input source.) <br></br> If the application knows the character encoding of the object pointed to by the system identifier, it can set the encoding using the <code>encoding</code> attribute. <br></br> If the specified system ID is a relative URI reference (see section 5 in []), the DOM implementation will attempt to resolve the relative URI with the <code>baseURI</code> as the base, if that fails, the behavior is implementation dependent. </para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetSystemId(string systemId) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The public identifier for this input source. This may be mapped to an input source using an implementation dependent mechanism (such as catalogues or other mappings). The public identifier, if specified, may also be reported as part of the location information when errors are reported. </para>
/// </summary>
/// <java-name>
/// getPublicId
/// </java-name>
[Dot42.DexImport("getPublicId", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetPublicId() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The public identifier for this input source. This may be mapped to an input source using an implementation dependent mechanism (such as catalogues or other mappings). The public identifier, if specified, may also be reported as part of the location information when errors are reported. </para>
/// </summary>
/// <java-name>
/// setPublicId
/// </java-name>
[Dot42.DexImport("setPublicId", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetPublicId(string publicId) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The base URI to be used (see section 5.1.4 in []) for resolving a relative <code>systemId</code> to an absolute URI. <br></br> If, when used, the base URI is itself a relative URI, an empty string, or null, the behavior is implementation dependent. </para>
/// </summary>
/// <java-name>
/// getBaseURI
/// </java-name>
[Dot42.DexImport("getBaseURI", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetBaseURI() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The base URI to be used (see section 5.1.4 in []) for resolving a relative <code>systemId</code> to an absolute URI. <br></br> If, when used, the base URI is itself a relative URI, an empty string, or null, the behavior is implementation dependent. </para>
/// </summary>
/// <java-name>
/// setBaseURI
/// </java-name>
[Dot42.DexImport("setBaseURI", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetBaseURI(string baseURI) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The character encoding, if known. The encoding must be a string acceptable for an XML encoding declaration ([] section 4.3.3 "Character Encoding in Entities"). <br></br> This attribute has no effect when the application provides a character stream or string data. For other sources of input, an encoding specified by means of this attribute will override any encoding specified in the XML declaration or the Text declaration, or an encoding obtained from a higher level protocol, such as HTTP []. </para>
/// </summary>
/// <java-name>
/// getEncoding
/// </java-name>
[Dot42.DexImport("getEncoding", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetEncoding() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The character encoding, if known. The encoding must be a string acceptable for an XML encoding declaration ([] section 4.3.3 "Character Encoding in Entities"). <br></br> This attribute has no effect when the application provides a character stream or string data. For other sources of input, an encoding specified by means of this attribute will override any encoding specified in the XML declaration or the Text declaration, or an encoding obtained from a higher level protocol, such as HTTP []. </para>
/// </summary>
/// <java-name>
/// setEncoding
/// </java-name>
[Dot42.DexImport("setEncoding", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetEncoding(string encoding) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If set to true, assume that the input is certified (see section 2.13 in []) when parsing []. </para>
/// </summary>
/// <java-name>
/// getCertifiedText
/// </java-name>
[Dot42.DexImport("getCertifiedText", "()Z", AccessFlags = 1025)]
bool GetCertifiedText() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If set to true, assume that the input is certified (see section 2.13 in []) when parsing []. </para>
/// </summary>
/// <java-name>
/// setCertifiedText
/// </java-name>
[Dot42.DexImport("setCertifiedText", "(Z)V", AccessFlags = 1025)]
void SetCertifiedText(bool certifiedText) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><span>This interface represents an output destination for data.</span> </para><para>This interface allows an application to encapsulate information about an output destination in a single object, which may include a URI, a byte stream (possibly with a specified encoding), a base URI, and/or a character stream. </para><para>The exact definitions of a byte stream and a character stream are binding dependent. </para><para>The application is expected to provide objects that implement this interface whenever such objects are needed. The application can either provide its own objects that implement this interface, or it can use the generic factory method <code>DOMImplementationLS.createLSOutput()</code> to create objects that implement this interface. </para><para>The <code>LSSerializer</code> will use the <code>LSOutput</code> object to determine where to serialize the output to. The <code>LSSerializer</code> will look at the different outputs specified in the <code>LSOutput</code> in the following order to know which one to output to, the first one that is not null and not an empty string will be used: <ol><li><para><code>LSOutput.characterStream</code> </para></li><li><para><code>LSOutput.byteStream</code> </para></li><li><para><code>LSOutput.systemId</code> </para></li></ol></para><para><code>LSOutput</code> objects belong to the application. The DOM implementation will never modify them (though it may make copies and modify the copies, if necessary). </para><para>See also the . </para>
/// </summary>
/// <java-name>
/// org/w3c/dom/ls/LSOutput
/// </java-name>
[Dot42.DexImport("org/w3c/dom/ls/LSOutput", AccessFlags = 1537)]
public partial interface ILSOutput
/* scope: __dot42__ */
{
/// <summary>
/// <para>An attribute of a language and binding dependent type that represents a writable stream to which 16-bit units can be output. </para>
/// </summary>
/// <java-name>
/// getCharacterStream
/// </java-name>
[Dot42.DexImport("getCharacterStream", "()Ljava/io/Writer;", AccessFlags = 1025)]
global::Java.Io.Writer GetCharacterStream() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>An attribute of a language and binding dependent type that represents a writable stream to which 16-bit units can be output. </para>
/// </summary>
/// <java-name>
/// setCharacterStream
/// </java-name>
[Dot42.DexImport("setCharacterStream", "(Ljava/io/Writer;)V", AccessFlags = 1025)]
void SetCharacterStream(global::Java.Io.Writer characterStream) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>An attribute of a language and binding dependent type that represents a writable stream of bytes. </para>
/// </summary>
/// <java-name>
/// getByteStream
/// </java-name>
[Dot42.DexImport("getByteStream", "()Ljava/io/OutputStream;", AccessFlags = 1025)]
global::Java.Io.OutputStream GetByteStream() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>An attribute of a language and binding dependent type that represents a writable stream of bytes. </para>
/// </summary>
/// <java-name>
/// setByteStream
/// </java-name>
[Dot42.DexImport("setByteStream", "(Ljava/io/OutputStream;)V", AccessFlags = 1025)]
void SetByteStream(global::Java.Io.OutputStream byteStream) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The system identifier, a URI reference [], for this output destination. <br></br> If the system ID is a relative URI reference (see section 5 in []), the behavior is implementation dependent. </para>
/// </summary>
/// <java-name>
/// getSystemId
/// </java-name>
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetSystemId() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The system identifier, a URI reference [], for this output destination. <br></br> If the system ID is a relative URI reference (see section 5 in []), the behavior is implementation dependent. </para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetSystemId(string systemId) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The character encoding to use for the output. The encoding must be a string acceptable for an XML encoding declaration ([] section 4.3.3 "Character Encoding in Entities"), it is recommended that character encodings registered (as charsets) with the Internet Assigned Numbers Authority [] should be referred to using their registered names. </para>
/// </summary>
/// <java-name>
/// getEncoding
/// </java-name>
[Dot42.DexImport("getEncoding", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetEncoding() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>The character encoding to use for the output. The encoding must be a string acceptable for an XML encoding declaration ([] section 4.3.3 "Character Encoding in Entities"), it is recommended that character encodings registered (as charsets) with the Internet Assigned Numbers Authority [] should be referred to using their registered names. </para>
/// </summary>
/// <java-name>
/// setEncoding
/// </java-name>
[Dot42.DexImport("setEncoding", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetEncoding(string encoding) /* MethodBuilder.Create */ ;
}
}
| 71.371341 | 1,909 | 0.694193 | [
"Apache-2.0"
] | Dot42Xna/master | Generated/v4.1/Org.W3c.Dom.Ls.cs | 46,320 | C# |
namespace _03._NullConditionalOperators
{
public class Customer
{
public Customer()
{
this.Orders = new List<string>();
}
public IEnumerable<string> Orders { get; set; }
}
}
| 17.846154 | 55 | 0.551724 | [
"MIT"
] | BorisLechev/CSharp-New-Features | CSharp-6.0-New-Features/03. NullConditionalOperators/Customer.cs | 234 | C# |
using System;
using System.Windows.Forms;
namespace HorsePoints
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 21.4 | 65 | 0.567757 | [
"MIT"
] | OxygeneIV/Vaulting | HorsePoints/Program.cs | 430 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Zetris.PPT.Memory;
using MisaMinoNET;
using PerfectClearNET;
using ScpDriverInterface;
namespace Zetris.PPT {
class PPTBot: Bot<UI, PPTBot> {
const int rngsearch_max = 1000;
Thread BotThread = null;
#region InputHelper
static int FindInputGoalX(int[,] board, int piece, int x, int y, int r, int d) {
fixInput(piece, ref x, ref y, r);
while (FitPiece(board, piece, x, y, r))
x += d;
x -= d;
fixOutput(piece, ref x, ref y, r);
return x;
}
static int FindInputGoalY(int[,] board, int piece, int x, int y, int r) {
fixInput(piece, ref x, ref y, r);
while (FitPiece(board, piece, x, y, r))
y--;
y++;
fixOutput(piece, ref x, ref y, r);
return y;
}
static int FixWall(int[,] board, int piece, int x, int y, int r) {
fixInput(piece, ref x, ref y, r);
int d = (x > 4) ? -1 : 1;
while (!FitPiece(board, piece, x, y, r)) {
x += d;
if (x > 11) {
d = -1;
}
if (x < -2) {
return -1;
}
}
fixOutput(piece, ref x, ref y, r);
return x;
}
static int BoardHeight(int[,] board, int height) {
int ret = 0;
for (int i = 0; i < 10; i++) {
for (int j = height - 1; j >= 0; j--) {
if (board[i, j] != 255) {
ret = Math.Max(ret, j + 1);
break;
}
}
}
return ret;
}
static bool FixTspinMini(int[,] board, int x, int y, int r) {
fixInput(4, ref x, ref y, r);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (piecedefs[4][r][i, j] != -1) {
int col = x + j;
for (int row = y - i; row < 22; row++) { // row < baseBoardHeight
if (board[col, row] != 255) {
return false;
}
}
}
}
}
return true;
}
static void AddGarbage(int[,] board, uint rng, int lines) {
if (lines == 0) return;
int col = GameHelper.Instance.RandomInt(ref rng, 10);
for (int i = 0; i < lines; i++) {
if (70 < GameHelper.Instance.RandomInt(ref rng, 99)) {
int newCol = GameHelper.Instance.RandomInt(ref rng, 9);
col = newCol + Convert.ToInt32(newCol >= col);
}
AddGarbageLine(board, col);
}
}
#endregion
protected override int getPreviews() => (Preferences.Previews > 18) ? int.MaxValue : Preferences.Previews;
protected override bool getPerfectClear() => Preferences.PerfectClear;
protected override bool getEnhancePerfect() => Preferences.EnhancePerfect;
protected override bool HoldAllowed() => Preferences.HoldAllowed;
protected override bool AllSpins() => Preferences.AllSpins;
protected override MisaMinoParameters CurrentStyle() => Preferences.CurrentStyle.Clone().Parameters;
protected override bool C4W() => Preferences.C4W;
protected override bool TSDOnly() => Preferences.TSDOnly;
protected override int Intelligence() => Preferences.Intelligence;
protected override bool Allow180() => false;
protected override bool SRSPlus() => false;
protected override uint PCThreads() => Preferences.PCThreads;
protected override bool GarbageBlocking() => GameHelper.Instance.InSwap.Call();
protected override int RushTime() => 12;
protected override bool Danger() =>
#if PUBLIC
GameHelper.Instance.Online.Call() || (GameHelper.Instance.LobbyPtr.Call() != 0);
#else
false;
#endif
static void ResetGame() {
#if !PUBLIC
if (!(GameHelper.Instance is Memory.PPT) || GameHelper.Instance.InSwap.Call() || !Preferences.PuzzleLeague) return;
GameHelper.Instance.ResetGame();
Stopwatch resetting = new Stopwatch();
resetting.Start();
while (resetting.ElapsedMilliseconds < 7000) {}
#endif
}
int gamepadIndex = 4;
ScpBus scp = new ScpBus();
X360Controller gamepad = new X360Controller();
public bool SetGamepad(bool state) {
scp.Unplug(gamepadIndex);
scp = new ScpBus();
gamepad = new X360Controller();
return state? scp.PlugIn(gamepadIndex) : false;
}
int playerID, currentRating, numplayers, frames, globalFrames, engineFrames;
bool inMatch = false;
int menuStartFrames = 0;
int ratingSafe = 0;
int state = 0;
int piece = 0;
bool register = false;
bool shouldHaveRegistered = false;
int old_y;
bool startbreak = false;
bool ppt2arewait1f = false;
void misaPrediction(int current, int[] q, int? hold, int combo, int cleared) {
int garbage_left = GameHelper.Instance.getGarbageDropping.Call(playerID);
if (!GameHelper.Instance.InSwap.Call() || cleared == 0)
AddGarbage(
misaboard,
GameHelper.Instance.RNG.Call(playerID),
GameHelper.Instance.CalculateGarbage(playerID, atk, out garbage_left)
);
MisaMinoAOT(current, q, hold, combo, garbage_left, 21 + Convert.ToInt32(!FitPieceWithConvert(misaboard, current, 4, 4, 0)));
}
void runLogic() {
numplayers = GameHelper.Instance.PlayerCount.Call();
playerID = GameHelper.Instance.FindPlayer.Call();
if (GameHelper.Instance.InMultiplayer.Call())
playerID = Preferences.Player;
int temp = GameHelper.Instance.getRating.Call();
if (temp != currentRating) {
ratingSafe = globalFrames;
}
currentRating = temp;
int y = GameHelper.Instance.getPiecePositionY.Call(playerID);
baseBoardHeight = 25 - y;
board = GameHelper.Instance.getBoard.Call(playerID);
int[,] oboard = (int[,])board.Clone();
if (GameHelper.Instance is Memory.PPT && GameHelper.Instance.OutsideMenu.Call() && GameHelper.Instance.CurrentMode.Call() == 4 && numplayers < 2 && GameHelper.Instance.boardAddress.Call(playerID) < 0x1000 && ratingSafe + 1500 < globalFrames && !(GameHelper.Instance.GameEnd.Call() != 16 || GameHelper.Instance.GameEnd.Call() != 36)) {
// ResetGame only implemented on PPT1
ResetGame();
return;
}
if (GameHelper.Instance.boardAddress.Call(playerID) > 0x1000 && GameHelper.Instance.OutsideMenu.Call() && GameHelper.Instance.getPlayer1Base.Call() > 0x1000) {
if (GameHelper.Instance is Memory.PPT && numplayers < 2 && GameHelper.Instance.CurrentMode.Call() == 4 && GameHelper.Instance.Online.Call() && !(GameHelper.Instance.GameEnd.Call() != 16 || GameHelper.Instance.GameEnd.Call() != 36)) {
ResetGame();
return;
}
int drop = GameHelper.Instance.getPieceDropped.Call(playerID);
int[] pieces = GameHelper.Instance.getPieces.Call(playerID);
bool startanim = GameHelper.Instance.getStartAnimation.Call() > 0x1000;
if (startanim && !startbreak) {
NewGame(() => {
atk = 0;
register = false;
movements.Clear();
inputStarted = 0;
softdrop = false;
speedTick = 0;
ppt2arewait1f = false;
current = pieces[0];
queue = pieces.Skip(1).Concat(GameHelper.Instance.getNextFromBags.Call(playerID)).Concat(GameHelper.Instance.getNextFromRNG(playerID, rngsearch_max, 0)).ToList();
}, 21);
useEngineFrames();
refreshEngineTimeout();
RestoreManual();
}
current = GameHelper.Instance.getCurrentPiece.Call(playerID);
startbreak = startanim;
int? hold = GameHelper.Instance.getHold.Call(playerID);
int combo = GameHelper.Instance.getCombo.Call(playerID);
if (drop != state) {
if (drop == 1) {
register = !shouldHaveRegistered;
old_y = y;
int[,] clearedboard = (int[,])board.Clone();
ClearLines(clearedboard, out int cleared);
if (!BoardEquivalent(misaboard, clearedboard, out _)) {
if (!(GameHelper.Instance is PPT2) || ppt2arewait1f) {
LogHelper.LogText("ARE");
LogHelper.LogBoard(misaboard, clearedboard);
misaboard = clearedboard;
int[] q = pieces.Skip(1).Concat(GameHelper.Instance.getNextFromBags.Call(playerID)).Concat(GameHelper.Instance.getNextFromRNG(playerID, rngsearch_max, atk)).ToArray();
q = q.Take(Math.Min(q.Length, getPreviews())).ToArray();
misaPrediction(pieces[0], q, hold, combo, cleared);
} else ppt2arewait1f = true;
}
} else if (drop == 0) shouldHaveRegistered = true;
}
if (queue.Count == 0)
queue = pieces.ToList();
bool itstimetomove = ((register && !pieces.SequenceEqual(queue.Take(pieces.Length)) && current == queue[0]) || (current != piece && piece == 255)) && y < Math.Max(6, old_y);
if (itstimetomove) {
register = false;
ppt2arewait1f = false;
}
if (!register)
queue = pieces.Concat(GameHelper.Instance.getNextFromBags.Call(playerID)).Concat(GameHelper.Instance.getNextFromRNG(playerID, rngsearch_max, 0)).ToList();
if (itstimetomove) {
shouldHaveRegistered = false;
inputStarted = 0;
softdrop = false;
b2b = GameHelper.Instance.getB2B.Call(playerID);
garbage = GameHelper.Instance.getGarbageDropping.Call(playerID);
if (MakeDecision(out bool wasHold, out _, out _)) {
//LogHelper.LogText($"[Decision] {string.Join(", ", movements)}");
int start = Convert.ToInt32(wasHold && hold == null);
int[] q = pieces.Skip(start + 1).Concat(GameHelper.Instance.getNextFromBags.Call(playerID)).Concat(GameHelper.Instance.getNextFromRNG(playerID, rngsearch_max, atk)).ToArray();
int futureCurrent = pieces[start];
int? futureHold = wasHold? current : hold;
int futureCombo = combo + Convert.ToInt32(clear > 0);
LogHelper.LogText("AOT");
misaPrediction(futureCurrent, q.Take(Math.Min(q.Length, getPreviews())).ToArray(), futureHold, futureCombo, clear);
pcboard = (int[,])misaboard.Clone();
if (movements.Count > 0)
PerfectClearAOT(futureCurrent, q, futureHold, futureCombo);
} else LogHelper.LogText("FUCK");
register = false;
}
if (!ppt2arewait1f)
state = drop;
piece = current;
inMatch = true;
} else {
if (inMatch) {
inMatch = false;
useGlobalFrames();
menuStartFrames = globalFrames;
EndGame();
}
}
board = (int[,])oboard.Clone();
}
int clear = 0;
int inputStarted = 0;
long inputGoal = -1;
bool softdrop = false;
int desiredX, desiredR;
bool desiredHold;
void processInput() {
if (movements.Count > 0) {
if (GameHelper.Instance.InSwap.Call() && GameHelper.Instance.SwapType.Call() == 0) {
softdrop = false;
movements.Clear();
inputStarted = 0;
return;
}
int boardHeight = BoardHeight(board, baseBoardHeight);
if (pieceUsed == 4 && inputStarted == 0 && boardHeight < 16) {
if (FixTspinMini(board, finalX, finalY + baseBoardHeight - 21, finalR)) { // Y is baseBoardHeight compensated
desiredX = finalX;
desiredR = finalR;
desiredHold = movements.Contains(Instruction.HOLD);
inputStarted = 3;
if (clear > 0) b2b += -1;
}
}
if (((spinUsed || boardHeight >= 16 || movements.Contains(Instruction.D) || movements.Contains(Instruction.DD)) && inputStarted != 3) || inputStarted == 1 || inputStarted == 2) {
if (inputStarted == 0 || inputStarted == 2) {
switch (movements[0]) {
case Instruction.NULL: inputGoal = -1; break;
case Instruction.L: inputGoal = GameHelper.Instance.getPiecePositionX.Call(playerID) - 1; break;
case Instruction.R: inputGoal = GameHelper.Instance.getPiecePositionX.Call(playerID) + 1; break;
case Instruction.DROP: inputGoal = 1; break;
case Instruction.HOLD: inputGoal = GameHelper.Instance.getHoldPointer.Call(playerID); break;
case Instruction.D:
inputGoal = Math.Min(
GameHelper.Instance.getPiecePositionY.Call(playerID) + 1,
FindInputGoalY(
board,
pieceUsed,
GameHelper.Instance.getPiecePositionX.Call(playerID),
GameHelper.Instance.getPiecePositionY.Call(playerID),
GameHelper.Instance.getPieceRotation.Call(playerID)
)
);
break;
case Instruction.LL:
inputGoal = FindInputGoalX(
board,
pieceUsed,
GameHelper.Instance.getPiecePositionX.Call(playerID),
GameHelper.Instance.getPiecePositionY.Call(playerID),
GameHelper.Instance.getPieceRotation.Call(playerID),
-1
);
if (movements.Count > 1 && movements[1] == Instruction.R) {
inputGoal++;
movements.RemoveAt(1);
}
break;
case Instruction.RR:
inputGoal = FindInputGoalX(
board,
pieceUsed,
GameHelper.Instance.getPiecePositionX.Call(playerID),
GameHelper.Instance.getPiecePositionY.Call(playerID),
GameHelper.Instance.getPieceRotation.Call(playerID),
1
);
if (movements.Count > 1 && movements[1] == Instruction.L) {
inputGoal--;
movements.RemoveAt(1);
}
break;
case Instruction.DD:
inputGoal = FindInputGoalY(
board,
pieceUsed,
GameHelper.Instance.getPiecePositionX.Call(playerID),
GameHelper.Instance.getPiecePositionY.Call(playerID),
GameHelper.Instance.getPieceRotation.Call(playerID)
);
break;
case Instruction.LSPIN:
inputGoal = GameHelper.Instance.getPieceRotation.Call(playerID) - 1;
if (inputGoal < 0) inputGoal = 3;
break;
case Instruction.RSPIN:
inputGoal = GameHelper.Instance.getPieceRotation.Call(playerID) + 1;
if (inputGoal > 3) inputGoal = 0;
break;
}
inputStarted = 1;
}
long inputCurrent = -1;
switch (movements[0]) {
case Instruction.NULL: inputCurrent = -1; break;
case Instruction.L:
case Instruction.R:
case Instruction.LL:
case Instruction.RR: inputCurrent = GameHelper.Instance.getPiecePositionX.Call(playerID); break;
case Instruction.D:
case Instruction.DD: inputCurrent = GameHelper.Instance.getPiecePositionY.Call(playerID); break;
case Instruction.LSPIN:
case Instruction.RSPIN: inputCurrent = GameHelper.Instance.getPieceRotation.Call(playerID); break;
case Instruction.DROP: inputCurrent = GameHelper.Instance.getPieceDropped.Call(playerID); break;
case Instruction.HOLD: inputCurrent = (GameHelper.Instance.getHoldPointer.Call(playerID) != inputGoal && GameHelper.Instance.getHoldPointer.Call(playerID) > 0x08000000) ? inputGoal : 0; break;
}
if (inputCurrent == inputGoal || (softdrop && inputCurrent >= inputGoal)) {
softdrop = false;
movements.RemoveAt(0);
inputStarted = movements.Count == 0 ? 0 : 2;
processInput();
return;
} else {
switch (movements[0]) {
case Instruction.L:
case Instruction.LL: gamepad.Buttons |= X360Buttons.Left; break;
case Instruction.R:
case Instruction.RR: gamepad.Buttons |= X360Buttons.Right; break;
case Instruction.D:
case Instruction.DD: softdrop = true; break;
case Instruction.LSPIN: gamepad.Buttons |= X360Buttons.A; break;
case Instruction.RSPIN: gamepad.Buttons |= X360Buttons.B; break;
case Instruction.DROP: gamepad.Buttons |= X360Buttons.Up; break;
case Instruction.HOLD: gamepad.Buttons |= X360Buttons.LeftBumper; break;
}
if (((movements[0] == Instruction.LSPIN && !previousInputs.HasFlag(X360Buttons.A)) || (movements[0] == Instruction.RSPIN && !previousInputs.HasFlag(X360Buttons.B))) && movements.Count > 1 && movements[1] == Instruction.DROP)
gamepad.Buttons |= X360Buttons.Up;
}
} else if (inputStarted != 1 && inputStarted != 2) { // Desire mode = faster due to rotation/movement mixing, but can't softdrop/spin
int pieceX = GameHelper.Instance.getPiecePositionX.Call(playerID);
int pieceR = GameHelper.Instance.getPieceRotation.Call(playerID);
if (inputStarted == 0) {
desiredX = pieceX;
desiredR = pieceR;
desiredHold = false;
foreach (Instruction i in movements) {
switch (i) {
case Instruction.L: desiredX--; break;
case Instruction.R: desiredX++; break;
case Instruction.LL:
desiredX = FindInputGoalX(
board,
pieceUsed,
desiredX,
GameHelper.Instance.getPiecePositionY.Call(playerID),
desiredR,
-1
);
break;
case Instruction.RR:
desiredX = FindInputGoalX(
board,
pieceUsed,
desiredX,
GameHelper.Instance.getPiecePositionY.Call(playerID),
desiredR,
1
);
break;
case Instruction.LSPIN:
desiredR--;
if (desiredR < 0) desiredR = 3;
if (pieceUsed == 6) {
switch (desiredR) {
case 0: desiredX--; break;
case 2: desiredX++; break;
}
}
desiredX = FixWall(
board,
pieceUsed,
desiredX,
GameHelper.Instance.getPiecePositionY.Call(playerID),
desiredR
);
break;
case Instruction.RSPIN:
desiredR++;
if (desiredR > 3) desiredR = 0;
if (pieceUsed == 6) {
switch (desiredR) {
case 1: desiredX++; break;
case 3: desiredX--; break;
}
}
desiredX = FixWall(
board,
pieceUsed,
desiredX,
GameHelper.Instance.getPiecePositionY.Call(playerID),
desiredR
);
break;
case Instruction.HOLD: desiredHold = true; break;
}
}
inputStarted = 3;
}
if (GameHelper.Instance.getPieceDropped.Call(playerID) == 1) {
inputStarted = 0;
movements.Clear();
return;
}
if (desiredHold) {
gamepad.Buttons |= X360Buttons.RightBumper;
}
bool nerd = desiredX == 5 && desiredR % 2 == 1 && pieceUsed == 6;
if (nerd) desiredR = 1;
if (desiredX == pieceX && desiredR == pieceR) {
gamepad.Buttons |= X360Buttons.Up;
} else {
if (desiredX != pieceX && !nerd)
if (desiredX < pieceX) {
gamepad.Buttons |= X360Buttons.Left;
} else {
gamepad.Buttons |= X360Buttons.Right;
}
if (desiredR != pieceR)
if (desiredR == 3) {
gamepad.Buttons |= X360Buttons.A;
} else {
gamepad.Buttons |= X360Buttons.B;
}
if ((desiredX == pieceX || nerd) && desiredR != pieceR && (desiredR == 3 || desiredR - pieceR == 1) && !previousInputs.HasFlag(X360Buttons.A) && !previousInputs.HasFlag(X360Buttons.B)) {
gamepad.Buttons |= X360Buttons.Up;
}
}
}
}
}
X360Buttons previousInputs = X360Buttons.None;
decimal speedTick = 0;
int charindex = 0;
void applyInputs() {
bool addDown = false;
if (GameHelper.Instance.boardAddress.Call(playerID) > 0x1000 && GameHelper.Instance.OutsideMenu.Call() && engineFrames > 0 && GameHelper.Instance.getPlayer1Base.Call() > 0x1000 && (GameHelper.Instance is Memory.PPT? GameHelper.Instance.GameEnd.Call() != 16 && GameHelper.Instance.GameEnd.Call() != 36 : true)) {
if (engineFrames != frames) {
gamepad.Buttons = X360Buttons.None;
processInput();
}
addDown = softdrop;
frames = engineFrames;
} else {
gamepad.Buttons = X360Buttons.None;
#if !PUBLIC
if (GameHelper.Instance is Memory.PPT && Preferences.SpamA && GameHelper.Instance.GetMenu.Call() == 28)
gamepad.Buttons |= globalFrames % 2 == 0? X360Buttons.A : (X360Buttons.LeftBumper | X360Buttons.Down);
else
#endif
if (globalFrames % 2 == 0) {
if (GameHelper.Instance is Memory.PPT && Preferences.SaveReplay && GameHelper.Instance.CanSaveReplay.Call() == 0 && GameHelper.Instance.MenuNavigation.Call(0) != 250 && GameHelper.Instance.OutsideMenu.Call()) {
if (GameHelper.Instance.MenuNavigation.Call(1) != 1) // end of match
gamepad.Buttons |= X360Buttons.A;
else if (GameHelper.Instance.MenuNavigation.Call(2) == 0) // not default position
gamepad.Buttons |= X360Buttons.Up;
else if (GameHelper.Instance.ConfirmingReplay.Call() != 1) // in replay confirm sub menu
gamepad.Buttons |= X360Buttons.A;
else gamepad.Buttons |= GameHelper.Instance.ReplayMenuSelection.Call() == 1? X360Buttons.A : X360Buttons.Right;
} else if (GameHelper.Instance is Memory.PPT && Preferences.PuzzleLeague) {
int mode = GameHelper.Instance.CurrentMode.Call();
if (GameHelper.Instance.OutsideMenu.Call())
gamepad.Buttons |= X360Buttons.A;
else if (mode == 4) {
if (menuStartFrames + 1150 < globalFrames)
menuStartFrames = globalFrames;
gamepad.Buttons |= menuStartFrames + 1030 < globalFrames? X360Buttons.B : X360Buttons.A;
} else if (mode == 1)
gamepad.Buttons |= X360Buttons.B;
else gamepad.Buttons |= GameHelper.Instance.MenuHighlighted.Call() == 4? X360Buttons.A : X360Buttons.Down;
// In PPT2, Character Select is really gay, and the user will need to pick character using manual input mode
} else if (!(GameHelper.Instance is PPT2) && GameHelper.Instance.InMultiplayer.Call() && GameHelper.Instance.OutsideMenu.Call()) {
if (!GameHelper.Instance.IsCharacterSelect.Call() || GameHelper.Instance.CharSelectIndex.Call(playerID) == 13) // Zed
gamepad.Buttons |= X360Buttons.A;
else if (GameHelper.Instance.CharacterSelectState.Call(playerID) > 1) // Picked not Zed on accident
gamepad.Buttons |= X360Buttons.B;
else gamepad.Buttons |= (charindex = ++charindex % 5) == 0? X360Buttons.Down : X360Buttons.Right;
}
}
}
speedTick += Preferences.Speed / 100M;
if (speedTick < 1 && inMatch) {
gamepad.Buttons = X360Buttons.None;
} else {
if (inMatch) speedTick += -1;
gamepad.Buttons &= ~previousInputs;
if (addDown)
gamepad.Buttons |= X360Buttons.Down;
if (gamepad.Buttons.HasFlag(X360Buttons.RightBumper))
gamepad.Buttons = X360Buttons.RightBumper;
if (manualtimer > 0) {
gamepad.Buttons = manualbtn;
manualtimer--;
GameHelper.Instance.ShiftFocus();
} else if (doingManualInput) gamepad.Buttons = X360Buttons.None;
previousInputs = gamepad.Buttons;
}
scp.Report(gamepadIndex, gamepad.GetReport());
//LogHelper.LogText($"[Inputs] Frame {engineFrames} {gamepad.Buttons}");
}
X360Buttons manualbtn;
int manualtimer = 0;
bool doingManualInput = false;
StackPanel _btn;
public void ManualInput(X360Buttons button, StackPanel aaaaaaa) {
doingManualInput = true;
(_btn = aaaaaaa).MaxHeight = double.PositiveInfinity;
manualbtn = button;
manualtimer = 3;
}
public void RestoreManual() {
if (GameHelper.CheckProcess())
GameHelper.Instance.ShiftFocus();
doingManualInput = false;
Window?.Dispatcher.InvokeAsync(() => {
if (_btn != null) _btn.MaxHeight = 0;
});
}
public void UpdatePriority() {
if (BotThread != null)
BotThread.Priority = Preferences.AccurateSync? ThreadPriority.Normal : ThreadPriority.AboveNormal;
}
protected override void BeforeLoop() {
BotThread = Thread.CurrentThread;
UpdatePriority();
}
int e_prev = 0;
bool usingEngineFrames = false;
Stopwatch engineFramesTimeout;
void refreshEngineTimeout() {
if (!usingEngineFrames) return;
engineFramesTimeout?.Stop();
engineFramesTimeout = new Stopwatch();
engineFramesTimeout.Start();
}
void useEngineFrames() {
if (usingEngineFrames) return;
usingEngineFrames = true;
LogHelper.LogText("[Framesync] Switched to Engine Frames");
}
void useGlobalFrames() {
if (!usingEngineFrames) return;
engineFramesTimeout?.Stop();
engineFramesTimeout = null;
usingEngineFrames = false;
LogHelper.LogText("[Framesync] Switched to Global/Menu Frames");
}
protected override void LoopIteration() {
bool newFrame = false;
if (GameHelper.CheckProcess()) {
GameHelper.TrustProcess = true;
e_prev = engineFrames;
engineFrames = GameHelper.Instance.getEngineFrameCount();
if (!usingEngineFrames && engineFrames > 6 && engineFrames != e_prev)
useEngineFrames();
else if (usingEngineFrames && engineFrames == e_prev && (engineFramesTimeout?.ElapsedMilliseconds?? 1337L) > 3000L)
useGlobalFrames();
int prev = globalFrames;
globalFrames = GameHelper.Instance.getMenuFrameCount();
ref int f = ref globalFrames, p = ref prev;
if (usingEngineFrames) {
f = engineFrames;
p = e_prev;
}
if (newFrame = f != p) {
if (f != p + 1)
LogHelper.LogText("Skipped " + (f - p - 1) + $" {(usingEngineFrames? "engine" : "global")} frames");
GameHelper.InvalidateCache();
runLogic();
applyInputs();
refreshEngineTimeout();
}
GameHelper.TrustProcess = false;
} else {
MisaMino.Abort();
PerfectClear.Abort();
}
Window.Active = inMatch;
if (!Preferences.AccurateSync && !newFrame)
Thread.Sleep(10);
}
protected override void Starting() {
scp.UnplugAll();
scp = new ScpBus();
scp.PlugIn(gamepadIndex);
}
public void Start(UI window, int gamepadindex) {
gamepadIndex = gamepadindex;
Start(window);
}
protected override void BeforeDispose() => scp.UnplugAll();
}
}
| 41.571767 | 346 | 0.463661 | [
"BSD-3-Clause"
] | mat1jaczyyy/Zetris | Zetris.PPT/PPTBot.cs | 35,047 | C# |
using System;
namespace BPlusTreePractice
{
public partial class BPlusTreeNode
{
#region Delete
/// <summary>
/// 删除指定键的记录
/// </summary>
/// <param name="key">指定键</param>
/// <param name="mergeMe">如果为真则意味着删除键后节点已经小于1/2满,需要合并</param>
/// <returns>返回节点中最小的键,如无变化则返回空</returns>
public string Delete(string key, out bool mergeMe)
{
// 如果是叶节点,则调用删除叶节点逻辑
if (this.IsLeaf)
{
return DeleteLeaf(key, out mergeMe);
}
// 假设我是不需要被合并的
mergeMe = false;
// 我是内部节点,找到指定键的位置
int deletePosition = this.FindAtOrNextPosition(key, false);
// 加载要被删除位置的子节点
BPlusTreeNode deleteChildNode = LoadNodeAtPosition(deletePosition);
// 从子节点中删除键
bool isChildNodeNeedMerge;
string deletedChildKey = deleteChildNode.Delete(key, out isChildNodeNeedMerge);
// 删除完毕,当前节点为脏节点
this.Soil();
// 发现子节点的最小键与被删除的键相同,则认为子节点已经没用了
string result = null;
if (deletedChildKey != null && this.Tree.CompareKey(deletedChildKey, key) == 0)
{
if (this.Capacity > 3)
{
throw new BPlusTreeException(
string.Format("Deletion returned delete key for too large node size: {0}.",
this.Capacity));
}
// 判断删除的是头或尾
if (deletePosition == 0)
{
result = this._childKeys[deletePosition];
}
else if (deletePosition == this.Capacity)
{
this._childKeys[deletePosition - 1] = null;
}
else
{
this._childKeys[deletePosition - 1] = this._childKeys[deletePosition];
}
if (result != null && this.Tree.CompareKey(result, key) == 0)
{
this.LoadNodeAtPosition(1);
result = this._childNodes[1].LeastKey();
}
// 这个子节点彻底没用了,释放其空间
deleteChildNode.Free();
// 节点中键位置右侧全部左移 1 位
OverwriteDeletePosition(deletePosition);
// 如果节点的使用率小于一半,则需要合并节点
if (this.Count < this.Capacity / 2)
{
mergeMe = true;
}
// 重置子节点的父节点
this.ResetAllChildrenParent();
return result;
}
if (deletePosition == 0)
{
result = deletedChildKey;
}
else if (deletedChildKey != null && deletePosition > 0)
{
if (this.Tree.CompareKey(deletedChildKey, key) != 0)
{
this._childKeys[deletePosition - 1] = deletedChildKey;
}
}
// 如果子节点需要合并
if (isChildNodeNeedMerge)
{
int leftIndex, rightIndex;
BPlusTreeNode leftNode, rightNode;
string keyBetween;
if (deletePosition == 0)
{
// 和右侧兄弟节点合并
leftIndex = deletePosition;
rightIndex = deletePosition + 1;
leftNode = deleteChildNode;
rightNode = this.LoadNodeAtPosition(rightIndex);
}
else
{
// 和左侧兄弟节点合并
leftIndex = deletePosition - 1;
rightIndex = deletePosition;
leftNode = this.LoadNodeAtPosition(leftIndex);
rightNode = deleteChildNode;
}
keyBetween = this._childKeys[leftIndex];
// 合并节点
string rightLeastKey;
bool isDeleteRight;
MergeInternal(leftNode, keyBetween, rightNode, out rightLeastKey, out isDeleteRight);
// 是否需要删除右节点
if (isDeleteRight)
{
for (int i = rightIndex; i < this.Capacity; i++)
{
this._childKeys[i - 1] = this._childKeys[i];
this._childValues[i] = this._childValues[i + 1];
this._childNodes[i] = this._childNodes[i + 1];
}
this._childKeys[this.Capacity - 1] = null;
this._childValues[this.Capacity] = StorageConstants.NullBlockNumber;
this._childNodes[this.Capacity] = null;
this.ResetAllChildrenParent();
rightNode.Free();
// 当前节点还需要再合并吗
if (this.Count < this.Capacity / 2)
{
mergeMe = true;
}
}
else
{
this._childKeys[rightIndex - 1] = rightLeastKey;
}
}
return result;
}
/// <summary>
/// 删除指定键的记录,当前节点是叶节点的情况。
/// </summary>
/// <param name="key">指定键</param>
/// <param name="mergeMe">如果为真则意味着删除键后节点已经小于1/2满,需要合并</param>
/// <returns>返回节点中最小的键,如无变化则返回空</returns>
public string DeleteLeaf(string key, out bool mergeMe)
{
// 假设我是不需要被合并的
mergeMe = false;
// 如果自己不是叶节点,那一定是用错了方法
if (!this.IsLeaf)
{
throw new BPlusTreeException("Bad call to delete leaf, this is not a leaf.");
}
// 先找到指定的键的位置
bool isKeyFound = false;
int deletePosition = 0;
foreach (string childKey in this._childKeys)
{
if (childKey != null && this.Tree.CompareKey(childKey, key) == 0)
{
isKeyFound = true;
break;
}
deletePosition++;
}
if (!isKeyFound)
{
throw new BPlusTreeKeyNotFoundException(
string.Format("Cannot delete missing key: {0}.", key));
}
// 这个节点即将被修改,先标记为脏节点
this.Soil();
// 将指定键位置右侧的数据左移 1 位,覆盖掉指定键,也就算删除了
for (int i = deletePosition; i < this.Capacity - 1; i++)
{
this._childKeys[i] = this._childKeys[i + 1];
this._childValues[i] = this._childValues[i + 1];
}
this._childKeys[this.Capacity - 1] = null;
// 如果节点的使用率小于一半,小于 1/2 满,则需要合并节点
if (this.Count < this.Capacity / 2)
{
mergeMe = true;
}
// 返回被删后的最小键
string result = null;
if (deletePosition == 0)
{
result = this._childKeys[0];
if (result == null)
{
result = key; // 被删除的键
}
}
return result;
}
/// <summary>
/// 节点中键位置右侧全部左移 1 位
/// </summary>
/// <param name="deletePosition">被删除的键位置</param>
private void OverwriteDeletePosition(int deletePosition)
{
// 节点中键位置右侧全部左移 1 位
for (int i = deletePosition; i < this.Capacity - 1; i++)
{
this._childKeys[i] = this._childKeys[i + 1];
this._childValues[i] = this._childValues[i + 1];
this._childNodes[i] = this._childNodes[i + 1];
}
this._childKeys[this.Capacity - 1] = null;
if (deletePosition < this.Capacity)
{
this._childValues[this.Capacity - 1] = this._childValues[this.Capacity];
this._childNodes[this.Capacity - 1] = this._childNodes[this.Capacity];
}
this._childNodes[this.Capacity] = null;
this._childValues[this.Capacity] = StorageConstants.NullBlockNumber;
}
/// <summary>
/// 获取最小的键
/// </summary>
/// <returns>最小的键</returns>
private string LeastKey()
{
string key = null;
if (this.IsLeaf)
{
key = this._childKeys[0];
}
else
{
this.LoadNodeAtPosition(0);
key = this._childNodes[0].LeastKey();
}
if (key == null)
{
throw new BPlusTreeException("No least key found.");
}
return key;
}
#endregion
#region Merge
/// <summary>
/// 合并内部节点,当节点的使用率不足 50% 时,则需要合并
/// </summary>
/// <param name="left">左节点</param>
/// <param name="keyBetween">左右节点的中间键</param>
/// <param name="right">右节点</param>
/// <param name="rightLeastKey">合并后的键的最小值</param>
/// <param name="canDeleteRightNode">是否可以删除右节点</param>
public static void MergeInternal(BPlusTreeNode left, string keyBetween, BPlusTreeNode right, out string rightLeastKey, out bool canDeleteRightNode)
{
if (left == null)
throw new ArgumentNullException("left");
if (right == null)
throw new ArgumentNullException("right");
rightLeastKey = null; // only if DeleteRight
// 合并叶节点
if (left.IsLeaf || right.IsLeaf)
{
if (!(left.IsLeaf && right.IsLeaf))
{
throw new BPlusTreeException("Cannot merge leaf with non-leaf.");
}
// 合并子节点
MergeLeaves(left, right, out canDeleteRightNode);
rightLeastKey = right._childKeys[0];
return;
}
// 合并非叶节点
canDeleteRightNode = false;
if (left._childValues[0] == StorageConstants.NullBlockNumber || right._childValues[0] == StorageConstants.NullBlockNumber)
{
throw new BPlusTreeException("Cannot merge empty non-leaf with non-leaf.");
}
string[] allKeys = new string[left.Capacity * 2 + 1];
long[] allValues = new long[left.Capacity * 2 + 2];
BPlusTreeNode[] allNodes = new BPlusTreeNode[left.Capacity * 2 + 2];
// 拷贝左节点的数据
int index = 0;
allValues[0] = left._childValues[0];
allNodes[0] = left._childNodes[0];
for (int i = 0; i < left.Capacity; i++)
{
if (left._childKeys[i] == null)
{
break;
}
allKeys[index] = left._childKeys[i];
allValues[index + 1] = left._childValues[i + 1];
allNodes[index + 1] = left._childNodes[i + 1];
index++;
}
// 拷贝中间键
allKeys[index] = keyBetween;
index++;
// 拷贝右节点的数据
allValues[index] = right._childValues[0];
allNodes[index] = right._childNodes[0];
int rightCount = 0;
for (int i = 0; i < right.Capacity; i++)
{
if (right._childKeys[i] == null)
{
break;
}
allKeys[index] = right._childKeys[i];
allValues[index + 1] = right._childValues[i + 1];
allNodes[index + 1] = right._childNodes[i + 1];
index++;
rightCount++;
}
// 如果数量小于左节点的能力,则右节点可以删除掉
if (index <= left.Capacity)
{
// it will all fit in one node
canDeleteRightNode = true;
for (int i = 0; i < index; i++)
{
left._childKeys[i] = allKeys[i];
left._childValues[i] = allValues[i];
left._childNodes[i] = allNodes[i];
}
left._childValues[index] = allValues[index];
left._childNodes[index] = allNodes[index];
left.ResetAllChildrenParent();
left.Soil();
right.Free();
return;
}
// otherwise split the content between the nodes
left.Clear();
right.Clear();
left.Soil();
right.Soil();
int leftContent = index / 2;
int rightContent = index - leftContent - 1;
rightLeastKey = allKeys[leftContent];
int outputIndex = 0;
for (int i = 0; i < leftContent; i++)
{
left._childKeys[i] = allKeys[outputIndex];
left._childValues[i] = allValues[outputIndex];
left._childNodes[i] = allNodes[outputIndex];
outputIndex++;
}
rightLeastKey = allKeys[outputIndex];
left._childValues[outputIndex] = allValues[outputIndex];
left._childNodes[outputIndex] = allNodes[outputIndex];
outputIndex++;
rightCount = 0;
for (int i = 0; i < rightContent; i++)
{
right._childKeys[i] = allKeys[outputIndex];
right._childValues[i] = allValues[outputIndex];
right._childNodes[i] = allNodes[outputIndex];
outputIndex++;
rightCount++;
}
right._childValues[rightCount] = allValues[outputIndex];
right._childNodes[rightCount] = allNodes[outputIndex];
left.ResetAllChildrenParent();
right.ResetAllChildrenParent();
}
/// <summary>
/// 合并叶节点,当节点的使用率不足 50% 时,则需要合并
/// </summary>
/// <param name="left">左节点</param>
/// <param name="right">右节点</param>
/// <param name="canDeleteRightNode">是否可以删除右节点</param>
public static void MergeLeaves(BPlusTreeNode left, BPlusTreeNode right, out bool canDeleteRightNode)
{
if (left == null)
throw new ArgumentNullException("left");
if (right == null)
throw new ArgumentNullException("right");
canDeleteRightNode = false;
string[] allKeys = new string[left.Capacity * 2];
long[] allValues = new long[left.Capacity * 2];
int index = 0;
for (int i = 0; i < left.Capacity; i++)
{
if (left._childKeys[i] == null)
{
break;
}
allKeys[index] = left._childKeys[i];
allValues[index] = left._childValues[i];
index++;
}
for (int i = 0; i < right.Capacity; i++)
{
if (right._childKeys[i] == null)
{
break;
}
allKeys[index] = right._childKeys[i];
allValues[index] = right._childValues[i];
index++;
}
// 如果左节点的容量足够,则可删除右节点
if (index <= left.Capacity)
{
canDeleteRightNode = true;
left.Clear();
for (int i = 0; i < index; i++)
{
left._childKeys[i] = allKeys[i];
left._childValues[i] = allValues[i];
}
left.Soil();
right.Free();
return;
}
// 左节点的容量不够了
left.Clear();
right.Clear();
left.Soil();
right.Soil();
int rightContent = index / 2;
int leftContent = index - rightContent;
int newIndex = 0;
for (int i = 0; i < leftContent; i++)
{
left._childKeys[i] = allKeys[newIndex];
left._childValues[i] = allValues[newIndex];
newIndex++;
}
for (int i = 0; i < rightContent; i++)
{
right._childKeys[i] = allKeys[newIndex];
right._childValues[i] = allValues[newIndex];
newIndex++;
}
}
#endregion
}
}
| 26.902299 | 152 | 0.535071 | [
"MIT"
] | gaochundong/BPlusTreePractice | BPlusTreePractice/BPlusTreeNode.Delete.cs | 15,417 | C# |
using System;
using Xunit;
namespace Firestorm.Endpoints.Tests.Start
{
public class ValidationExtensionTests
{
[Fact]
public void EnsureValid_DefaultConfiguration_DoesntThrow()
{
var config = new EndpointConfiguration();
config.EnsureValid();
}
[Fact]
public void EnsureValid_NullQueryStringConfiguration_Throws()
{
var config = new EndpointConfiguration
{
QueryString = null
};
Action ensureValid = () => config.EnsureValid();
Assert.Throws<FirestormConfigurationException>(ensureValid);
}
[Fact]
public void EnsureValid_NullUrlConfiguration_Throws()
{
var config = new EndpointConfiguration
{
Url = null
};
Action ensureValid = () => config.EnsureValid();
Assert.Throws<FirestormConfigurationException>(ensureValid);
}
[Fact]
public void EnsureValid_NullResponseConfiguration_Throws()
{
var config = new EndpointConfiguration
{
Response = null
};
Action ensureValid = () => config.EnsureValid();
Assert.Throws<FirestormConfigurationException>(ensureValid);
}
[Fact]
public void EnsureValid_NullNamingConventionConfiguration_Throws()
{
var config = new EndpointConfiguration
{
NamingConventions = null
};
Action ensureValid = () => config.EnsureValid();
Assert.Throws<FirestormConfigurationException>(ensureValid);
}
}
}
| 25.173913 | 74 | 0.56304 | [
"MIT"
] | connellw/Firestorm | tests/Firestorm.Endpoints.Tests/Start/ValidationExtensionTests.cs | 1,739 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.ComponentModel;
namespace Azure.ResourceManager.Sql.Models
{
/// <summary> The unit of the metric. </summary>
public readonly partial struct QueryMetricUnitType : IEquatable<QueryMetricUnitType>
{
private readonly string _value;
/// <summary> Initializes a new instance of <see cref="QueryMetricUnitType"/>. </summary>
/// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
public QueryMetricUnitType(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
private const string PercentageValue = "percentage";
private const string KBValue = "KB";
private const string MicrosecondsValue = "microseconds";
private const string CountValue = "count";
/// <summary> percentage. </summary>
public static QueryMetricUnitType Percentage { get; } = new QueryMetricUnitType(PercentageValue);
/// <summary> KB. </summary>
public static QueryMetricUnitType KB { get; } = new QueryMetricUnitType(KBValue);
/// <summary> microseconds. </summary>
public static QueryMetricUnitType Microseconds { get; } = new QueryMetricUnitType(MicrosecondsValue);
/// <summary> count. </summary>
public static QueryMetricUnitType Count { get; } = new QueryMetricUnitType(CountValue);
/// <summary> Determines if two <see cref="QueryMetricUnitType"/> values are the same. </summary>
public static bool operator ==(QueryMetricUnitType left, QueryMetricUnitType right) => left.Equals(right);
/// <summary> Determines if two <see cref="QueryMetricUnitType"/> values are not the same. </summary>
public static bool operator !=(QueryMetricUnitType left, QueryMetricUnitType right) => !left.Equals(right);
/// <summary> Converts a string to a <see cref="QueryMetricUnitType"/>. </summary>
public static implicit operator QueryMetricUnitType(string value) => new QueryMetricUnitType(value);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is QueryMetricUnitType other && Equals(other);
/// <inheritdoc />
public bool Equals(QueryMetricUnitType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc />
public override string ToString() => _value;
}
}
| 48.206897 | 138 | 0.682403 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/QueryMetricUnitType.cs | 2,796 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MxNet.SciKit.Ensemble.HistGradientBoosting
{
class TreeNode
{
}
}
| 14.272727 | 52 | 0.738854 | [
"Apache-2.0"
] | SciSharp/MxNet.Sharp | src/MxNet.Scikit/Ensemble/HistGradientBoosting/TreeNode.cs | 159 | C# |
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace CodeAnalyzer.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ConstantAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "MakeConstCS";
private const string Title = "Variable can be made constant";
private const string MessageFormat = "Can be made constant";
private const string Description = "Make Constant";
private const string Category = "Usage";
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
public override void Initialize(AnalysisContext context)
{
//context.RegisterSyntaxNodeAction(AnalyzePotentialConstant, SyntaxKind.LocalDeclarationStatement);
}
private static void AnalyzePotentialConstant(SyntaxNodeAnalysisContext context)
{
var localDeclaration = (LocalDeclarationStatementSyntax)context.Node;
// Only consider local variable declarations that aren't already const.
if (localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword))
{
return;
}
var variableTypeName = localDeclaration.Declaration.Type;
var variableType = context.SemanticModel.GetTypeInfo(variableTypeName).ConvertedType;
// Ensure that all variables in the local declaration have initializers that
// are assigned with constant values.
foreach (var variable in localDeclaration.Declaration.Variables)
{
var initializer = variable.Initializer;
if (initializer is null)
{
return;
}
var constantValue = context.SemanticModel.GetConstantValue(initializer.Value);
if (!constantValue.HasValue)
{
return;
}
// Ensure that the initializer value can be converted to the type of the
// local declaration without a user-defined conversion.
var conversion = context.SemanticModel.ClassifyConversion(initializer.Value, variableType);
if (!conversion.Exists || conversion.IsUserDefined)
{
return;
}
// Special cases:
// * If the constant value is a string, the type of the local declaration
// must be System.String.
// * If the constant value is null, the type of the local declaration must
// be a reference type.
if (constantValue.Value is string)
{
if (variableType.SpecialType != SpecialType.System_String)
{
return;
}
}
else if (variableType.IsReferenceType && constantValue.Value != null)
{
return;
}
}
// Perform data flow analysis on the local declaration.
var dataFlowAnalysis = context.SemanticModel.AnalyzeDataFlow(localDeclaration);
// Retrieve the local symbol for each variable in the local declaration
// and ensure that it is not written outside of the data flow analysis region.
foreach (var variable in localDeclaration.Declaration.Variables)
{
var variableSymbol = context.SemanticModel.GetDeclaredSymbol(variable);
if (dataFlowAnalysis.WrittenOutside.Contains(variableSymbol))
{
return;
}
}
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
}
}
}
| 42.35 | 211 | 0.609917 | [
"MIT"
] | KThaulow/CodeAnalyzer | src/CodeAnalyzer/Analyzers/ConstantAnalyzer.cs | 4,237 | C# |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 Akan Murat Cimen
*
* 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;
namespace ArgsMapper.ValueConversion.Converters
{
internal class ObjectValueConverter : ISystemTypeValueConverter
{
public object Convert(string value, IFormatProvider formatProvider)
{
return value;
}
}
}
| 39.472222 | 83 | 0.741027 | [
"MIT"
] | akanmuratcimen/args-mapper | src/ArgsMapper/ValueConversion/Converters/ObjectValueConverter.cs | 1,421 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Snoffleware.LLBLGen.Identity.Core.Models;
namespace Snoffleware.LLBLGen.Identity.WebTest.Areas.Identity.Pages.Account.Manage
{
public class DeletePersonalDataModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<DeletePersonalDataModel> _logger;
public DeletePersonalDataModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<DeletePersonalDataModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
public bool RequirePassword { get; set; }
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
if (RequirePassword)
{
if (!await _userManager.CheckPasswordAsync(user, Input.Password))
{
ModelState.AddModelError(string.Empty, "Incorrect password.");
return Page();
}
}
var result = await _userManager.DeleteAsync(user);
var userId = await _userManager.GetUserIdAsync(user);
if (!result.Succeeded)
{
throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
}
await _signInManager.SignOutAsync();
_logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);
return Redirect("~/");
}
}
}
| 33.152941 | 116 | 0.604684 | [
"MIT"
] | sucrose0413/Snoffleware.LLBLGen.Identity | Snoffleware.LLBLGen.Identity.WebTest/Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml.cs | 2,820 | C# |
using AI.BackEnds.DSP.NWaves.Windows;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace AI.BackEnds.DSP.NWaves.FeatureExtractors.Options
{
[DataContract]
public class PnccOptions : FilterbankOptions
{
[DataMember]
public int Power { get; set; } = 15;
[DataMember]
public bool IncludeEnergy { get; set; }
[DataMember]
public float LogEnergyFloor { get; set; } = float.Epsilon;
public PnccOptions()
{
LowFrequency = 100;
HighFrequency = 6800;
FilterBankSize = 40;
Window = WindowTypes.Hamming;
}
public override List<string> Errors
{
get
{
List<string> errors = base.Errors;
if (FeatureCount <= 0)
{
errors.Add("Positive number of PNCC coefficients must be specified");
}
return errors;
}
}
}
}
| 25.6 | 89 | 0.536133 | [
"Apache-2.0"
] | AIFramework/AIFrameworkOpen | AI/BackEnds/DSP/NWaves/FeatureExtractors/Options/PnccOptions.cs | 1,026 | C# |
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace RedditCore.Http
{
/// <summary>
/// Interface that wraps HTTP calls. This is so that we can mock all HTTP calls for testing without having to use MSFT
/// Fakes. This is also done so we can centralize serialization & deserialization of objects.
/// </summary>
public interface IHttpClient
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="requestUri">URI to GET</param>
/// <param name="requestTimeout">Timeout for the request. If not specified then the timeout will be the default value defined by the .NET HTTP client.</param>
/// <param name="authenticationHeaderValue">Authentication header. If NULL then no authentication header will be used.</param>
/// <returns></returns>
Task<IHttpJsonResponseMessage<T>> GetJsonAsync<T>(
Uri requestUri,
TimeSpan? requestTimeout = null,
AuthenticationHeaderValue authenticationHeaderValue = null);
/// <summary>
/// Issues an HTTP Delete.
/// </summary>
/// <param name="requestUri">URI to DELETE</param>
/// <param name="requestTimeout">Timeout for the request. If not specified then the timeout will be the default value defined by the .NET HTTP client.</param>
/// <param name="authenticationHeaderValue">Authentication header. If NULL then no authentication header will be used.</param>
/// <param name="requestTimeout"></param>
/// <returns></returns>
Task<HttpResponseMessage> DeleteAsync(
Uri requestUri,
TimeSpan? requestTimeout = null,
AuthenticationHeaderValue authenticationHeaderValue = null);
}
}
| 45.414634 | 167 | 0.648228 | [
"MIT"
] | Bhaskers-Blu-Org2/BusinessPlatformApps | Functions/Code/Reddit/Src/RedditCore/Http/IHttpClient.cs | 1,864 | C# |
using CalcWin.DataAccess.Model;
using System.Collections.Generic;
namespace CalcWin.Models.ProjectsViewModel
{
public class ProjectsViewModel
{
// Start data
public List<WineProject> Projects { get; set; }
// Edit Project
public int ProjectId { get; set; }
public WineProject WineProject { get; set; }
}
}
| 22.5625 | 55 | 0.65374 | [
"MIT"
] | katanisk8/CalcWin | CalcWin/Models/ProjectsViewModels/ProjectsViewModel.cs | 363 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview
{
using Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.PowerShell;
/// <summary>Defines reference to a proxy resource.</summary>
[System.ComponentModel.TypeConverter(typeof(ProxyResourceReferenceTypeConverter))]
public partial class ProxyResourceReference
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.ProxyResourceReference"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IProxyResourceReference"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IProxyResourceReference DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new ProxyResourceReference(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.ProxyResourceReference"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IProxyResourceReference"
/// />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IProxyResourceReference DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new ProxyResourceReference(content);
}
/// <summary>
/// Creates a new instance of <see cref="ProxyResourceReference" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IProxyResourceReference FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.ProxyResourceReference"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal ProxyResourceReference(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IProxyResourceReferenceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IProxyResourceReferenceInternal)this).Name, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IAzureResourceReferenceInternal)this).SourceArmResourceId = (string) content.GetValueForProperty("SourceArmResourceId",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IAzureResourceReferenceInternal)this).SourceArmResourceId, global::System.Convert.ToString);
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.ProxyResourceReference"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal ProxyResourceReference(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IProxyResourceReferenceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IProxyResourceReferenceInternal)this).Name, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IAzureResourceReferenceInternal)this).SourceArmResourceId = (string) content.GetValueForProperty("SourceArmResourceId",((Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IAzureResourceReferenceInternal)this).SourceArmResourceId, global::System.Convert.ToString);
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Defines reference to a proxy resource.
[System.ComponentModel.TypeConverter(typeof(ProxyResourceReferenceTypeConverter))]
public partial interface IProxyResourceReference
{
}
} | 67.2 | 378 | 0.704034 | [
"MIT"
] | 3quanfeng/azure-powershell | src/ResourceMover/generated/api/Models/Api20191001Preview/ProxyResourceReference.PowerShell.cs | 8,938 | C# |
namespace FewBox.ActiveDirectory.Core.Attribute
{
/// <summary>
/// Domain Object Attribute const values.
/// </summary>
public class DomainControllerAttributeValues
{
/// <summary>
/// The domain DNS attribute value.
/// </summary>
public const string DomainDNS = "domainDNS";
/// <summary>
/// The domain attribute value.
/// </summary>
public const string Domain = "domain";
}
}
| 24.842105 | 52 | 0.576271 | [
"Apache-2.0"
] | FewBox/ActiveDirectory.Core | FewBox.ActiveDirectory.Core/Attribute/DomainControllerAttributeValues.cs | 474 | C# |
using NUnit.Framework;
using Xero.Api.Infrastructure.Exceptions;
namespace CoreTests.Integration.LinkedTransactions
{
public class Delete : LinkedTransactionTest
{
[Test]
public void can_delete_linked_transactions()
{
Given_a_basic_linked_transaction();
var id = LinkedTransactionId;
Api.LinkedTransactions.Delete(LinkedTransaction);
//After deleting the linked transaction, it no longer exists so we exopect to get a 404 NotFound when looking for it.
Assert.Throws<NotFoundException>(() => Api.LinkedTransactions.Find(id));
}
}
}
| 29.090909 | 129 | 0.676563 | [
"MIT",
"Unlicense"
] | prajapatichintan/Xero-Net-With-oAuth2.0-Support | CoreTests/Integration/LinkedTransactions/Delete.cs | 642 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public GameObject gameOverCanvas;
public GameObject scoreCanvas;
public GameObject pauseCanvas;
public GameObject tapToPlay;
public GameObject tapToPlayButton;
public GameObject getReady;
public GameObject pauseButton;
public TextMeshProUGUI score;
// Start is called before the first frame update
void Awake()
{
Time.timeScale = 0;
pauseButton.SetActive(false);
}
public void GameOver()
{
gameOverCanvas.SetActive(true);
scoreCanvas.SetActive(false);
pauseCanvas.SetActive(false);
Time.timeScale = 0;
}
public void Replay()
{
Scene scene = SceneManager.GetActiveScene(); SceneManager.LoadScene(scene.name);
}
public void Play()
{
Time.timeScale = 1;
tapToPlay.SetActive(false);
tapToPlayButton.SetActive(false);
getReady.SetActive(false);
pauseButton.SetActive(true);
}
public void NextLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
| 23.537037 | 88 | 0.675059 | [
"MIT"
] | emyl089/doftana-heads | Assets/Scripts/GameManager.cs | 1,273 | C# |
using System;
using FluentAssertions;
using NUnit.Framework;
using Resgrid.Model;
namespace Resgrid.Tests.Models
{
[TestFixture]
public class MobileCarrierTests
{
[Test]
public void CarriersMapShouldPullBackCorrectValue()
{
var mts = Carriers.CarriersMap[MobileCarriers.MTSMobility];
mts.Should().NotBeNullOrWhiteSpace();
mts.Should().Be("{0}@text.mtsmobility.com");
}
[Test]
public void CarriersNumberLengthShouldPullBackCorrectValue()
{
var rogers = Carriers.CarriersNumberLength[MobileCarriers.RogersWireless];
rogers.Should().NotBeNull();
rogers.Should().Be(Tuple.Create(10, "Format is ###-###-####, No country code."));
}
[Test]
public void DirectSendCarriersShouldPullBackCorrectValue()
{
//var returnValue = Carriers.DirectSendCarriers.Contains(MobileCarriers.Att);
var returnValue = Carriers.DirectSendCarriers.Contains(MobileCarriers.BellMobility);
returnValue.Should().BeTrue();
}
}
}
| 24.538462 | 87 | 0.741902 | [
"Apache-2.0"
] | Joshb888/dfdfd | Tests/Resgrid.Tests/Models/MobileCarrierTests.cs | 959 | C# |
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore;
using System;
using Microsoft.AspNetCore.Identity;
using Rent.Shared.Models;
using Rent.Server.Repositories;
namespace Rent.Server.Data.Configuration
{
public class DealConfiguration : IEntityTypeConfiguration<Deal>
{
public void Configure(EntityTypeBuilder<Deal> builder)
{
builder.HasOne(d => d.DealRealty)
.WithMany(p => p.RealtyDeals)
.HasForeignKey(d => d.DealRealtyId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(d => d.Owner)
.WithMany(p => p.DealsAsOwner)
.HasForeignKey(d => d.OwnerId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(d => d.Tenant)
.WithMany(p => p.DealsAsTenant)
.HasForeignKey(d => d.TenantId)
.OnDelete(DeleteBehavior.Cascade);
}
}
} | 29.178571 | 64 | 0.738066 | [
"Apache-2.0"
] | AlexanderSolomin/RentApp | Rent/Server/Data/Configuration/DealConfiguration.cs | 817 | C# |
using System;
using System.Linq;
using System.Threading;
namespace ThreadpoolExample
{
class Program
{
private static int _finishedItems;
static void Main(string[] args)
{
int taskCount = 1000;
Enumerable.Range(0, taskCount).ToList().ForEach(i => ThreadPool.QueueUserWorkItem(WorkItem));
while (_finishedItems < taskCount)
{
Thread.Sleep(100);
}
}
private static void WorkItem(object state)
{
Thread.Sleep(100);
Interlocked.Increment(ref _finishedItems);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
}
}
| 24.206897 | 105 | 0.579772 | [
"MIT"
] | vhe1/XITASO.AsyncLightningTalk | ThreadpoolExample/Program.cs | 704 | 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 bmp_creation.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings: global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 32.83871 | 149 | 0.61002 | [
"MIT"
] | darklink623/palette-creator | bmp creation/bmp creation/Properties/Settings.Designer.cs | 1,020 | C# |
using Hk.Core.Data.Repositories;
using Hk.Core.Entity.Base_SysManage;
using Hk.Core.Util.Datas;
using Hk.Core.Util.Dependency;
using System.Collections.Generic;
namespace Hk.Core.IRepositorys
{
public interface IBaseSysRoleRepository:IRepository<Base_SysRole,string>,IScopeDependency
{
List<Base_SysRole> GetDataList(string condition, string keyword, Pagination pagination);
Base_SysRole GetTheData(string id);
void AddData(Base_SysRole newData);
void UpdateData(Base_SysRole theData);
void DeleteData(List<string> ids);
string GetRoleName(string userId);
}
} | 34.5 | 96 | 0.748792 | [
"MIT"
] | a275979650/NetCoreFramewoker | Hk.Core.Framework/Hk.Core.IRepositorys/IBaseSysRoleRepository.cs | 623 | C# |
using AdventOfCode.Common;
using AdventOfCode.Common.Extensions;
namespace AdventOfCode.Day4;
public class Table
{
public long CalculateScore()
{
var totalScore = 0;
for (var vertical = 0; vertical < _board.GetLength(0); vertical++)
{
for (var horizontal = 0; horizontal < _board.GetLength(1); horizontal++)
{
var isMarked = _markedNumbers[vertical, horizontal];
if (!isMarked)
{
totalScore += _board[vertical, horizontal];
}
}
}
var winningNumber = _drawnNumbers.LastOrDefault();
totalScore *= winningNumber;
return totalScore;
}
public int DrawnNumbersCount => _drawnNumbers.Count;
private readonly byte[,] _board;
private readonly bool[,] _markedNumbers;
private readonly IList<byte> _drawnNumbers;
private bool _isWinner;
public Table(byte[,] board)
{
_board = board;
const int BoardSize = 5;
_markedNumbers = new bool[BoardSize, BoardSize];
_drawnNumbers = new List<byte>();
}
public void MarkNumber(byte numberDrawn)
{
if (_isWinner) return;
_drawnNumbers.Add(numberDrawn);
for (var vertical = 0; vertical < _board.GetLength(0); vertical++)
{
for (var horizontal = 0; horizontal < _board.GetLength(1); horizontal++)
{
var numberOnBoard = _board[vertical, horizontal];
if (numberOnBoard == numberDrawn)
{
_markedNumbers[vertical, horizontal] = true;
return;
}
}
}
}
public bool IsWinner()
{
if (_isWinner) return _isWinner;
_isWinner = IsWinningRow() || IsWinningColumn();
return _isWinner;
bool IsWinningRow()
{
for (var vertical = 0; vertical < _markedNumbers.GetLength(0); vertical++)
{
if (IsWinningRow(vertical)) return true;
}
bool IsWinningRow(int row)
{
bool isWinner = true;
for (var horizontal = 0; horizontal < _markedNumbers.GetLength(1); horizontal++)
{
isWinner = isWinner && _markedNumbers[row, horizontal];
}
return isWinner;
}
return false;
}
bool IsWinningColumn()
{
for (var horizontal = 0; horizontal < _markedNumbers.GetLength(1); horizontal++)
{
if (IsWinningColumn(horizontal)) return true;
}
bool IsWinningColumn(int column)
{
var isWinner = true;
for (var vertical = 0; vertical < _markedNumbers.GetLength(0); vertical++)
{
isWinner = isWinner && _markedNumbers[vertical, column];
}
return isWinner;
}
return false;
}
}
public static Table Parse(string tableLines)
{
var board = tableLines
.SplitByEndOfLine()
.Select(
boardLine => boardLine
.Split(' ')
.Where(cell => !string.IsNullOrWhiteSpace(cell))
.Select(cell => byte.Parse(cell))
.ToArray()
)
.ToArray()
.To2D();
return new Table(board);
}
} | 26.649254 | 96 | 0.506301 | [
"MIT"
] | Almantask/AdventOfCode2021 | AdventOfCode/Day4/Table.cs | 3,573 | C# |
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipayOfflineProviderMonitorLogSyncModel Data Structure.
/// </summary>
[Serializable]
public class AlipayOfflineProviderMonitorLogSyncModel : AopObject
{
/// <summary>
/// 数据回流日志
/// </summary>
[XmlArray("logs")]
[XmlArrayItem("i_s_v_log_sync")]
public List<ISVLogSync> Logs { get; set; }
}
}
| 24.571429 | 70 | 0.610465 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/AlipayOfflineProviderMonitorLogSyncModel.cs | 528 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.Health.Dicom.Core.Configs;
using Microsoft.Health.Dicom.Core.Features.Common;
using Microsoft.Health.Dicom.Core.Features.Delete;
using Microsoft.Health.Dicom.Core.Features.Store;
using Microsoft.IO;
using NSubstitute;
using Xunit;
namespace Microsoft.Health.Dicom.Tests.Integration.Persistence
{
public class DeleteServiceTestsFixture : IAsyncLifetime
{
private readonly SqlDataStoreTestsFixture _sqlDataStoreTestsFixture;
private readonly DataStoreTestsFixture _blobStorageTestsFixture;
public DeleteServiceTestsFixture()
{
_sqlDataStoreTestsFixture = new SqlDataStoreTestsFixture();
_blobStorageTestsFixture = new DataStoreTestsFixture();
RecyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
}
public DeleteService DeleteService { get; private set; }
public RecyclableMemoryStreamManager RecyclableMemoryStreamManager { get; }
public IIndexDataStore IndexDataStore => _sqlDataStoreTestsFixture.IndexDataStore;
public IIndexDataStoreTestHelper IndexDataStoreTestHelper => _sqlDataStoreTestsFixture.TestHelper;
public IFileStore FileStore => _blobStorageTestsFixture.FileStore;
public IMetadataStore MetadataStore => _blobStorageTestsFixture.MetadataStore;
public async Task InitializeAsync()
{
await _sqlDataStoreTestsFixture.InitializeAsync();
await _blobStorageTestsFixture.InitializeAsync();
var cleanupConfiguration = new DeletedInstanceCleanupConfiguration
{
BatchSize = 10,
DeleteDelay = TimeSpan.FromSeconds(1),
MaxRetries = 3,
PollingInterval = TimeSpan.FromSeconds(1),
RetryBackOff = TimeSpan.FromSeconds(2),
};
var optionsConfiguration = Substitute.For<IOptions<DeletedInstanceCleanupConfiguration>>();
optionsConfiguration.Value.Returns(cleanupConfiguration);
DeleteService = new DeleteService(
_sqlDataStoreTestsFixture.SqlIndexDataStoreFactory,
_blobStorageTestsFixture.MetadataStore,
_blobStorageTestsFixture.FileStore,
optionsConfiguration,
_sqlDataStoreTestsFixture.SqlTransactionHandler,
NullLogger<DeleteService>.Instance);
}
public async Task DisposeAsync()
{
await _sqlDataStoreTestsFixture.DisposeAsync();
await _blobStorageTestsFixture.DisposeAsync();
}
}
}
| 40.194805 | 106 | 0.661712 | [
"MIT"
] | QPC-database/dicom-server | test/Microsoft.Health.Dicom.Tests.Integration/Persistence/DeleteServiceTestsFixture.cs | 3,097 | C# |
//Declare five variables choosing for each of them the most appropriate of the types byte, sbyte, short, ushort, int, uint, long, ulong to represent the following values: 52130, -115, 4825932, 97, -10000.
//Choose a large enough type for each number to ensure it will fit in it. Try to compile the code.
using System;
class Variables
{
static void Main()
{
ushort a = 52130;
sbyte b = -115;
uint c = 4825932;
byte d = 97;
short e = -10000;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Console.WriteLine(e);
}
}
| 29.5 | 205 | 0.625578 | [
"MIT"
] | mdraganov/Telerik-Academy | C#/C# Programming Part I/PrimitiveDataTypesAndVariables/DeclareVariables/Variables.cs | 651 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Devices.PointOfService
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public enum PosPrinterCartridgeSensors
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
None,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Removed,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
Empty,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
HeadCleaning,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
NearEnd,
#endif
}
#endif
}
| 27.103448 | 63 | 0.693384 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.PointOfService/PosPrinterCartridgeSensors.cs | 786 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using AutoLot.Dal.BulkImport;
using AutoLot.Dal.DataOperations;
using AutoLot.Dal.Models;
namespace AutoLot.Client
{
class Program
{
static void Main(string[] args)
{
DoBulkCopy();
//FlagCustomer();
InventoryDal dal = new();
List<CarViewModel> list = dal.GetAllInventory();
Console.WriteLine(" ************** All Cars ************** ");
Console.WriteLine("Id\tMake\tColor\tPet Name");
foreach (CarViewModel carViewModel in list)
{
Console.WriteLine($"{carViewModel.Id}\t{carViewModel.Make}\t{carViewModel.Color}\t{carViewModel.PetName}");
}
Console.WriteLine();
CarViewModel car = dal.GetCar(list.OrderBy(x => x.Color).Select(x => x.Id).First());
Console.WriteLine(" ************** First Car By Color ************** ");
Console.WriteLine("CarId\tMake\tColor\tPet Name");
Console.WriteLine($"{car.Id}\t{car.Make}\t{car.Color}\t{car.PetName}");
try
{
dal.DeleteCar(5);
Console.WriteLine("Car deleted.");
}
catch (Exception e)
{
Console.WriteLine($"An exception occured: {e.Message}");
}
dal.InsertAuto("Blue", 5, "TowMonster");
list = dal.GetAllInventory();
CarViewModel newCar = list.First(x => x.PetName == "TowMonster");
Console.WriteLine(" ************** New Car ************** ");
Console.WriteLine("CarId\tMake\tColor\tPet Name");
Console.WriteLine($"{newCar.Id}\t{newCar.Make}\t{newCar.Color}\t{newCar.PetName}");
dal.DeleteCar(newCar.Id);
string petName = dal.LookUpPetName(car.Id);
Console.WriteLine(" ************** New Car ************** ");
Console.WriteLine($"Car pet name: {petName}");
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
}
public static void FlagCustomer()
{
Console.WriteLine("***** Simple Transaction Example *****\n");
bool throwEx = true;
Console.Write("Do you want to throw an exception (Y or N): ");
var userAnswer = Console.ReadLine();
if (string.IsNullOrWhiteSpace(userAnswer) || userAnswer.Equals("N", StringComparison.OrdinalIgnoreCase))
{
throwEx = false;
}
var dal = new InventoryDal();
dal.ProcessCreditRisk(throwEx, 1);
Console.WriteLine("Check CreditRisk table for results");
Console.ReadLine();
}
public static void DoBulkCopy()
{
Console.WriteLine(" ************** Do Bulk Copy ************** ");
List<Car> cars = new()
{
new Car {Color = "Blue", MakeId = 1, PetName = "MyCar1"},
new Car {Color = "Red", MakeId = 2, PetName = "MyCar2"},
new Car {Color = "White", MakeId = 3, PetName = "MyCar3"},
new Car {Color = "Yellow", MakeId = 4, PetName = "MyCar4"}
};
ProcessBulkImport.ExecuteBulkImport(cars, "Inventory");
InventoryDal dal = new();
List<CarViewModel> list = dal.GetAllInventory();
Console.WriteLine(" ************** All Cars ************** ");
Console.WriteLine("CarId\tMake\tColor\tPet Name");
foreach (CarViewModel car in list)
{
Console.WriteLine($"{car.Id}\t{car.Make}\t{car.Color}\t{car.PetName}");
}
Console.WriteLine();
}
}
}
| 29.059829 | 115 | 0.583824 | [
"MIT"
] | rontucuman/auto-lot | src/AutoLot.DataReader/AutoLot.Client/Program.cs | 3,402 | C# |
namespace Microsoft.Marketplace.SaasKit.Models
{
using Microsoft.Marketplace.SaasKit.Models;
using Newtonsoft.Json;
using System;
/// <summary>
/// Subscription Usage Result
/// </summary>
/// <seealso cref="Microsoft.Marketplace.SaasKit.Models.SaaSApiResult" />
public class MeteringUsageResult : SaaSApiResult
{
/// <summary>
/// Gets or sets the status.
/// </summary>
/// <value>
/// The status.
/// </value>
[JsonProperty("status")]
public string Status { get; set; }
/// <summary>
/// Gets or sets the usage posted date.
/// </summary>
/// <value>
/// The usage posted date.
/// </value>
[JsonProperty("effectiveStartTime")]
public DateTime? UsagePostedDate { get; set; }
/// <summary>
/// Gets or sets the usage event identifier.
/// </summary>
/// <value>
/// The usage event identifier.
/// </value>
[JsonProperty("usageEventId")]
public Guid UsageEventId { get; set; }
/// <summary>
/// Gets or sets the message time.
/// </summary>
/// <value>
/// The message time.
/// </value>
[JsonProperty("messageTime")]
public DateTime MessageTime { get; set; }
/// <summary>
/// Gets or sets the resource identifier.
/// </summary>
/// <value>
/// The resource identifier.
/// </value>
[JsonProperty("resourceId")]
public Guid ResourceId { get; set; }
/// <summary>
/// Gets or sets the quantity.
/// </summary>
/// <value>
/// The quantity.
/// </value>
[JsonProperty("quantity")]
public long Quantity { get; set; }
/// <summary>
/// Gets or sets the dimension.
/// </summary>
/// <value>
/// The dimension.
/// </value>
[JsonProperty("dimension")]
public string Dimension { get; set; }
/// <summary>
/// Gets or sets the plan identifier.
/// </summary>
/// <value>
/// The plan identifier.
/// </value>
[JsonProperty("planId")]
public string PlanId { get; set; }
}
}
| 27.104651 | 77 | 0.499356 | [
"MIT"
] | santhoshbomma9/Microsoft-commercial-marketplace-transactable-SaaS-offer-SDK | src/SaaS.SDK.Client/Models/MeteringUsageResult.cs | 2,333 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Persistence.Contexts;
#nullable disable
namespace Persistence.Migrations
{
[DbContext(typeof(BaseDbContext))]
[Migration("20220208090711_Rental-Seed")]
partial class RentalSeed
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);
modelBuilder.Entity("Domain.Entities.Brand", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("Name");
b.HasKey("Id");
b.ToTable("Brands", (string)null);
b.HasData(
new
{
Id = 1,
Name = "BMW"
},
new
{
Id = 2,
Name = "Mercedes"
});
});
modelBuilder.Entity("Domain.Entities.Car", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<int>("CarState")
.HasColumnType("int")
.HasColumnName("State");
b.Property<int>("ColorId")
.HasColumnType("int")
.HasColumnName("ColorId");
b.Property<int>("Kilometer")
.HasColumnType("int")
.HasColumnName("Kilometer");
b.Property<short>("MinFindeksCreditRate")
.HasColumnType("smallint");
b.Property<int>("ModelId")
.HasColumnType("int")
.HasColumnName("ModelId");
b.Property<short>("ModelYear")
.HasColumnType("smallint")
.HasColumnName("ModelYear");
b.Property<string>("Plate")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("Plate");
b.Property<int>("RentalBranchId")
.HasColumnType("int")
.HasColumnName("RentalBranchId");
b.HasKey("Id");
b.HasIndex("ColorId");
b.HasIndex("ModelId");
b.HasIndex("RentalBranchId");
b.ToTable("Cars", (string)null);
b.HasData(
new
{
Id = 1,
CarState = 1,
ColorId = 1,
Kilometer = 1000,
MinFindeksCreditRate = (short)500,
ModelId = 1,
ModelYear = (short)2018,
Plate = "07ABC07",
RentalBranchId = 1
},
new
{
Id = 2,
CarState = 2,
ColorId = 2,
Kilometer = 1000,
MinFindeksCreditRate = (short)1100,
ModelId = 2,
ModelYear = (short)2018,
Plate = "15ABC15",
RentalBranchId = 2
});
});
modelBuilder.Entity("Domain.Entities.Color", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("Name");
b.HasKey("Id");
b.ToTable("Colors", (string)null);
b.HasData(
new
{
Id = 1,
Name = "Red"
},
new
{
Id = 2,
Name = "Blue"
});
});
modelBuilder.Entity("Domain.Entities.CorporateCustomer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<string>("CompanyName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("CompanyName");
b.Property<int>("CustomerId")
.HasColumnType("int")
.HasColumnName("CustomerId");
b.Property<string>("TaxNo")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("TaxNo");
b.HasKey("Id");
b.HasIndex("CustomerId")
.IsUnique();
b.ToTable("CorporateCustomers", (string)null);
b.HasData(
new
{
Id = 1,
CompanyName = "Ahmet Çetinkaya",
CustomerId = 2,
TaxNo = "54154512"
});
});
modelBuilder.Entity("Domain.Entities.Customer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("Email");
b.HasKey("Id");
b.ToTable("Customers", (string)null);
b.HasData(
new
{
Id = 1,
Email = "ahmetcetinkaya7@outlook.com"
},
new
{
Id = 2,
Email = "ahmet@cetinkaya.com"
});
});
modelBuilder.Entity("Domain.Entities.FindeksCreditRate", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<int>("CustomerId")
.HasColumnType("int")
.HasColumnName("CustomerId");
b.Property<short>("Score")
.HasColumnType("smallint")
.HasColumnName("Score");
b.HasKey("Id");
b.HasIndex("CustomerId")
.IsUnique();
b.ToTable("FindeksCreditRates", (string)null);
b.HasData(
new
{
Id = 1,
CustomerId = 1,
Score = (short)1000
},
new
{
Id = 2,
CustomerId = 2,
Score = (short)1900
});
});
modelBuilder.Entity("Domain.Entities.Fuel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("Name");
b.HasKey("Id");
b.ToTable("Fuels", (string)null);
b.HasData(
new
{
Id = 1,
Name = "Diesel"
},
new
{
Id = 2,
Name = "Electric"
});
});
modelBuilder.Entity("Domain.Entities.IndividualCustomer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<int>("CustomerId")
.HasColumnType("int")
.HasColumnName("CustomerId");
b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("FirstName");
b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("LastName");
b.Property<string>("NationalIdentity")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("NationalIdentity");
b.HasKey("Id");
b.HasIndex("CustomerId")
.IsUnique();
b.ToTable("IndividualCustomers", (string)null);
b.HasData(
new
{
Id = 1,
CustomerId = 1,
FirstName = "Ahmet",
LastName = "Çetinkaya",
NationalIdentity = "123123123123"
});
});
modelBuilder.Entity("Domain.Entities.Invoice", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<DateTime>("CreatedDate")
.HasColumnType("datetime2")
.HasColumnName("CreatedDate");
b.Property<int>("CustomerId")
.HasColumnType("int")
.HasColumnName("CustomerId");
b.Property<string>("No")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("No");
b.Property<DateTime>("RentalEndDate")
.HasColumnType("datetime2")
.HasColumnName("RentalEndDate");
b.Property<decimal>("RentalPrice")
.HasColumnType("decimal(18,2)")
.HasColumnName("RentalPrice");
b.Property<DateTime>("RentalStartDate")
.HasColumnType("datetime2")
.HasColumnName("RentalStartDate");
b.Property<short>("TotalRentalDate")
.HasColumnType("smallint")
.HasColumnName("TotalRentalDate");
b.HasKey("Id");
b.HasIndex("CustomerId");
b.ToTable("Invoices", (string)null);
b.HasData(
new
{
Id = 1,
CreatedDate = new DateTime(2022, 2, 8, 0, 0, 0, 0, DateTimeKind.Local),
CustomerId = 1,
No = "123123",
RentalEndDate = new DateTime(2022, 2, 10, 0, 0, 0, 0, DateTimeKind.Local),
RentalPrice = 1000m,
RentalStartDate = new DateTime(2022, 2, 8, 0, 0, 0, 0, DateTimeKind.Local),
TotalRentalDate = (short)2
},
new
{
Id = 2,
CreatedDate = new DateTime(2022, 2, 8, 0, 0, 0, 0, DateTimeKind.Local),
CustomerId = 1,
No = "123123",
RentalEndDate = new DateTime(2022, 2, 10, 0, 0, 0, 0, DateTimeKind.Local),
RentalPrice = 2000m,
RentalStartDate = new DateTime(2022, 2, 8, 0, 0, 0, 0, DateTimeKind.Local),
TotalRentalDate = (short)2
});
});
modelBuilder.Entity("Domain.Entities.Model", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<int>("BrandId")
.HasColumnType("int")
.HasColumnName("BrandId");
b.Property<decimal>("DailyPrice")
.HasColumnType("decimal(18,2)")
.HasColumnName("DailyPrice");
b.Property<int>("FuelId")
.HasColumnType("int")
.HasColumnName("FuelId");
b.Property<string>("ImageUrl")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("ImageUrl");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("Name");
b.Property<int>("TransmissionId")
.HasColumnType("int")
.HasColumnName("TransmissionId");
b.HasKey("Id");
b.HasIndex("BrandId");
b.HasIndex("FuelId");
b.HasIndex("TransmissionId");
b.ToTable("Models", (string)null);
b.HasData(
new
{
Id = 1,
BrandId = 1,
DailyPrice = 1000m,
FuelId = 1,
ImageUrl = "",
Name = "418i",
TransmissionId = 2
},
new
{
Id = 2,
BrandId = 2,
DailyPrice = 600m,
FuelId = 2,
ImageUrl = "",
Name = "CLA 180D",
TransmissionId = 1
});
});
modelBuilder.Entity("Domain.Entities.Rental", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<int>("CarId")
.HasColumnType("int")
.HasColumnName("CarId");
b.Property<int>("CustomerId")
.HasColumnType("int")
.HasColumnName("CustomerId");
b.Property<DateTime>("RentEndDate")
.HasColumnType("datetime2")
.HasColumnName("RentEndDate");
b.Property<int>("RentEndKilometer")
.HasColumnType("int")
.HasColumnName("RentEndKilometer");
b.Property<int>("RentEndRentalBranchId")
.HasColumnType("int")
.HasColumnName("RentEndRentalBranchId");
b.Property<DateTime>("RentStartDate")
.HasColumnType("datetime2")
.HasColumnName("RentStartDate");
b.Property<int>("RentStartKilometer")
.HasColumnType("int")
.HasColumnName("RentStartKilometer");
b.Property<int>("RentStartRentalBranchId")
.HasColumnType("int")
.HasColumnName("RentStartRentalBranchId");
b.Property<DateTime?>("ReturnDate")
.HasColumnType("datetime2")
.HasColumnName("ReturnDate");
b.HasKey("Id");
b.HasIndex("CarId");
b.HasIndex("CustomerId");
b.HasIndex("RentEndRentalBranchId");
b.HasIndex("RentStartRentalBranchId");
b.ToTable("Rentals", (string)null);
b.HasData(
new
{
Id = 1,
CarId = 2,
CustomerId = 1,
RentEndDate = new DateTime(2022, 2, 10, 0, 0, 0, 0, DateTimeKind.Local),
RentEndKilometer = 1200,
RentEndRentalBranchId = 2,
RentStartDate = new DateTime(2022, 2, 8, 0, 0, 0, 0, DateTimeKind.Local),
RentStartKilometer = 1000,
RentStartRentalBranchId = 1
},
new
{
Id = 2,
CarId = 1,
CustomerId = 2,
RentEndDate = new DateTime(2022, 2, 10, 0, 0, 0, 0, DateTimeKind.Local),
RentEndKilometer = 1200,
RentEndRentalBranchId = 1,
RentStartDate = new DateTime(2022, 2, 8, 0, 0, 0, 0, DateTimeKind.Local),
RentStartKilometer = 1000,
RentStartRentalBranchId = 2
});
});
modelBuilder.Entity("Domain.Entities.RentalBranch", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<int>("City")
.HasColumnType("int")
.HasColumnName("City");
b.HasKey("Id");
b.ToTable("RentalBranches", (string)null);
b.HasData(
new
{
Id = 1,
City = 1
},
new
{
Id = 2,
City = 7
});
});
modelBuilder.Entity("Domain.Entities.Transmission", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasColumnName("Id");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)")
.HasColumnName("Name");
b.HasKey("Id");
b.ToTable("Transmissions", (string)null);
b.HasData(
new
{
Id = 1,
Name = "Manuel"
},
new
{
Id = 2,
Name = "Automatic"
});
});
modelBuilder.Entity("Domain.Entities.Car", b =>
{
b.HasOne("Domain.Entities.Color", "Color")
.WithMany("Cars")
.HasForeignKey("ColorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.Entities.Model", "Model")
.WithMany("Cars")
.HasForeignKey("ModelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.Entities.RentalBranch", "RentalBranch")
.WithMany("Cars")
.HasForeignKey("RentalBranchId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Color");
b.Navigation("Model");
b.Navigation("RentalBranch");
});
modelBuilder.Entity("Domain.Entities.CorporateCustomer", b =>
{
b.HasOne("Domain.Entities.Customer", "Customer")
.WithOne("CorporateCustomer")
.HasForeignKey("Domain.Entities.CorporateCustomer", "CustomerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Customer");
});
modelBuilder.Entity("Domain.Entities.FindeksCreditRate", b =>
{
b.HasOne("Domain.Entities.Customer", "Customer")
.WithOne("FindeksCreditRate")
.HasForeignKey("Domain.Entities.FindeksCreditRate", "CustomerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Customer");
});
modelBuilder.Entity("Domain.Entities.IndividualCustomer", b =>
{
b.HasOne("Domain.Entities.Customer", "Customer")
.WithOne("IndividualCustomer")
.HasForeignKey("Domain.Entities.IndividualCustomer", "CustomerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Customer");
});
modelBuilder.Entity("Domain.Entities.Invoice", b =>
{
b.HasOne("Domain.Entities.Customer", "Customer")
.WithMany("Invoices")
.HasForeignKey("CustomerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Customer");
});
modelBuilder.Entity("Domain.Entities.Model", b =>
{
b.HasOne("Domain.Entities.Brand", "Brand")
.WithMany("Models")
.HasForeignKey("BrandId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.Entities.Fuel", "Fuel")
.WithMany("Models")
.HasForeignKey("FuelId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.Entities.Transmission", "Transmission")
.WithMany("Models")
.HasForeignKey("TransmissionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Brand");
b.Navigation("Fuel");
b.Navigation("Transmission");
});
modelBuilder.Entity("Domain.Entities.Rental", b =>
{
b.HasOne("Domain.Entities.Car", "Car")
.WithMany()
.HasForeignKey("CarId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.Entities.Customer", "Customer")
.WithMany("Rentals")
.HasForeignKey("CustomerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.Entities.RentalBranch", "RentEndRentalBranch")
.WithMany()
.HasForeignKey("RentEndRentalBranchId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.Entities.RentalBranch", "RentStartRentalBranch")
.WithMany()
.HasForeignKey("RentStartRentalBranchId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Car");
b.Navigation("Customer");
b.Navigation("RentEndRentalBranch");
b.Navigation("RentStartRentalBranch");
});
modelBuilder.Entity("Domain.Entities.Brand", b =>
{
b.Navigation("Models");
});
modelBuilder.Entity("Domain.Entities.Color", b =>
{
b.Navigation("Cars");
});
modelBuilder.Entity("Domain.Entities.Customer", b =>
{
b.Navigation("CorporateCustomer")
.IsRequired();
b.Navigation("FindeksCreditRate")
.IsRequired();
b.Navigation("IndividualCustomer")
.IsRequired();
b.Navigation("Invoices");
b.Navigation("Rentals");
});
modelBuilder.Entity("Domain.Entities.Fuel", b =>
{
b.Navigation("Models");
});
modelBuilder.Entity("Domain.Entities.Model", b =>
{
b.Navigation("Cars");
});
modelBuilder.Entity("Domain.Entities.RentalBranch", b =>
{
b.Navigation("Cars");
});
modelBuilder.Entity("Domain.Entities.Transmission", b =>
{
b.Navigation("Models");
});
#pragma warning restore 612, 618
}
}
}
| 36.427873 | 103 | 0.381771 | [
"MIT"
] | ahmet-cetinkaya/rentacar-project-backend-dotnet | src/rentACar/Persistence/Migrations/20220208090711_Rental-Seed.Designer.cs | 29,802 | C# |
/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml - All Rights Reserved
*
* This source is subject to the Microsoft Permissive License.
* Please see the License.txt file for more information.
* All other rights reserved.
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*/
using System;
using DocumentFormat.OpenXml.Packaging;
namespace HtmlToOpenXml
{
/// <summary>
/// Represents an image and its metadata.
/// </summary>
sealed class HtmlImageInfo
{
/// <summary>
/// Gets or sets the size of the image
/// </summary>
public Size Size { get; set; }
/// <summary>
/// Gets or sets the binary data of the image could read.
/// </summary>
public byte[] RawData { get; set; }
/// <summary>
/// Gets or sets the format of the image.
/// </summary>
public ImagePartType? Type { get; set; }
}
} | 28.972973 | 93 | 0.666978 | [
"MIT"
] | dimarobert/html2openxml | src/Html2OpenXml/Primitives/HtmlImageInfo.cs | 1,074 | C# |
//
// Copyright (c) 2002-2016 Mirko Matytschak
// (www.netdataobjects.de)
//
// Author: Mirko Matytschak
//
// 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;
using System.Text;
using System.Collections.Generic;
namespace CodeGenerator
{
/// <summary>
/// Zusammenfassung f�r Property.
/// </summary>
public class Property : ITextProvider
{
string typeName;
string name;
bool hasSetter;
bool hasGetter;
string varName;
public Property(string typeName, string varName, bool hasSetter, bool hasGetter)
{
this.typeName = typeName;
this.varName = varName;
this.hasGetter = hasGetter;
this.hasSetter = hasSetter;
if (char.IsUpper(varName[0]))
throw new ArgumentException("varName shouldn't start with upper case letter", "varName");
this.name = varName.Substring(0, 1).ToUpper() + varName.Substring(1);
}
public Property(string typeName, string name, string varName, bool hasSetter, bool hasGetter)
{
this.typeName = typeName;
this.name = name;
this.hasGetter = hasGetter;
this.hasSetter = hasSetter;
this.varName = varName;
}
public List<string> Text
{
get
{
List<string> result = new List<string>();
StringBuilder sb = new StringBuilder();
sb.Append("public ");
sb.Append(typeName);
sb.Append(' ');
sb.Append(name);
result.Add(sb.ToString());
result.Add("{");
if (hasGetter)
{
sb.Length = 0;
sb.Append("\tget { return ");
sb.Append(varName);
sb.Append("; }");
result.Add(sb.ToString());
}
if (hasSetter)
{
sb.Length = 0;
sb.Append("\tset { ");
sb.Append(varName);
sb.Append(" = value; }");
result.Add(sb.ToString());
}
result.Add("}");
return result;
}
}
}
}
| 30.734043 | 116 | 0.662859 | [
"MIT"
] | mirkomaty/NDO | UnitTestGenerator/CodeGenerator/Property.cs | 2,894 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, 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 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.460)
// Version 5.460.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.ComponentModel;
using System.Diagnostics;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Overrides for defining button specifications.
/// </summary>
public class KryptonPaletteButtonSpecs : Storage
{
#region Instance Fields
#endregion
#region Events
/// <summary>
/// Occurs when a button spec change occurs.
/// </summary>
public event EventHandler ButtonSpecChanged;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the KryptonPaletteButtonSpecs class.
/// </summary>
/// <param name="redirector">Palette redirector for sourcing inherited values.</param>
internal KryptonPaletteButtonSpecs(PaletteRedirect redirector)
{
Debug.Assert(redirector != null);
// Create exposed button specifications
Common = new KryptonPaletteButtonSpecTyped(redirector);
Generic = new KryptonPaletteButtonSpecTyped(redirector);
Close = new KryptonPaletteButtonSpecTyped(redirector);
Context = new KryptonPaletteButtonSpecTyped(redirector);
Next = new KryptonPaletteButtonSpecTyped(redirector);
Previous = new KryptonPaletteButtonSpecTyped(redirector);
ArrowLeft = new KryptonPaletteButtonSpecTyped(redirector);
ArrowRight = new KryptonPaletteButtonSpecTyped(redirector);
ArrowUp = new KryptonPaletteButtonSpecTyped(redirector);
ArrowDown = new KryptonPaletteButtonSpecTyped(redirector);
DropDown = new KryptonPaletteButtonSpecTyped(redirector);
PinVertical = new KryptonPaletteButtonSpecTyped(redirector);
PinHorizontal = new KryptonPaletteButtonSpecTyped(redirector);
FormClose = new KryptonPaletteButtonSpecTyped(redirector);
FormMax = new KryptonPaletteButtonSpecTyped(redirector);
FormMin = new KryptonPaletteButtonSpecTyped(redirector);
FormRestore = new KryptonPaletteButtonSpecTyped(redirector);
PendantClose = new KryptonPaletteButtonSpecTyped(redirector);
PendantMin = new KryptonPaletteButtonSpecTyped(redirector);
PendantRestore = new KryptonPaletteButtonSpecTyped(redirector);
WorkspaceMaximize = new KryptonPaletteButtonSpecTyped(redirector);
WorkspaceRestore = new KryptonPaletteButtonSpecTyped(redirector);
RibbonMinimize = new KryptonPaletteButtonSpecTyped(redirector);
RibbonExpand = new KryptonPaletteButtonSpecTyped(redirector);
// Create redirector for inheriting from style specific to style common
PaletteRedirectButtonSpec redirectCommon = new PaletteRedirectButtonSpec(redirector, Common);
// Inform the button spec to use the new redirector
Generic.SetRedirector(redirectCommon);
Close.SetRedirector(redirectCommon);
Context.SetRedirector(redirectCommon);
Next.SetRedirector(redirectCommon);
Previous.SetRedirector(redirectCommon);
ArrowLeft.SetRedirector(redirectCommon);
ArrowRight.SetRedirector(redirectCommon);
ArrowUp.SetRedirector(redirectCommon);
ArrowDown.SetRedirector(redirectCommon);
DropDown.SetRedirector(redirectCommon);
PinVertical.SetRedirector(redirectCommon);
PinHorizontal.SetRedirector(redirectCommon);
FormClose.SetRedirector(redirectCommon);
FormMax.SetRedirector(redirectCommon);
FormMin.SetRedirector(redirectCommon);
FormRestore.SetRedirector(redirectCommon);
PendantClose.SetRedirector(redirectCommon);
PendantMin.SetRedirector(redirectCommon);
PendantRestore.SetRedirector(redirectCommon);
WorkspaceMaximize.SetRedirector(redirectCommon);
WorkspaceRestore.SetRedirector(redirectCommon);
RibbonMinimize.SetRedirector(redirectCommon);
RibbonExpand.SetRedirector(redirectCommon);
// Hook into the storage change events
Common.ButtonSpecChanged += OnButtonSpecChanged;
Generic.ButtonSpecChanged += OnButtonSpecChanged;
Close.ButtonSpecChanged += OnButtonSpecChanged;
Context.ButtonSpecChanged += OnButtonSpecChanged;
Next.ButtonSpecChanged += OnButtonSpecChanged;
Previous.ButtonSpecChanged += OnButtonSpecChanged;
ArrowLeft.ButtonSpecChanged += OnButtonSpecChanged;
ArrowRight.ButtonSpecChanged += OnButtonSpecChanged;
ArrowUp.ButtonSpecChanged += OnButtonSpecChanged;
ArrowDown.ButtonSpecChanged += OnButtonSpecChanged;
DropDown.ButtonSpecChanged += OnButtonSpecChanged;
PinVertical.ButtonSpecChanged += OnButtonSpecChanged;
PinHorizontal.ButtonSpecChanged += OnButtonSpecChanged;
FormClose.ButtonSpecChanged += OnButtonSpecChanged;
FormMax.ButtonSpecChanged += OnButtonSpecChanged;
FormMin.ButtonSpecChanged += OnButtonSpecChanged;
FormRestore.ButtonSpecChanged += OnButtonSpecChanged;
PendantClose.ButtonSpecChanged += OnButtonSpecChanged;
PendantMin.ButtonSpecChanged += OnButtonSpecChanged;
PendantRestore.ButtonSpecChanged += OnButtonSpecChanged;
WorkspaceMaximize.ButtonSpecChanged += OnButtonSpecChanged;
WorkspaceRestore.ButtonSpecChanged += OnButtonSpecChanged;
RibbonMinimize.ButtonSpecChanged += OnButtonSpecChanged;
RibbonExpand.ButtonSpecChanged += OnButtonSpecChanged;
}
#endregion
#region IsDefault
/// <summary>
/// Gets a value indicating if all values are default.
/// </summary>
public override bool IsDefault => Common.IsDefault &&
Generic.IsDefault &&
Close.IsDefault &&
Context.IsDefault &&
Next.IsDefault &&
Previous.IsDefault &&
ArrowLeft.IsDefault &&
ArrowRight.IsDefault &&
ArrowUp.IsDefault &&
ArrowDown.IsDefault &&
DropDown.IsDefault &&
PinVertical.IsDefault &&
PinHorizontal.IsDefault &&
FormClose.IsDefault &&
FormMax.IsDefault &&
FormMin.IsDefault &&
FormRestore.IsDefault &&
PendantClose.IsDefault &&
PendantMin.IsDefault &&
PendantRestore.IsDefault &&
WorkspaceMaximize.IsDefault &&
WorkspaceRestore.IsDefault &&
RibbonMinimize.IsDefault &&
RibbonExpand.IsDefault;
#endregion
#region PopulateFromBase
/// <summary>
/// Populate values from the base palette.
/// </summary>
public void PopulateFromBase()
{
// Populate only the designated styles
Generic.PopulateFromBase(PaletteButtonSpecStyle.Generic);
Close.PopulateFromBase(PaletteButtonSpecStyle.Close);
Context.PopulateFromBase(PaletteButtonSpecStyle.Context);
Next.PopulateFromBase(PaletteButtonSpecStyle.Next);
Previous.PopulateFromBase(PaletteButtonSpecStyle.Previous);
ArrowLeft.PopulateFromBase(PaletteButtonSpecStyle.ArrowLeft);
ArrowRight.PopulateFromBase(PaletteButtonSpecStyle.ArrowRight);
ArrowUp.PopulateFromBase(PaletteButtonSpecStyle.ArrowUp);
ArrowDown.PopulateFromBase(PaletteButtonSpecStyle.ArrowDown);
DropDown.PopulateFromBase(PaletteButtonSpecStyle.DropDown);
PinVertical.PopulateFromBase(PaletteButtonSpecStyle.PinVertical);
PinHorizontal.PopulateFromBase(PaletteButtonSpecStyle.PinHorizontal);
FormClose.PopulateFromBase(PaletteButtonSpecStyle.FormClose);
FormMax.PopulateFromBase(PaletteButtonSpecStyle.FormMax);
FormMin.PopulateFromBase(PaletteButtonSpecStyle.FormMin);
FormRestore.PopulateFromBase(PaletteButtonSpecStyle.FormRestore);
PendantClose.PopulateFromBase(PaletteButtonSpecStyle.PendantClose);
PendantRestore.PopulateFromBase(PaletteButtonSpecStyle.PendantRestore);
PendantMin.PopulateFromBase(PaletteButtonSpecStyle.PendantMin);
PendantRestore.PopulateFromBase(PaletteButtonSpecStyle.PendantRestore);
WorkspaceMaximize.PopulateFromBase(PaletteButtonSpecStyle.WorkspaceMaximize);
WorkspaceRestore.PopulateFromBase(PaletteButtonSpecStyle.WorkspaceRestore);
RibbonMinimize.PopulateFromBase(PaletteButtonSpecStyle.RibbonMinimize);
RibbonExpand.PopulateFromBase(PaletteButtonSpecStyle.RibbonExpand);
}
#endregion
#region Common
/// <summary>
/// Gets access to the common button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining common button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped Common { get; }
private bool ShouldSerializeCommon()
{
return !Common.IsDefault;
}
#endregion
#region Generic
/// <summary>
/// Gets access to the generic button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining generic button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped Generic { get; }
private bool ShouldSerializeGeneric()
{
return !Generic.IsDefault;
}
#endregion
#region Close
/// <summary>
/// Gets access to the close button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining close button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped Close { get; }
private bool ShouldSerializeClose()
{
return !Close.IsDefault;
}
#endregion
#region Context
/// <summary>
/// Gets access to the context button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining context button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped Context { get; }
private bool ShouldSerializeContext()
{
return !Context.IsDefault;
}
#endregion
#region Next
/// <summary>
/// Gets access to the next button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining next button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped Next { get; }
private bool ShouldSerializeNext()
{
return !Next.IsDefault;
}
#endregion
#region Previous
/// <summary>
/// Gets access to the previous button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining previous button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped Previous { get; }
private bool ShouldSerializePrevious()
{
return !Previous.IsDefault;
}
#endregion
#region ArrowLeft
/// <summary>
/// Gets access to the left arrow button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining left arrow button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped ArrowLeft { get; }
private bool ShouldSerializeArrowLeft()
{
return !ArrowLeft.IsDefault;
}
#endregion
#region ArrowRight
/// <summary>
/// Gets access to the right arrow button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining right arrow button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped ArrowRight { get; }
private bool ShouldSerializeArrowRight()
{
return !ArrowRight.IsDefault;
}
#endregion
#region ArrowUp
/// <summary>
/// Gets access to the right up button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining up arrow button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped ArrowUp { get; }
private bool ShouldSerializeArrowUp()
{
return !ArrowUp.IsDefault;
}
#endregion
#region ArrowDown
/// <summary>
/// Gets access to the right up button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining up arrow button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped ArrowDown { get; }
private bool ShouldSerializeArrowDown()
{
return !ArrowDown.IsDefault;
}
#endregion
#region DropDown
/// <summary>
/// Gets access to the drop down button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining drop down button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped DropDown { get; }
private bool ShouldSerializeDropDown()
{
return !DropDown.IsDefault;
}
#endregion
#region PinVertical
/// <summary>
/// Gets access to the pin vertical button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining pin vertical button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped PinVertical { get; }
private bool ShouldSerializePinVertical()
{
return !PinVertical.IsDefault;
}
#endregion
#region PinHorizontal
/// <summary>
/// Gets access to the pin horizontal button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining pin horizontal button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped PinHorizontal { get; }
private bool ShouldSerializePinHorizontal()
{
return !PinHorizontal.IsDefault;
}
#endregion
#region FormClose
/// <summary>
/// Gets access to the form close button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining form close button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped FormClose { get; }
private bool ShouldSerializeFormClose()
{
return !FormClose.IsDefault;
}
#endregion
#region FormMin
/// <summary>
/// Gets access to the form minimize button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining form minimize button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped FormMin { get; }
private bool ShouldSerializeFormMin()
{
return !FormMin.IsDefault;
}
#endregion
#region FormMax
/// <summary>
/// Gets access to the form maximize button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining form maximize button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped FormMax { get; }
private bool ShouldSerializeFormMax()
{
return !FormMax.IsDefault;
}
#endregion
#region FormRestore
/// <summary>
/// Gets access to the form restore button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining form restore button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped FormRestore { get; }
private bool ShouldSerializeFormRestore()
{
return !FormRestore.IsDefault;
}
#endregion
#region PendantClose
/// <summary>
/// Gets access to the pendant close button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining pendant close button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped PendantClose { get; }
private bool ShouldSerializePendantClose()
{
return !PendantClose.IsDefault;
}
#endregion
#region PendantMin
/// <summary>
/// Gets access to the pendant minimize button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining pendant minimize button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped PendantMin { get; }
private bool ShouldSerializePendantMin()
{
return !PendantMin.IsDefault;
}
#endregion
#region PendantRestore
/// <summary>
/// Gets access to the pendant restore button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining pendant restore button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped PendantRestore { get; }
private bool ShouldSerializePendantRestore()
{
return !PendantRestore.IsDefault;
}
#endregion
#region WorkspaceMaximize
/// <summary>
/// Gets access to the workspace maximize button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining workspace maximize button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped WorkspaceMaximize { get; }
private bool ShouldSerializeWorkspaceMaximize()
{
return !WorkspaceMaximize.IsDefault;
}
#endregion
#region WorkspaceRestore
/// <summary>
/// Gets access to the workspace restore button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining workspace restore button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped WorkspaceRestore { get; }
private bool ShouldSerializeWorkspaceRestore()
{
return !WorkspaceRestore.IsDefault;
}
#endregion
#region RibbonMinimize
/// <summary>
/// Gets access to the ribbon minimize button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining ribbon minimize button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped RibbonMinimize { get; }
private bool ShouldSerializeRibbonMinimize()
{
return !RibbonMinimize.IsDefault;
}
#endregion
#region RibbonExpand
/// <summary>
/// Gets access to the ribbon expand button specification.
/// </summary>
[KryptonPersist]
[Category("Visuals")]
[Description("Overrides for defining ribbon expand button specifications.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public KryptonPaletteButtonSpecTyped RibbonExpand { get; }
private bool ShouldSerializeRibbonExpand()
{
return !RibbonExpand.IsDefault;
}
#endregion
#region OnButtonSpecChanged
/// <summary>
/// Raises the ButtonSpecChanged event.
/// </summary>
/// <param name="sender">Source of the event.</param>
/// <param name="e">An EventArgs containing event data.</param>
protected virtual void OnButtonSpecChanged(object sender, EventArgs e)
{
ButtonSpecChanged?.Invoke(this, e);
}
#endregion
}
}
| 41.040886 | 157 | 0.6309 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.460 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Component/KryptonPaletteButtonSpecs.cs | 24,094 | C# |
using Newtonsoft.Json;
namespace Nop.Plugin.Api.DTOs.SpecificationAttributes
{
public class SpecificationAttributesCountRootObject
{
[JsonProperty("count")]
public int Count { get; set; }
}
} | 22.1 | 55 | 0.692308 | [
"MIT"
] | ApertureLabsInc/api-plugin-for-nopcommerce | Nop.Plugin.Api/DTOs/SpecificationAttributes/SpecificationAttributesCountRootObject.cs | 223 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20190401.Inputs
{
/// <summary>
/// VpnConnection Resource.
/// </summary>
public sealed class VpnConnectionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Expected bandwidth in MBPS.
/// </summary>
[Input("connectionBandwidth")]
public Input<int>? ConnectionBandwidth { get; set; }
/// <summary>
/// EnableBgp flag.
/// </summary>
[Input("enableBgp")]
public Input<bool>? EnableBgp { get; set; }
/// <summary>
/// Enable internet security.
/// </summary>
[Input("enableInternetSecurity")]
public Input<bool>? EnableInternetSecurity { get; set; }
/// <summary>
/// EnableBgp flag.
/// </summary>
[Input("enableRateLimiting")]
public Input<bool>? EnableRateLimiting { get; set; }
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
[Input("ipsecPolicies")]
private InputList<Inputs.IpsecPolicyArgs>? _ipsecPolicies;
/// <summary>
/// The IPSec Policies to be considered by this connection.
/// </summary>
public InputList<Inputs.IpsecPolicyArgs> IpsecPolicies
{
get => _ipsecPolicies ?? (_ipsecPolicies = new InputList<Inputs.IpsecPolicyArgs>());
set => _ipsecPolicies = value;
}
/// <summary>
/// The name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Id of the connected vpn site.
/// </summary>
[Input("remoteVpnSite")]
public Input<Inputs.SubResourceArgs>? RemoteVpnSite { get; set; }
/// <summary>
/// Routing weight for vpn connection.
/// </summary>
[Input("routingWeight")]
public Input<int>? RoutingWeight { get; set; }
/// <summary>
/// SharedKey for the vpn connection.
/// </summary>
[Input("sharedKey")]
public Input<string>? SharedKey { get; set; }
/// <summary>
/// Use local azure ip to initiate connection.
/// </summary>
[Input("useLocalAzureIpAddress")]
public Input<bool>? UseLocalAzureIpAddress { get; set; }
/// <summary>
/// Enable policy-based traffic selectors.
/// </summary>
[Input("usePolicyBasedTrafficSelectors")]
public Input<bool>? UsePolicyBasedTrafficSelectors { get; set; }
/// <summary>
/// Connection protocol used for this connection.
/// </summary>
[Input("vpnConnectionProtocolType")]
public InputUnion<string, Pulumi.AzureNextGen.Network.V20190401.VirtualNetworkGatewayConnectionProtocol>? VpnConnectionProtocolType { get; set; }
public VpnConnectionArgs()
{
}
}
}
| 31.457944 | 153 | 0.581402 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20190401/Inputs/VpnConnectionArgs.cs | 3,366 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace MediaBazar
{
public partial class HiringRequest : Form
{
public HiringRequest(string username, string firstName, string lastName, decimal hourlyWage, int departmentId, DateTime contractStartDate, long phoneNumber, string email)
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.Enabled = false;
tbUsername.Text = username;
tbFirstName.Text = firstName;
tbLastName.Text = lastName;
nHourlyWage.Value = hourlyWage;
dtbContractStartDate.Value = contractStartDate;
tbPhoneNumber.Text = phoneNumber.ToString();
tbEmail.Text = email;
List<Department> departments = Department.GetAllDepartments();
foreach (Department d in departments)
{
if (d.DepartmentId == departmentId) cmbDepartment.Text = d.Name;
};
}
}
}
| 32.75 | 178 | 0.631679 | [
"MIT"
] | karinakozarova/MediaBazaar | WindowsFormsApp1/MediaBazar/HiringRequest.cs | 1,050 | C# |
using System;
namespace WechatMall.WX
{
public class Class1
{
}
}
| 8.888889 | 23 | 0.6125 | [
"MIT"
] | jancy-xu99/HZY.AdminRazor-master | WechatMall.WX/Class1.cs | 82 | 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.
// Source: https://github.com/windows-toolkit/WindowsCommunityToolkit/tree/master/Microsoft.Toolkit.Uwp.UI.Controls/MarkdownTextBlock/Render
namespace Notepads.Controls.Markdown
{
using Windows.UI.Xaml.Documents;
/// <summary>
/// The Context of the Current Document Rendering.
/// </summary>
public class InlineRenderContext : RenderContext
{
internal InlineRenderContext(InlineCollection inlineCollection, IRenderContext context)
{
InlineCollection = inlineCollection;
TrimLeadingWhitespace = context.TrimLeadingWhitespace;
Parent = context.Parent;
if (context is RenderContext localcontext)
{
Foreground = localcontext.Foreground;
OverrideForeground = localcontext.OverrideForeground;
}
if (context is InlineRenderContext inlinecontext)
{
WithinBold = inlinecontext.WithinBold;
WithinItalics = inlinecontext.WithinItalics;
WithinHyperlink = inlinecontext.WithinHyperlink;
}
}
/// <summary>
/// Gets or sets a value indicating whether the Current Element is being rendered inside an Italics Run.
/// </summary>
public bool WithinItalics { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the Current Element is being rendered inside a Bold Run.
/// </summary>
public bool WithinBold { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the Current Element is being rendered inside a Link.
/// </summary>
public bool WithinHyperlink { get; set; }
/// <summary>
/// Gets or sets the list to add to.
/// </summary>
public InlineCollection InlineCollection { get; set; }
}
} | 39 | 141 | 0.621445 | [
"MIT"
] | 2Bunzen2/Notepads | src/Notepads.Controls/MarkdownTextBlock/Markdown/Render/InlineRenderContext.cs | 2,091 | C# |
using System;
using System.Numerics;
using AltV.Net.Data;
using AltV.Net.Enums;
using AltV.Net.Shared.Elements.Entities;
namespace AltV.Net.Elements.Entities
{
public interface IVehicle : ISharedVehicle, IEntity
{
/// <summary>
/// Get the current driver of the
/// </summary>
/// <exception cref="EntityRemovedException">This entity was removed</exception>
IPlayer Driver { get; }
/// <summary>
/// Gets if the vehicle is destroyed.
/// </summary>
bool IsDestroyed { get; }
/// <summary>
/// Get or set mod kit of the
/// </summary>
/// <exception cref="EntityRemovedException">This entity was removed</exception>
byte ModKit { get; set; }
/// <summary>
/// The amount of Modkits
/// </summary>
byte ModKitsCount { get; }
/// <summary>
/// If the primary color is RGBA
/// </summary>
bool IsPrimaryColorRgb { get; }
/// <summary>
/// Get or set primary color of the
/// </summary>
/// <exception cref="EntityRemovedException">This entity was removed</exception>
byte PrimaryColor { get; set; }
/// <summary>
/// The primary color in RGBA
/// </summary>
Rgba PrimaryColorRgb { get; set; }
/// <summary>
/// If the secondary color is RGBA
/// </summary>
bool IsSecondaryColorRgb { get; }
/// <summary>
/// The secondary color
/// </summary>
byte SecondaryColor { get; set; }
/// <summary>
/// The secondary color in RGBA
/// </summary>
Rgba SecondaryColorRgb { get; set; }
/// <summary>
/// Pearl Color
/// </summary>
byte PearlColor { get; set; }
/// <summary>
/// Wheel Color
/// </summary>
byte WheelColor { get; set; }
/// <summary>
/// Interior Color
/// </summary>
byte InteriorColor { get; set; }
/// <summary>
/// Dashboard Color
/// </summary>
byte DashboardColor { get; set; }
/// <summary>
/// If the tyre smoke is RGBA
/// </summary>
bool IsTireSmokeColorCustom { get; }
/// <summary>
/// The RGBA of the tyre smoke
/// </summary>
Rgba TireSmokeColor { get; set; }
/// <summary>
/// The wheel type
/// </summary>
byte WheelType { get; }
/// <summary>
/// The wheel variation, for e.g. bikes only this getter works, RearWheel won't.
/// For most other vehicles this is the FrontWheel variation getter.
/// </summary>
byte WheelVariation { get; }
/// <summary>
/// Rear wheel variation.
/// </summary>
byte RearWheel { get; set; }
/// <summary>
/// Sets custom tires on the vehicle
/// </summary>
bool CustomTires { get; set; }
byte SpecialDarkness { get; set; }
/// <summary>
/// Get or set number plate index of the vehicle
/// </summary>
/// <exception cref="EntityRemovedException">This entity was removed</exception>
uint NumberplateIndex { get; set; }
/// <summary>
/// Get or set number plate text of the vehicle
/// </summary>
/// <exception cref="EntityRemovedException">This entity was removed</exception>
string NumberplateText { get; set; }
/// <summary>
/// The window tint level
/// </summary>
byte WindowTint { get; set; }
/// <summary>
/// The dirt level
/// </summary>
byte DirtLevel { get; set; }
/// <summary>
/// Neon Color in RGBA
/// </summary>
Rgba NeonColor { get; set; }
/// <summary>
/// The livery
/// </summary>
byte Livery { get; set; }
/// <summary>
/// The roof livery
/// </summary>
byte RoofLivery { get; set; }
string AppearanceData { get; set; }
/// <summary>
/// Gets the vehicle that is attached on this vehicle
/// </summary>
IVehicle Attached { get; }
/// <summary>
/// Gets the vehicle that this vehicle is attached to
/// </summary>
IVehicle AttachedTo { get; }
/// <summary>
/// Current mod in category
/// </summary>
/// <param name="category">Mod Category</param>
/// <returns>Current mod</returns>
byte GetMod(byte category);
/// <summary>
/// Mod count in Category
/// </summary>
/// <param name="category">Mod Category</param>
/// <returns>Mod count</returns>
byte GetModsCount(byte category);
/// <summary>
/// Set Mod
/// </summary>
/// <param name="category">The mod category (slot)</param>
/// <param name="id">The mod id</param>
/// <returns>True - Mod was set</returns>
bool SetMod(byte category, byte id);
/// <summary>
/// Sets the wheels type and variation
/// </summary>
/// <param name="type">Wheel Type</param>
/// <param name="variation">Wheel variation</param>
void SetWheels(byte type, byte variation);
/// <summary>
/// If the vehicle extra is on
/// </summary>
/// <param name="extraId"></param>
/// <returns></returns>
bool IsExtraOn(byte extraId);
/// <summary>
/// Toggles the vehicle extra
/// </summary>
/// <param name="extraId">Extra Id</param>
/// <param name="state">True - Enabled</param>
void ToggleExtra(byte extraId, bool state);
/// <summary>
/// Is the neon active - True = Active
/// </summary>
bool IsNeonActive { get; }
/// <summary>
/// Gets the neon active for each area
/// </summary>
/// <param name="left">Left Side</param>
/// <param name="right">Right Side</param>
/// <param name="top">Front Side</param>
/// <param name="back">Rear Side</param>
void GetNeonActive(ref bool left, ref bool right, ref bool top, ref bool back);
/// <summary>
/// Sets neon active by side
/// </summary>
/// <param name="left">Left side</param>
/// <param name="right">Right Side</param>
/// <param name="top">Top Side</param>
/// <param name="back">Back Side</param>
void SetNeonActive(bool left, bool right, bool top, bool back);
/// <summary>
/// Sets or Returns the status of the Engine
/// </summary>
bool EngineOn { get; set; }
/// <summary>
/// Returns the status of the handbrake
/// </summary>
bool IsHandbrakeActive { get; }
/// <summary>
/// The current headlight color
/// </summary>
byte HeadlightColor { get; set; }
/// <summary>
/// Sets or Gets the current radio station
/// </summary>
uint RadioStation { get; set; }
/// <summary>
/// Sets or Gets if the siren is active. True = active
/// </summary>
bool SirenActive { get; set; }
/// <summary>
/// Returns or Sets the LockState of the vehicle
/// </summary>
VehicleLockState LockState { get; set; }
/// <summary>
/// Returns the state of the door
/// </summary>
/// <param name="doorId">Door Id</param>
/// <returns>Door State</returns>
byte GetDoorState(byte doorId);
/// <summary>
/// Sets the door state
/// </summary>
/// <param name="doorId">The Door</param>
/// <param name="state">The state</param>
void SetDoorState(byte doorId, byte state);
/// <summary>
/// Returns if the window is opened
/// </summary>
/// <param name="windowId">Window Id</param>
/// <returns>True = Open</returns>
bool IsWindowOpened(byte windowId);
/// <summary>
/// Sets the window status
/// </summary>
/// <param name="windowId">Window Id</param>
/// <param name="state">True = Open</param>
void SetWindowOpened(byte windowId, bool state);
/// <summary>
/// Is the day lights on
/// </summary>
bool IsDaylightOn { get; }
/// <summary>
/// Is the night light on
/// </summary>
bool IsNightlightOn { get; }
/// <summary>
/// Sets the Roof state
/// </summary>
byte RoofState { get; set; }
/// <summary>
/// If the flamethrower is active
/// </summary>
bool IsFlamethrowerActive { get; }
/// <summary>
/// Multiplier for the lights
/// </summary>
float LightsMultiplier { get; set; }
/// <summary>
/// Vehicle state
/// </summary>
string State { get; set; }
/// <summary>
/// Engine Health
/// </summary>
int EngineHealth { get; set; }
/// <summary>
/// Fuel Tank Health
/// </summary>
int PetrolTankHealth { get; set; }
/// <summary>
/// Is the type burst
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <returns>True = Burst</returns>
bool IsWheelBurst(byte wheelId);
/// <summary>
/// Sets a wheels burst state
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <param name="state">True = Burst</param>
void SetWheelBurst(byte wheelId, bool state);
/// <summary>
/// Returns if the wheel has a tyre
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <returns>True = Has tyre</returns>
bool DoesWheelHasTire(byte wheelId);
/// <summary>
/// Sets if the wheel has a tyre
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <param name="state">True = Has tyre</param>
void SetWheelHasTire(byte wheelId, bool state);
/// <summary>
/// Returns if the wheel is detached
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <returns>True if the wheel is detached</returns>
bool IsWheelDetached(byte wheelId);
/// <summary>
/// Sets the detached state of the given wheel
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <param name="state">True when it should be detached, False when it should be attached</param>
void SetWheelDetached(byte wheelId, bool state);
/// <summary>
/// Returns if the wheel is on fire
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <returns>True if the wheel is on fire</returns>
bool IsWheelOnFire(byte wheelId);
/// <summary>
/// Sets the fire state of the given wheel
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <param name="state">True when it should be on fire, False when it should not be on fire</param>
void SetWheelOnFire(byte wheelId, bool state);
/// <summary>
/// Gets the wheels health
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <returns>Wheel health</returns>
float GetWheelHealth(byte wheelId);
/// <summary>
/// Sets the wheels healthy
/// </summary>
/// <param name="wheelId">Wheel Id</param>
/// <param name="health">Health</param>
void SetWheelHealth(byte wheelId, float health);
/// <summary>
/// Fix the wheel
/// </summary>
/// <param name="wheelId">Wheel Id</param>
void SetWheelFixed(byte wheelId);
/// <summary>
/// The amount of repairs
/// </summary>
byte RepairsCount { get; }
/// <summary>
/// The body health
/// </summary>
uint BodyHealth { get; set; }
/// <summary>
/// The additional body health
/// </summary>
uint BodyAdditionalHealth { get; set; }
/// <summary>
/// Health Data
/// </summary>
string HealthData { get; set; }
/// <summary>
/// Damage level by part
/// </summary>
/// <param name="partId">Part Id</param>
/// <returns>Damage Level</returns>
byte GetPartDamageLevel(byte partId);
/// <summary>
/// Sets the damage level of a part
/// </summary>
/// <param name="partId">Part Id</param>
/// <param name="damage">Damage Level</param>
void SetPartDamageLevel(byte partId, byte damage);
/// <summary>
/// Get the amount of bullet holes for the current part id
/// </summary>
/// <param name="partId">The current part od between 0 and 5</param>
/// <returns>The bullet holes count between 0 and 15</returns>
byte GetPartBulletHoles(byte partId);
/// <summary>
/// Set the amount of bullet holes for the current part id
/// </summary>
/// <param name="partId">The current part id between 0 and 5</param>
/// <param name="shootsCount">The bullet holes count between 0 and 15</param>
void SetPartBulletHoles(byte partId, byte shootsCount);
/// <summary>
/// Is the light damaged
/// </summary>
/// <param name="lightId">Light Id</param>
/// <returns>True = Damaged</returns>
bool IsLightDamaged(byte lightId);
/// <summary>
/// Sets the light damage state
/// </summary>
/// <param name="lightId">Light Id</param>
/// <param name="isDamaged">True = Damaged</param>
void SetLightDamaged(byte lightId, bool isDamaged);
/// <summary>
/// Returns if the window is damaged
/// </summary>
/// <param name="windowId">Window Id</param>
/// <returns>True = Damaged</returns>
bool IsWindowDamaged(byte windowId);
/// <summary>
/// Sets the window damage state
/// </summary>
/// <param name="windowId">Window Id</param>
/// <param name="isDamaged">True = Damaged</param>
void SetWindowDamaged(byte windowId, bool isDamaged);
/// <summary>
/// Returns if the special light is damaged
/// </summary>
/// <param name="specialLightId">Special light Id</param>
/// <returns>True = Damaged</returns>
bool IsSpecialLightDamaged(byte specialLightId);
/// <summary>
/// Sets the state of the special light damage
/// </summary>
/// <param name="specialLightId">Special Light</param>
/// <param name="isDamaged">Damage</param>
void SetSpecialLightDamaged(byte specialLightId, bool isDamaged);
/// <summary>
/// Returns true if has armored windows
/// </summary>
bool HasArmoredWindows { get; }
/// <summary>
/// Returns health of an armored window
/// </summary>
/// <param name="windowId">Window Id</param>
/// <returns>Health level</returns>
float GetArmoredWindowHealth(byte windowId);
/// <summary>
/// Sets the armored window health state
/// </summary>
/// <param name="windowId">Window Id</param>
/// <param name="health">State</param>
void SetArmoredWindowHealth(byte windowId, float health);
/// <summary>
/// Gets the amount of bullets that has hit the window
/// </summary>
/// <param name="windowId">Window Id</param>
/// <returns>Bullet Count</returns>
byte GetArmoredWindowShootCount(byte windowId);
/// <summary>
/// Sets the amount of bullets that has hit the window
/// </summary>
/// <param name="windowId">Window Id</param>
/// <param name="count">Amount of bullets</param>
void SetArmoredWindowShootCount(byte windowId, byte count);
/// <summary>
/// Gets the damage level for a bumper
/// </summary>
/// <param name="bumperId">0 - Front, 1 - Rear</param>
/// <returns>0 - Not Damaged / 1 - Damaged / 2 - None</returns>
byte GetBumperDamageLevel(byte bumperId);
/// <summary>
/// Sets the damage level of a bumper
/// </summary>
/// <param name="bumperId">0 - Front, 1 - Rear</param>
/// <param name="damageLevel">0 - Not Damaged / 1 - Damaged / 2 - None</param>
void SetBumperDamageLevel(byte bumperId, byte damageLevel);
/// <summary>
/// Returns the damage data
/// </summary>
string DamageData { get; set; }
/// <summary>
/// Enables or Disables automatic engine start when a player enters the drivers seat
/// </summary>
bool ManualEngineControl { get; set; }
/// <summary>
/// Script Data
/// </summary>
string ScriptData { get; set; }
/// <summary>
/// Removes the vehicle entity
/// </summary>
void Remove();
/// <summary>
/// Repairs the vehicle
/// </summary>
void Repair();
/// <summary>
/// Returns the current mod of the vehicle in the category
/// </summary>
/// <param name="category">Mod category</param>
/// <returns></returns>
byte GetModExt(VehicleModType category) => GetMod((byte) category);
/// <summary>
/// Returns the amount of mods available in a category
/// </summary>
/// <param name="category">The mod type</param>
/// <returns></returns>
byte GetModsCountExt(VehicleModType category) =>
GetModsCount((byte) category);
/// <summary>
/// Sets a vehicles mod into a category
/// </summary>
/// <param name="category">The mod category</param>
/// <param name="id">The mod id</param>
/// <returns></returns>
bool SetModExt(VehicleModType category, byte id) =>
SetMod((byte) category, id);
/// <summary>
/// Sets a vehicles part damage
/// </summary>
/// <param name="part">The vehicle part</param>
/// <param name="damage">The damage</param>
void SetPartDamageLevelExt(VehiclePart part, byte damage) =>
SetPartDamageLevel((byte) part, damage);
/// <summary>
/// Gets the damage level of a vehicle part
/// </summary>
/// <param name="part">The part</param>
/// <returns>The VehiclePart damage level</returns>
VehiclePartDamage GetPartDamageLevelExt(VehiclePart part) =>
(VehiclePartDamage) GetPartDamageLevel((byte) part);
/// <summary>
/// Get the amount of bullet holes in a part
/// </summary>
/// <param name="part">The vehicle part</param>
/// <returns>Amount of bullet holes</returns>
byte GetPartBulletHolesExt(VehiclePart part) =>
GetPartBulletHoles((byte) part);
/// <summary>
/// Sets the amount of bullet holes in a vehicles part
/// </summary>
/// <param name="part">The part</param>
/// <param name="shootsCount">The amount of bullets</param>
void SetPartBulletHolesExt(VehiclePart part, byte shootsCount) =>
SetPartBulletHoles((byte) part, shootsCount);
/// <summary>
/// Gets the vehicles bumper damage level
/// </summary>
/// <param name="bumper">The bumper</param>
/// <returns>Enum of VehicleBumperDamage</returns>
VehicleBumperDamage GetBumperDamageLevelExt(VehicleBumper bumper) =>
(VehicleBumperDamage) GetBumperDamageLevel((byte) bumper);
/// <summary>
/// Sets the vehicles bumper damage level
/// </summary>
/// <param name="bumper">The bumper (Front/Rear)</param>
/// <param name="damageLevel">The Bumper damage level</param>
void SetBumperDamageLevelExt(VehicleBumper bumper,
VehicleBumperDamage damageLevel) => SetBumperDamageLevel((byte) bumper, (byte) damageLevel);
/// <summary>
/// Sets the damage level of a vehicle part
/// </summary>
/// <param name="part">The vehicle part</param>
/// <param name="damage">The damage level</param>
void SetPartDamageLevelExt(VehiclePart part, VehiclePartDamage damage) =>
SetPartDamageLevel((byte) part, (byte) damage);
/// <summary>
/// Returns the current door state of a vehicles door
/// </summary>
/// <param name="door">The door</param>
/// <returns>The door state</returns>
VehicleDoorState GetDoorStateExt(VehicleDoor door) =>
(VehicleDoorState) GetDoorState((byte) door);
/// <summary>
/// Sets a vehicles door to a state
/// </summary>
/// <param name="door">The door</param>
/// <param name="state">The state</param>
void SetDoorStateExt(VehicleDoor door, VehicleDoorState state) =>
SetDoorState((byte) door, (byte) state);
/// <summary>
/// Sets the current radio station
/// </summary>
/// <param name="radioStation">The radio station</param>
void SetRadioStationExt(RadioStation radioStation) =>
RadioStation = (uint) radioStation;
/// <summary>
/// Gets the current radio station
/// </summary>
/// <returns>The radio station</returns>
RadioStation GetRadioStationExt() => (RadioStation) RadioStation;
/// <summary>
/// Sets the current window tint
/// </summary>
/// <param name="windowTint">The window tint</param>
void SetWindowTintExt(WindowTint windowTint) =>
WindowTint = (byte) windowTint;
/// <summary>
/// Gets the current window tint
/// </summary>
/// <returns>The window tint</returns>
WindowTint GetWindowTintExt() => (WindowTint) WindowTint;
/// <summary>
/// Sets the current number plate style
/// </summary>
/// <param name="numberPlateStyle">The number plate style</param>
void SetNumberPlateStyleExt(NumberPlateStyle numberPlateStyle) =>
NumberplateIndex = (uint) numberPlateStyle;
/// <summary>
/// Gets the current number plate style
/// </summary>
/// <returns>The number plate style</returns>
NumberPlateStyle GetNumberPlateStyleExt() =>
(NumberPlateStyle) NumberplateIndex;
/// <summary>
/// Sets the current roof state
/// </summary>
/// <param name="roofState">The roof state</param>
void SetRoofStateExt(VehicleRoofState roofState) =>
RoofState = (byte) roofState;
/// <summary>
/// Gets the current roof state
/// </summary>
/// <returns>The roof state</returns>
VehicleRoofState GetRoofStateExt() =>
(VehicleRoofState) RoofState;
/// <summary>
/// Gets the vehicles velocity
/// </summary>
Position Velocity { get; }
/// <summary>
/// Get or set drift mode of the vehicle
/// </summary>
bool DriftMode { get; set; }
/// <summary>
/// Get or set boat anchor of the vehicle
/// </summary>
bool BoatAnchor { get; set; }
/// <summary>
/// Sets the searchlight to given entity
/// </summary>
bool SetSearchLight(bool state, IEntity spottedEntity);
/// <summary>
/// Gets or sets if the vehicle is a train
/// </summary>
bool IsMissionTrain { get; set; }
/// <summary>
/// Gets or sets the trains track id
/// </summary>
sbyte TrainTrackId { get; set; }
/// <summary>
/// Gets or sets the trains engine
/// </summary>
IVehicle TrainEngine { get; set; }
/// <summary>
/// Gets or sets the trains config index
/// </summary>
sbyte TrainConfigIndex { get; set; }
/// <summary>
/// Gets or sets the trains distance from the engine
/// </summary>
float TrainDistanceFromEngine { get; set; }
/// <summary>
/// Gets or sets if the vehicle is the trains engine
/// </summary>
bool IsTrainEngine { get; set; }
/// <summary>
/// Gets or sets if the vehicle is caboose
/// </summary>
bool IsTrainCaboose { get; set; }
/// <summary>
/// Gets or sets the trains direction
/// </summary>
bool TrainDirection { get; set; }
/// <summary>
/// Gets or sets if the train has passenger carriages
/// </summary>
bool TrainPassengerCarriages { get; set; }
/// <summary>
/// Gets or sets if the train should be rendered derailed
/// </summary>
bool TrainRenderDerailed { get; set; }
/// <summary>
/// Gets or sets if the trains doors should be forced open
/// </summary>
bool TrainForceDoorsOpen { get; set; }
/// <summary>
/// Gets or sets the trains cruise speed
/// </summary>
float TrainCruiseSpeed { get; set; }
/// <summary>
/// Gets or sets the trains carriage config index
/// </summary>
sbyte TrainCarriageConfigIndex { get; set; }
/// <summary>
/// Gets or sets the trains vehicle linked backward vehicle
/// </summary>
IVehicle TrainLinkedToBackward { get; set; }
/// <summary>
/// Gets or sets the trains vehicle linked forward vehicle
/// </summary>
IVehicle TrainLinkedToForward { get; set; }
}
} | 32.47349 | 107 | 0.537325 | [
"MIT"
] | ZackaryH8/coreclr-module | api/AltV.Net/Elements/Entities/IVehicle.cs | 26,336 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// Paginator Data Structure.
/// </summary>
[Serializable]
public class Paginator : AopObject
{
/// <summary>
/// 页码
/// </summary>
[XmlElement("page_num")]
public long PageNum { get; set; }
/// <summary>
/// 每页记录数, 最大值只能是10
/// </summary>
[XmlElement("page_size")]
public long PageSize { get; set; }
/// <summary>
/// 总记录数, 作为参数时该值不需要填写, 填写将被忽略
/// </summary>
[XmlElement("total_items")]
public long TotalItems { get; set; }
}
}
| 22.548387 | 45 | 0.494993 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/Paginator.cs | 769 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System.Web.Http;
namespace MappingEdu.Web.UI.Infrastructure.Config
{
/// <summary>
/// Configures the json formatters
/// </summary>
public class FormattersConfig
{
/// <summary>
/// Registers the configuration
/// </summary>
public static void Register(HttpConfiguration config)
{
//config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
//config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
//config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
//config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented;
//var isoConverter = new IsoDateTimeConverter {DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK"};
//config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(isoConverter);
}
}
} | 47.566667 | 129 | 0.70918 | [
"Apache-2.0"
] | Ed-Fi-Exchange-OSS/MappingEDU | src/MappingEdu.Web.UI/Infrastructure/Config/FormattersConfig.cs | 1,429 | C# |
namespace Afonsoft.Ranking.Authentication
{
public class JsonClaimMapDto
{
public string Claim { get; set; }
public string Key { get; set; }
}
} | 19.333333 | 42 | 0.62069 | [
"MIT"
] | afonsoft/Ranking | src/Afonsoft.Ranking.Core.Shared/Authentication/JsonClaimMapDto.cs | 176 | C# |
namespace engenious.Graphics
{
/// <summary>
/// Interface describing an effect with ambient and directional lights.
/// </summary>
public interface IEffectLights
{
/// <summary>
/// Gets or sets the ambient light color.
/// </summary>
Vector3 AmbientLightColor{get;set;}
/// <summary>
/// Gets or sets whether the lighting effect is enabled.
/// </summary>
bool LightingEnabled{get;set;}
/// <summary>
/// Gets or sets the first directional light of this effect.
/// </summary>
DirectionalLight DirectionalLight0{get;set;}
/// <summary>
/// Gets or sets the second directional light of this effect.
/// </summary>
DirectionalLight DirectionalLight1{get;set;}
/// <summary>
/// Gets or sets the third directional light of this effect.
/// </summary>
DirectionalLight DirectionalLight2{get;set;}
/// <summary>
/// Initializes lights with default parameters.
/// </summary>
void EnableDefaultLighting();
}
}
| 24.175 | 72 | 0.679421 | [
"Apache-2.0"
] | engeniousproject/engenious | Graphics/Effect/IEffectLights.cs | 969 | C# |
namespace DataHub.AnalyticDataStore;
public interface IAnalyticDataStoreClient
{
public IHoldingClient Holding { get; }
public IPartyClient Party { get; }
public IProductClient Product { get; }
} | 26.125 | 42 | 0.755981 | [
"MIT"
] | ElevateData/OpenTemenos | src/DataHub.AnalyticDataStore/IAnalyticDataStoreClient.cs | 211 | C# |
using System.Collections.Generic;
using System.Linq;
using ViVuStoreMVC.Data;
using ViVuStoreMVC.Models;
namespace ViVuStoreMVC.Repositories
{
public class AuthorRepository : IAuthorRepository
{
private readonly ViVuStoreDbContext _context;
public AuthorRepository(ViVuStoreDbContext context)
{
_context = context;
}
public IEnumerable<Author> GetAuthors()
{
return _context.Authors.ToList();
}
}
}
| 21.521739 | 59 | 0.662626 | [
"MIT"
] | congdinh2008/ViVuStoreMVC | ViVuStoreMVC.Drop/ViVuStoreMVC/Repositories/AuthorRepository.cs | 497 | C# |
// =====================================================
// DO NOT EDIT - this file is automatically regenerated.
// =====================================================
using System;
using System.Collections.Generic;
using Improbable.Gdk.Core;
using Improbable.Worker.CInterop;
namespace Improbable.TestSchema
{
public partial class ExhaustiveEntity
{
public class ExhaustiveEntityViewStorage : IViewStorage, IViewComponentStorage<Snapshot>, IViewComponentUpdater<Update>
{
private readonly Dictionary<long, Authority> authorityStates = new Dictionary<long, Authority>();
private readonly Dictionary<long, Snapshot> componentData = new Dictionary<long, Snapshot>();
public Type GetSnapshotType()
{
return typeof(Snapshot);
}
public Type GetUpdateType()
{
return typeof(Update);
}
public uint GetComponentId()
{
return ComponentId;
}
public bool HasComponent(long entityId)
{
return componentData.ContainsKey(entityId);
}
public Snapshot GetComponent(long entityId)
{
if (!componentData.TryGetValue(entityId, out var component))
{
throw new ArgumentException($"Entity with Entity ID {entityId} does not have component {typeof(Snapshot)} in the view.");
}
return component;
}
public Authority GetAuthority(long entityId)
{
if (!authorityStates.TryGetValue(entityId, out var authority))
{
throw new ArgumentException($"Entity with Entity ID {entityId} does not have component {typeof(Snapshot)} in the view.");
}
return authority;
}
public void ApplyDiff(ViewDiff viewDiff)
{
var storage = viewDiff.GetComponentDiffStorage(ComponentId);
foreach (var entity in storage.GetComponentsAdded())
{
authorityStates[entity.Id] = Authority.NotAuthoritative;
componentData[entity.Id] = new Snapshot();
}
foreach (var entity in storage.GetComponentsRemoved())
{
authorityStates.Remove(entity.Id);
componentData.Remove(entity.Id);
}
var updates = ((IDiffUpdateStorage<Update>) storage).GetUpdates();
for (var i = 0; i < updates.Count; i++)
{
ref readonly var update = ref updates[i];
ApplyUpdate(update.EntityId.Id, in update.Update);
}
var authorityChanges = ((IDiffAuthorityStorage) storage).GetAuthorityChanges();
for (var i = 0; i < authorityChanges.Count; i++)
{
var authorityChange = authorityChanges[i];
authorityStates[authorityChange.EntityId.Id] = authorityChange.Authority;
}
}
public void ApplyUpdate(long entityId, in Update update)
{
if (!componentData.TryGetValue(entityId, out var data))
{
return;
}
if (update.Field1.HasValue)
{
data.Field1 = update.Field1.Value;
}
if (update.Field2.HasValue)
{
data.Field2 = update.Field2.Value;
}
if (update.Field3.HasValue)
{
data.Field3 = update.Field3.Value;
}
if (update.Field4.HasValue)
{
data.Field4 = update.Field4.Value;
}
if (update.Field5.HasValue)
{
data.Field5 = update.Field5.Value;
}
componentData[entityId] = data;
}
}
}
}
| 33.102362 | 141 | 0.492388 | [
"MIT"
] | nasakib/gdk-for-unity | test-project/Assets/Generated/Source/improbable/testschema/ExhaustiveEntityViewStorage.cs | 4,204 | 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.Compute.V20180401.Inputs
{
/// <summary>
/// Describes a virtual machine scale set virtual machine profile.
/// </summary>
public sealed class VirtualMachineScaleSetVMProfileArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the boot diagnostic settings state. <br><br>Minimum api-version: 2015-06-15.
/// </summary>
[Input("diagnosticsProfile")]
public Input<Inputs.DiagnosticsProfileArgs>? DiagnosticsProfile { get; set; }
/// <summary>
/// Specifies the eviction policy for virtual machines in a low priority scale set. <br><br>Minimum api-version: 2017-10-30-preview
/// </summary>
[Input("evictionPolicy")]
public InputUnion<string, Pulumi.AzureNative.Compute.V20180401.VirtualMachineEvictionPolicyTypes>? EvictionPolicy { get; set; }
/// <summary>
/// Specifies a collection of settings for extensions installed on virtual machines in the scale set.
/// </summary>
[Input("extensionProfile")]
public Input<Inputs.VirtualMachineScaleSetExtensionProfileArgs>? ExtensionProfile { get; set; }
/// <summary>
/// Specifies that the image or disk that is being used was licensed on-premises. This element is only used for images that contain the Windows Server operating system. <br><br> Possible values are: <br><br> Windows_Client <br><br> Windows_Server <br><br> If this element is included in a request for an update, the value must match the initial value. This value cannot be updated. <br><br> For more information, see [Azure Hybrid Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-hybrid-use-benefit-licensing?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Minimum api-version: 2015-06-15
/// </summary>
[Input("licenseType")]
public Input<string>? LicenseType { get; set; }
/// <summary>
/// Specifies properties of the network interfaces of the virtual machines in the scale set.
/// </summary>
[Input("networkProfile")]
public Input<Inputs.VirtualMachineScaleSetNetworkProfileArgs>? NetworkProfile { get; set; }
/// <summary>
/// Specifies the operating system settings for the virtual machines in the scale set.
/// </summary>
[Input("osProfile")]
public Input<Inputs.VirtualMachineScaleSetOSProfileArgs>? OsProfile { get; set; }
/// <summary>
/// Specifies the priority for the virtual machines in the scale set. <br><br>Minimum api-version: 2017-10-30-preview
/// </summary>
[Input("priority")]
public InputUnion<string, Pulumi.AzureNative.Compute.V20180401.VirtualMachinePriorityTypes>? Priority { get; set; }
/// <summary>
/// Specifies the storage settings for the virtual machine disks.
/// </summary>
[Input("storageProfile")]
public Input<Inputs.VirtualMachineScaleSetStorageProfileArgs>? StorageProfile { get; set; }
public VirtualMachineScaleSetVMProfileArgs()
{
}
}
}
| 50.478873 | 741 | 0.680525 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Compute/V20180401/Inputs/VirtualMachineScaleSetVMProfileArgs.cs | 3,584 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Kontur.Results;
namespace Kontur.Tests.Results.Extraction.SelectMany.FirstFault.Optional.Using
{
public static class SelectManyOptionalExtensions
{
public static Optional<IEnumerable<TResult>> SelectMany<TValue, TItem, TResult>(
this IOptional<TValue> optional,
Func<TValue, IEnumerable<TItem>> collectionSelector,
Func<TValue, TItem, TResult> resultSelector)
{
return optional.MapValue(value => collectionSelector(value).Select(item => resultSelector(value, item)));
}
}
}
| 33.315789 | 117 | 0.701422 | [
"MIT"
] | skbkontur/result | Kontur.Tests.Results/Extraction/SelectMany/FirstFault/Optional/Using/SelectManyOptionalExtensions.cs | 635 | C# |
using ImHungry.Api.Models;
using System.Globalization;
namespace ImHungry.Api.Helpers;
public static class CsvHelper
{
public static IEnumerable<MobileFoodPoint> MapCsvData(string? csvData, ILogger logger)
{
var mobileFoodPoints = new List<MobileFoodPoint>();
if (csvData is null)
{
return mobileFoodPoints;
}
var reader = new StringReader(csvData);
// get rid of the first line that contains column names
var _ = reader.ReadLine();
var id = 0;
var latitude = 0.0;
var longitude = 0.0;
while (true)
{
var line = reader.ReadLine();
if (line == null)
{
break;
}
var lineData = line.Split(',');
try
{
id = int.Parse(lineData[0]);
latitude = double.Parse(lineData[14], CultureInfo.InvariantCulture);
longitude = double.Parse(lineData[15], CultureInfo.InvariantCulture);
}
catch
{
logger.LogDebug($"Item with Id '{lineData[0]}' skipped because of error. Latitude: '{lineData[14]}', Longitude: '{lineData[15]}'");
continue;
}
if (latitude == 0.0 || longitude == 0.0)
{
logger.LogDebug($"Item with Id '{id}' skipped because of not correct values for latitude '{latitude}' or longitude '{longitude}'");
continue;
}
mobileFoodPoints.Add(new MobileFoodPoint
{
Id = id,
Name = lineData[1],
Type = lineData[2],
LocationDescription = lineData[4],
Address = lineData[5],
Food = lineData[11],
Latitude = latitude,
Longitude = longitude
});
}
logger.LogDebug($"Mapped {mobileFoodPoints.Count} mobile food points from CSV date");
return mobileFoodPoints;
}
}
| 30.235294 | 147 | 0.514105 | [
"MIT"
] | anmalkov/imhungry | src/ImHungry.Api/ImHungry.Api/Helpers/CsvHelper.cs | 2,058 | C# |
using GeoPay_API;
using GeoPay_API.Models;
using NUnit.Framework;
using System.Threading.Tasks;
namespace Tests
{
public class Tests
{
[SetUp]
public void Setup()
{
}
[Test]
public async Task Test1()
{
PaymentProcessor paymentProcessor = new PaymentProcessor();
var result = await paymentProcessor.ExecutePayment("321463282363179XX");
}
}
} | 18.5 | 84 | 0.599099 | [
"MIT"
] | TheLastColonial/ECB-Hackathon | GeoPay_API/GeoPay_API.Tests/UnitTest1.cs | 444 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34011
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LiteFx.Context.NHibernate.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "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 (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LiteFx.Context.NHibernate.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;
}
}
/// <summary>
/// Looks up a localized string similar to You can call ConfigurationManager.Initialize only once..
/// </summary>
internal static string YouCanCallConfigurationManagerInitializeOnlyOnce {
get {
return ResourceManager.GetString("YouCanCallConfigurationManagerInitializeOnlyOnce", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You can call SessionFactoryManager.Initialize only once..
/// </summary>
internal static string YouCanCallSessionFactoryManagerInitializeOnlyOnce {
get {
return ResourceManager.GetString("YouCanCallSessionFactoryManagerInitializeOnlyOnce", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You can't begin a transaction without an active NHibernate Session..
/// </summary>
internal static string YouCantBeginATransactionWithoutAnActiveNHibernateSession {
get {
return ResourceManager.GetString("YouCantBeginATransactionWithoutAnActiveNHibernateSession", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You have to call ConfigurationManager.Initialize at LiteFxWebNHibernate.Start..
/// </summary>
internal static string YouHaveToCallConfigurationManagerInitializeAtLiteFxWebNHibernateStart {
get {
return ResourceManager.GetString("YouHaveToCallConfigurationManagerInitializeAtLiteFxWebNHibernateStart", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You have to call SessionFactoryManager.Initialize at LiteFxWebNHibernate.Start..
/// </summary>
internal static string YouHaveToCallSessionFactoryManagerInitializeAtLiteFxWebNHibernateStart {
get {
return ResourceManager.GetString("YouHaveToCallSessionFactoryManagerInitializeAtLiteFxWebNHibernateStart", resourceCulture);
}
}
}
}
| 47.018349 | 192 | 0.620878 | [
"MIT"
] | Iarly/LiteFx | LiteFx.NHibernate/Properties/Resources.Designer.cs | 5,127 | C# |
/******************************************************************************
* Copyright (C) Ultraleap, Inc. 2011-2020. *
* Ultraleap proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Ultraleap and you, your company or other organization. *
******************************************************************************/
using InteractionEngineUtility;
using Leap.Unity.Space;
using Leap.Unity.Interaction.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Leap.Unity.RuntimeGizmos;
using Leap.Unity.Attributes;
namespace Leap.Unity.Interaction {
[Serializable]
public class InteractionControllerSet : SerializableHashSet<InteractionController> { }
/// <summary>
/// Specified on a per-object basis to allow Interaction objects
/// to ignore hover for the left hand, right hand, or both hands.
/// </summary>
public enum IgnoreHoverMode { None, Left, Right, Both }
/// <summary>
/// The Interaction Engine can be controlled by hands tracked by the
/// Leap Motion Controller, or by remote-style held controllers
/// such as the Oculus Touch or Vive controller.
/// </summary>
public enum ControllerType { Hand, XRController }
[DisallowMultipleComponent]
public abstract class InteractionController : MonoBehaviour,
IInternalInteractionController {
#region Inspector
[Tooltip("The manager responsible for this interaction controller. Interaction "
+ "controllers should be children of their interaction manager.")]
public InteractionManager manager;
[Header("Interaction Types")]
[Tooltip("If disabled, this interaction controller will not be used to generate "
+ "hover information or primary hover information. Warning: Primary hover "
+ "data is required for Interaction Engine user interface components like "
+ "InteractionButton and InteractionSlider to function, so this controller "
+ "won't able to interact with UI components.")]
[SerializeField]
[OnEditorChange("hoverEnabled")]
private bool _hoverEnabled = true;
public bool hoverEnabled {
get { return _hoverEnabled; }
set {
_hoverEnabled = value;
if (!_hoverEnabled) {
ClearHoverTracking();
}
}
}
[Tooltip("If disabled, this interaction controller will not collide with interaction "
+ "objects and objects will not receive contact callbacks.")]
[SerializeField]
[OnEditorChange("contactEnabled")]
private bool _contactEnabled = true;
public bool contactEnabled {
get { return _contactEnabled; }
set {
_contactEnabled = value;
if (!_contactEnabled) {
disableContactBoneCollision();
ClearContactTracking();
}
else {
resetContactBonePose();
EnableSoftContact();
}
}
}
[Tooltip("If disabled, this interaction controller will not be able to grasp "
+ "interaction objects.")]
[SerializeField]
[OnEditorChange("graspingEnabled")]
private bool _graspingEnabled = true;
public bool graspingEnabled {
get { return _graspingEnabled; }
set {
_graspingEnabled = value;
if (!_graspingEnabled) {
EnableSoftContact();
ReleaseGrasp();
}
}
}
#endregion
#region Public API
/// <summary>
/// Gets whether the underlying object (Leap hand or a held controller) is currently
/// in a tracked state. Objects grasped by a controller that becomes untracked will
/// become "suspended" and receive specific suspension callbacks. (Implementing any
/// behaviour during the suspension state is left up to the developer, however.)
/// </summary>
public abstract bool isTracked { get; }
/// <summary>
/// Gets whether the underlying object (Leap hand or a held controller) is currently
/// being moved or being actively manipulated by the player.
/// </summary>
public abstract bool isBeingMoved { get; }
/// <summary>
/// Gets whether the underlying object (Leap hand or a held controller) represents
/// or is held by a left hand (true) or a right hand (false).
/// </summary>
public abstract bool isLeft { get; }
/// <summary>
/// Gets whether the underlying object (Leap hand or a held controller) represents
/// or is held by a right hand (true) or a left hand (false).
/// </summary>
public bool isRight { get { return !isLeft; } }
/// <summary>
/// Returns the current position of this controller.
/// </summary>
public abstract Vector3 position { get; }
/// <summary>
/// Returns the current rotation of this controller.
/// </summary>
public abstract Quaternion rotation { get; }
/// <summary>
/// Returns the current velocity of this controller.
/// </summary>
public abstract Vector3 velocity { get; }
/// <summary>
/// Gets the type of controller this object represents underneath the
/// InteractionController abstraction. If the type is ControllerType.Hand, the
/// intHand property will contain the InteractionHand object this object abstracts
/// from.
/// </summary>
public abstract ControllerType controllerType { get; }
/// <summary>
/// If this InteractionController's controllerType is ControllerType.Hand,
/// this gets the InteractionHand, otherwise this returns null.
/// </summary>
public abstract InteractionHand intHand { get; }
/// <summary>
/// Contact requires knowledge of the controller's scale. Non-uniformly scaled
/// controllers are NOT supported.
/// </summary>
public float scale { get { return this.transform.lossyScale.x; } }
#endregion
#region Events
/// <summary>
/// Called when this InteractionController begins primarily hovering over an InteractionBehaviour.
/// If the controller transitions to primarily hovering a new object, OnEndPrimaryHoveringObject will
/// first be called on the old object, then OnBeginPrimaryHoveringObject will be called for
/// the new object.
/// </summary>
public Action<InteractionBehaviour> OnBeginPrimaryHoveringObject = (intObj) => { };
/// <summary>
/// Called when this InteractionController stops primarily hovering over an InteractionBehaviour.
/// If the controller transitions to primarily-hovering a new object, OnEndPrimaryHoveringObject will
/// first be called on the old object, then OnBeginPrimaryHoveringObject will be called for
/// the new object.
/// </summary>
public Action<InteractionBehaviour> OnEndPrimaryHoveringObject = (intObj) => { };
/// <summary>
/// Called every (fixed) frame this InteractionController is primarily hovering over an InteractionBehaviour.
/// </summary>
public Action<InteractionBehaviour> OnStayPrimaryHoveringObject = (intObj) => { };
/// <summary>
/// Called when the InteractionController begins grasping an object.
/// </summary>
public Action OnGraspBegin = () => { };
/// <summary>
/// Called while the InteractionController is grasping an object.
/// </summary>
public Action OnGraspStay = () => { };
/// <summary>
/// Called when the InteractionController releases an object.
/// </summary>
public Action OnGraspEnd = () => { };
/// <summary>
/// Called when contact data is initialized.
/// </summary>
public Action<InteractionController> OnContactInitialized = (intCtrl) => { };
#endregion
#region Unity Events
protected virtual void Reset() {
if (manager == null) manager = GetComponentInParent<InteractionManager>();
}
protected virtual void OnEnable() {
if (_contactInitialized) {
EnableSoftContact();
resetContactBonePose();
}
}
protected virtual void Start() {
if (manager == null) manager = InteractionManager.instance;
}
protected virtual void OnDisable() {
if (_contactInitialized) {
EnableSoftContact();
}
ReleaseGrasp();
ClearHoverTracking();
ClearPrimaryHoverTracking();
ClearContactTracking();
}
#endregion
// A list of InteractionControllers for use as a temporary buffer.
private List<InteractionController> _controllerListBuffer = new List<InteractionController>();
/// <summary>
/// Called by the InteractionManager every fixed (physics) frame to populate the
/// Interaction Hand with state from the Leap hand and perform bookkeeping operations.
/// </summary>
void IInternalInteractionController.FixedUpdateController() {
fixedUpdateController();
if (hoverEnabled) fixedUpdateHovering();
if (contactEnabled) fixedUpdateContact();
if (graspingEnabled) fixedUpdateGrasping();
}
public void NotifyObjectUnregistered(IInteractionBehaviour intObj) {
ClearHoverTrackingForObject(intObj);
ClearContactTrackingForObject(intObj);
onObjectUnregistered(intObj);
}
/// <summary>
/// This method is called by the InteractionController when it is notified by the
/// InteractionManager that an InteractionBehaviour has been unregistered from the
/// Interaction Engine. If your controller has any state that remembers or tracks
/// interaction objects, this method should clear that state, because unregistered
/// objects won't receive state updates or callbacks from this controller's
/// Interaction Manager anymore.
/// </summary>
protected abstract void onObjectUnregistered(IInteractionBehaviour intObj);
/// <summary>
/// Called just before the InteractionController proceeds with its usual FixedUpdate.
///
/// It's generally better to override this method instead of having your
/// InteractionController implement FixedUpdate because its execution order relative
/// to the Interaction Manager is fixed.
/// </summary>
protected virtual void fixedUpdateController() { }
#region Hovering
/// <summary>
/// In addition to standard hover validity checks, you can set this filter property
/// to further filter objects for hover consideration. Only objects for which this
/// function returns true will be hover candidates (if the filter is not null).
/// </summary>
public Func<IInteractionBehaviour, bool> customHoverActivityFilter = null;
// Hover Activity Filter
private Func<Collider, IInteractionBehaviour> hoverActivityFilter;
private IInteractionBehaviour hoverFilterFunc(Collider collider) {
Rigidbody rigidbody = collider.attachedRigidbody;
IInteractionBehaviour intObj = null;
bool objectValidForHover = rigidbody != null
&& manager.interactionObjectBodies.TryGetValue(rigidbody, out intObj)
&& !intObj.ShouldIgnoreHover(this)
&& (customHoverActivityFilter == null || customHoverActivityFilter(intObj));
if (objectValidForHover) return intObj;
else return null;
}
// Layer mask for the hover acitivity manager.
private Func<int> hoverLayerMaskAccessor;
// Hover Activity Manager
private ActivityManager<IInteractionBehaviour> _hoverActivityManager;
public ActivityManager<IInteractionBehaviour> hoverActivityManager {
get {
if (_hoverActivityManager == null) {
if (hoverActivityFilter == null) hoverActivityFilter = hoverFilterFunc;
if (hoverLayerMaskAccessor == null) hoverLayerMaskAccessor = manager.GetInteractionLayerMask;
_hoverActivityManager = new ActivityManager<IInteractionBehaviour>(manager.hoverActivationRadius,
hoverActivityFilter);
_hoverActivityManager.activationLayerFunction = hoverLayerMaskAccessor;
}
return _hoverActivityManager;
}
}
/// <summary>
/// Disables broadphase checks if an object is currently interacting with this hand.
/// </summary>
private bool _primaryHoverLocked = false;
/// <summary>
/// When set to true, locks the current primarily hovered object, even if the hand
/// gets closer to a different object.
/// </summary>
public bool primaryHoverLocked {
get { return _primaryHoverLocked; }
set { _primaryHoverLocked = value; }
}
/// <summary>
/// Sets the argument interaction object to be the current primary hover of this
/// interaction controller and locks the primary hover state of the interaction
/// controller.
/// <see cref="primaryHoverLocked"/>
/// </summary>
public void LockPrimaryHover(InteractionBehaviour intObj) {
_primaryHoveredObject = intObj;
_primaryHoverLocked = true;
}
/// <summary>
/// Gets the current position to check against nearby objects for hovering.
/// Position is only used if the controller is currently tracked. For example,
/// InteractionHand returns the center of the palm of the underlying Leap hand.
/// </summary>
public abstract Vector3 hoverPoint { get; }
private HashSet<IInteractionBehaviour> _hoveredObjects = new HashSet<IInteractionBehaviour>();
/// <summary>
/// Returns a set of all Interaction objects currently hovered by this
/// InteractionController.
/// </summary>
public ReadonlyHashSet<IInteractionBehaviour> hoveredObjects { get { return _hoveredObjects; } }
protected abstract List<Transform> _primaryHoverPoints { get; }
/// <summary>
/// Gets the list of Transforms to consider against nearby objects to determine
/// the closest object (primary hover) of this controller.
/// </summary>
public ReadonlyList<Transform> primaryHoverPoints { get { return _primaryHoverPoints; } }
/// <summary>
/// Gets whether the InteractionController is currently primarily hovering over
/// any interaction object.
/// </summary>
public bool isPrimaryHovering { get { return primaryHoveredObject != null; } }
private IInteractionBehaviour _primaryHoveredObject;
/// <summary>
/// Gets the InteractionBehaviour that is currently this InteractionController's
/// primary hovered object, if there is one.
/// </summary>
public IInteractionBehaviour primaryHoveredObject { get { return _primaryHoveredObject; } }
private float _primaryHoverDistance = float.PositiveInfinity;
/// <summary>
/// Gets the distance from the closest primary hover point on this controller to its
/// primarily hovered object, if there are any.
/// </summary>
public float primaryHoverDistance { get { return _primaryHoverDistance; } }
/// <summary>
/// Gets the position of the primary hovering point that is closest to its primary
/// hovered object, if this controller has a primary hover. Otherwise, returns
/// Vector3.zero.
/// </summary>
public Vector3 primaryHoveringPoint {
get {
return isPrimaryHovering ? _primaryHoverPoints[_primaryHoverPointIdx].position
: Vector3.zero;
}
}
/// <summary>
/// Gets the index in the primaryHoverPoints array of the primary hover point that is
/// currently closest to this controller's primary hover object.
/// </summary>
public int primaryHoveringPointIndex { get { return _primaryHoverPointIdx; } }
/// <summary> Index of the closest primary hover point in the primaryHoverPoints list. </summary>
private int _primaryHoverPointIdx = -1;
private List<IInteractionBehaviour> _perPointPrimaryHovered = new List<IInteractionBehaviour>();
private List<float> _perPointPrimaryHoverDistance = new List<float>();
private void fixedUpdateHovering() {
using (new ProfilerSample("Fixed Update InteractionController Hovering")) {
// Reset hover lock if the controller loses tracking.
if (!isTracked && primaryHoverLocked) {
_primaryHoverLocked = false;
}
// Update hover state.
hoverActivityManager.activationRadius = manager.WorldHoverActivationRadius;
Vector3? queryPosition = isTracked ? (Vector3?)hoverPoint : null;
hoverActivityManager.UpdateActivityQuery(queryPosition, LeapSpace.allEnabled);
// Add all returned objects as "hovered".
// Find closest objects per primary hover point to update primary hover state.
using (new ProfilerSample("Find Closest Objects for Primary Hover")) {
refreshHoverState(_hoverActivityManager.ActiveObjects);
}
// Refresh buffer information from the previous frame to be able to fire
// the appropriate hover state callbacks.
refreshHoverStateBuffers();
refreshPrimaryHoverStateBuffers();
// Support interactions in curved ("warped") space by "unwarping" hands into
// the curved space's physics (rectilinear) space.
if (isTracked && isPrimaryHovering) {
ISpaceComponent space = primaryHoveredObject.space;
if (space != null
&& space.anchor != null
&& space.anchor.space != null) {
unwarpColliders(primaryHoverPoints[_primaryHoverPointIdx], space);
}
}
}
}
/// <summary>
/// Implementing this method is necessary to support curved spaces as
/// rendered by a Leap Graphic Renderer. See InteractionHand for an example
/// implementation. (Implementing this method is optional if you are not
/// using a curved space as rendered by a Leap Graphic Renderer.)
/// </summary>
/// <remarks>
/// Warps the collider transforms of this controller by the inverse of the
/// transformation that is applied on the provided warpedSpaceElement, using
/// the primaryHoverPoint as the pivot transform for the transformation.
///
/// ITransformer.WorldSpaceUnwarp is a useful method here. (ISpaceComponents
/// contain references to their transformers via their anchors.)
///
/// ISpaceComponents denote game objects whose visual positions are warped
/// from rectilinear (non-warped) space into a curved space (via, for example,
/// a LeapCylindricalSpace, which can only be rendered correctly by the Leap
/// Graphic Renderer). This method reverses that transformation for the hand,
/// bringing it into the object's rectilinear space, allowing objects curved
/// in this way to correctly collide with the bones in the hand or collider of
/// a held controller.
///
/// The provided Transform is the closest primary hover point to any given
/// primary hover candidate, so it is used as the pivot point for unwarping
/// the colliders of this InteractionController.
/// </remarks>
protected abstract void unwarpColliders(Transform primaryHoverPoint,
ISpaceComponent warpedSpaceElement);
// Hover history, handled as part of the Interaction Manager's state-check calls.
private IInteractionBehaviour _primaryHoveredLastFrame = null;
private HashSet<IInteractionBehaviour> _hoveredLastFrame = new HashSet<IInteractionBehaviour>();
/// <summary>
/// Clears the previous hover state data and calculates it anew based on the
/// latest hover and primary hover point data.
/// </summary>
private void refreshHoverState(HashSet<IInteractionBehaviour> hoverCandidates) {
// Prepare data from last frame for hysteresis later on.
int primaryHoverPointIdxLastFrame = _primaryHoveredLastFrame != null ? _primaryHoverPointIdx : -1;
_hoveredObjects.Clear();
IInteractionBehaviour lockedPrimaryHoveredObject = null;
if (primaryHoverLocked) {
lockedPrimaryHoveredObject = _primaryHoveredObject;
}
_primaryHoveredObject = null;
_primaryHoverDistance = float.PositiveInfinity;
_primaryHoverPointIdx = -1;
_perPointPrimaryHovered.Clear();
_perPointPrimaryHoverDistance.Clear();
for (int i = 0; i < primaryHoverPoints.Count; i++) {
_perPointPrimaryHovered.Add(null);
_perPointPrimaryHoverDistance.Add(float.PositiveInfinity);
}
// We can only update hover information if there's tracked data.
if (!isTracked) return;
// Determine values to apply hysteresis to the primary hover state.
float maxNewPrimaryHoverDistance = float.PositiveInfinity;
if (_primaryHoveredLastFrame != null && primaryHoverPointIdxLastFrame != -1
&& primaryHoverPoints[primaryHoverPointIdxLastFrame] != null) {
if (_contactBehaviours.ContainsKey(_primaryHoveredLastFrame)) {
// If we're actually touching the last primary hover, prevent the primary hover from changing at all.
maxNewPrimaryHoverDistance = 0F;
}
else {
float distanceToLastPrimaryHover = _primaryHoveredLastFrame.GetHoverDistance(
primaryHoverPoints[primaryHoverPointIdxLastFrame].position);
// Otherwise...
// The distance to a new object must be even closer than the current primary hover
// distance in order for that object to become the new primary hover.
maxNewPrimaryHoverDistance = distanceToLastPrimaryHover
* distanceToLastPrimaryHover.Map(0.009F, 0.018F, 0.4F, 0.95F);
}
}
foreach (IInteractionBehaviour behaviour in hoverCandidates) {
// All hover candidates automatically count as hovered.
_hoveredObjects.Add(behaviour);
// Some objects can ignore consideration for primary hover as an
// optimization, since it can require a lot of distance checks.
if (behaviour.ignorePrimaryHover) continue;
// Do further processing to determine the primary hover if primary hover isn't
// locked.
else if (!primaryHoverLocked) {
processPrimaryHover(behaviour, maxNewPrimaryHoverDistance);
}
}
// If the primary hover is locked, we need to process primary hover specifically
// for the locked object.
if (primaryHoverLocked && lockedPrimaryHoveredObject != null) {
processPrimaryHover(lockedPrimaryHoveredObject, float.PositiveInfinity);
}
}
private void processPrimaryHover(IInteractionBehaviour behaviour, float maxNewPrimaryHoverDistance) {
// Check against all positions currently registered as primary hover points,
// finding the closest one and updating hover data accordingly.
float shortestPointDistance = float.PositiveInfinity;
for (int i = 0; i < primaryHoverPoints.Count; i++) {
var primaryHoverPoint = primaryHoverPoints[i];
// It's possible to disable primary hover points to ignore them for hover
// consideration.
if (primaryHoverPoint == null) continue;
if (!primaryHoverPoint.gameObject.activeInHierarchy) continue;
// Skip non-index fingers for InteractionHands if they aren't extended.
if (intHand != null) {
if (!(intHand.leapHand).Fingers[i].IsExtended && i != 1) { continue; }
}
// Check primary hover for the primary hover point.
float behaviourDistance = GetHoverDistance(primaryHoverPoint.position, behaviour);
if (behaviourDistance < shortestPointDistance) {
// This is the closest behaviour to this primary hover point.
_perPointPrimaryHovered[i] = behaviour;
_perPointPrimaryHoverDistance[i] = behaviourDistance;
shortestPointDistance = behaviourDistance;
if (primaryHoverLocked) {
// If primary hover is locked, there's only one object to consider,
// and the current primary hover point is the closest one to the object
// so far, so update primary hover accordingly.
_primaryHoveredObject = _perPointPrimaryHovered[i]; // (redundant)
_primaryHoverDistance = _perPointPrimaryHoverDistance[i];
_primaryHoverPointIdx = i;
}
else if (shortestPointDistance < _primaryHoverDistance
&& (behaviour == _primaryHoveredLastFrame || behaviourDistance < maxNewPrimaryHoverDistance)) {
// This is the closest behaviour to ANY primary hover point, and the
// distance is less than the hysteresis distance to transition away from
// the previous primary hovered object.
_primaryHoveredObject = _perPointPrimaryHovered[i];
_primaryHoverDistance = _perPointPrimaryHoverDistance[i];
_primaryHoverPointIdx = i;
}
}
}
}
/// <summary>
/// Clears all hover tracking state and fires the hover-end callbacks immediately.
/// If objects are still in the hover radius around this controller and the
/// controller and manager are still active, HoverBegin callbacks will be invoked
/// again on the next fixed frame.
/// </summary>
public void ClearHoverTracking() {
_controllerListBuffer.Clear();
_controllerListBuffer.Add(this);
var tempObjs = Pool<HashSet<IInteractionBehaviour>>.Spawn();
try {
foreach (var intObj in hoveredObjects) {
tempObjs.Add(intObj);
}
foreach (var intObj in tempObjs) {
// Prevents normal hover state checking on the next frame from firing duplicate
// hover-end callbacks. If the object is still hovered (and the controller is
// still in an enabled state), the object WILL receive a hover begin callback
// on the next frame.
_hoveredObjects.Remove(intObj);
_hoveredLastFrame.Remove(intObj);
intObj.EndHover(_controllerListBuffer);
}
}
finally {
tempObjs.Clear();
Pool<HashSet<IInteractionBehaviour>>.Recycle(tempObjs);
}
}
/// <summary>
/// Clears the hover tracking state for an object and fires the hover-end callback
/// for that object immediately.
///
/// If the object is still in the hover radius of this controller and the controller
/// and manager are still active, the hover will begin anew on the next fixed frame.
/// </summary>
public void ClearHoverTrackingForObject(IInteractionBehaviour intObj) {
if (!hoveredObjects.Contains(intObj)) return;
_hoveredObjects.Remove(intObj);
_hoveredLastFrame.Remove(intObj);
_controllerListBuffer.Clear();
_controllerListBuffer.Add(this);
intObj.EndHover(_controllerListBuffer);
}
#region Hover State Checks
private HashSet<IInteractionBehaviour> _hoverEndedBuffer = new HashSet<IInteractionBehaviour>();
private HashSet<IInteractionBehaviour> _hoverBeganBuffer = new HashSet<IInteractionBehaviour>();
private List<IInteractionBehaviour> _hoverRemovalCache = new List<IInteractionBehaviour>();
private void refreshHoverStateBuffers() {
_hoverBeganBuffer.Clear();
_hoverEndedBuffer.Clear();
var trackedBehaviours = _hoverActivityManager.ActiveObjects;
foreach (var hoverable in trackedBehaviours) {
bool inLastFrame = false, inCurFrame = false;
if (hoveredObjects.Contains(hoverable)) {
inCurFrame = true;
}
if (_hoveredLastFrame.Contains(hoverable)) {
inLastFrame = true;
}
if (inCurFrame && !inLastFrame) {
_hoverBeganBuffer.Add(hoverable);
_hoveredLastFrame.Add(hoverable);
}
if (!inCurFrame && inLastFrame) {
_hoverEndedBuffer.Add(hoverable);
_hoveredLastFrame.Remove(hoverable);
}
}
foreach (var hoverable in _hoveredLastFrame) {
if (!trackedBehaviours.Contains(hoverable)) {
_hoverEndedBuffer.Add(hoverable);
_hoverRemovalCache.Add(hoverable);
}
}
foreach (var hoverable in _hoverRemovalCache) {
_hoveredLastFrame.Remove(hoverable);
}
_hoverRemovalCache.Clear();
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Outputs objects that stopped being hovered by this hand this frame into hoverEndedObjects and returns whether
/// the output set is empty.
/// </summary>
bool IInternalInteractionController.CheckHoverEnd(out HashSet<IInteractionBehaviour> hoverEndedObjects) {
// Hover checks via the activity manager are robust to destroyed or made-invalid objects,
// so no additional validity checking is required.
hoverEndedObjects = _hoverEndedBuffer;
return _hoverEndedBuffer.Count > 0;
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Outputs objects that began being hovered by this hand this frame into hoverBeganObjects and returns whether
/// the output set is empty.
/// </summary>
bool IInternalInteractionController.CheckHoverBegin(out HashSet<IInteractionBehaviour> hoverBeganObjects) {
hoverBeganObjects = _hoverBeganBuffer;
return _hoverBeganBuffer.Count > 0;
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Outputs objects that are currently hovered by this hand into hoveredObjects and returns whether the
/// output set is empty.
/// </summary>
bool IInternalInteractionController.CheckHoverStay(out HashSet<IInteractionBehaviour> hoveredObjects) {
hoveredObjects = _hoveredObjects;
return hoveredObjects.Count > 0;
}
#endregion
/// <summary>
/// Clears primary hover tracking state for the current primary hovered object.
///
/// If the current primary hover is still the most eligible hovered object and this
/// controller and its manager are still active, primary hover will begin anew on
/// the next fixed frame.
/// </summary>
public void ClearPrimaryHoverTracking() {
if (!isPrimaryHovering) return;
// This will cause the primary-hover-end check to return this object, and prevent
// a duplicate primary-hover-end call when refreshPrimaryHoverStateBuffers() is
// called on the next frame.
var formerlyPrimaryHoveredObj = _primaryHoveredObject;
_primaryHoveredObject = null;
_primaryHoveredLastFrame = null;
if (primaryHoverLocked) primaryHoverLocked = false;
_controllerListBuffer.Clear();
_controllerListBuffer.Add(this);
formerlyPrimaryHoveredObj.EndPrimaryHover(_controllerListBuffer);
}
#region Primary Hover State Checks
private IInteractionBehaviour _primaryHoverEndedObject = null;
private IInteractionBehaviour _primaryHoverBeganObject = null;
private void refreshPrimaryHoverStateBuffers() {
if (primaryHoveredObject != _primaryHoveredLastFrame) {
if (_primaryHoveredLastFrame != null) _primaryHoverEndedObject = _primaryHoveredLastFrame;
else _primaryHoverEndedObject = null;
_primaryHoveredLastFrame = primaryHoveredObject;
if (_primaryHoveredLastFrame != null) _primaryHoverBeganObject = _primaryHoveredLastFrame;
else _primaryHoverBeganObject = null;
}
else {
_primaryHoverEndedObject = null;
_primaryHoverBeganObject = null;
}
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Returns whether an object stopped being primarily hovered by this hand this frame and, if so,
/// outputs the object into primaryHoverEndedObject (it will be null otherwise).
/// </summary>
bool IInternalInteractionController.CheckPrimaryHoverEnd(out IInteractionBehaviour primaryHoverEndedObject) {
primaryHoverEndedObject = _primaryHoverEndedObject;
bool primaryHoverEnded = primaryHoverEndedObject != null;
if (primaryHoverEnded && _primaryHoverEndedObject is InteractionBehaviour) {
OnEndPrimaryHoveringObject(_primaryHoverEndedObject as InteractionBehaviour);
}
return primaryHoverEnded;
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Returns whether an object began being primarily hovered by this hand this frame and, if so,
/// outputs the object into primaryHoverBeganObject (it will be null otherwise).
/// </summary>
bool IInternalInteractionController.CheckPrimaryHoverBegin(out IInteractionBehaviour primaryHoverBeganObject) {
primaryHoverBeganObject = _primaryHoverBeganObject;
bool primaryHoverBegan = primaryHoverBeganObject != null;
if (primaryHoverBegan && _primaryHoverBeganObject is InteractionBehaviour) {
OnBeginPrimaryHoveringObject(_primaryHoverBeganObject as InteractionBehaviour);
}
return primaryHoverBegan;
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Returns whether any object is the primary hover of this hand and, if so, outputs
/// the object into primaryHoveredObject.
/// </summary>
bool IInternalInteractionController.CheckPrimaryHoverStay(out IInteractionBehaviour primaryHoveredObject) {
primaryHoveredObject = _primaryHoveredObject;
bool primaryHoverStayed = primaryHoveredObject != null;
if (primaryHoverStayed && primaryHoveredObject is InteractionBehaviour) {
OnStayPrimaryHoveringObject(primaryHoveredObject as InteractionBehaviour);
}
return primaryHoverStayed;
}
#endregion
/// <summary>
/// Returns the hover distance from the hoverPoint to the specified object, automatically
/// accounting for ISpaceComponent warping if necessary.
/// </summary>
public static float GetHoverDistance(Vector3 hoverPoint, IInteractionBehaviour behaviour) {
if (behaviour.space != null) {
return behaviour.GetHoverDistance(TransformPoint(hoverPoint, behaviour.space));
}
else {
return behaviour.GetHoverDistance(hoverPoint);
}
}
/// <summary>
/// Applies the spatial warping of the provided ISpaceComponent to a world-space point.
/// </summary>
public static Vector3 TransformPoint(Vector3 worldPoint, ISpaceComponent element) {
if (element.anchor != null && element.anchor.space != null) {
Vector3 localPos = element.anchor.space.transform.InverseTransformPoint(worldPoint);
return element.anchor.space.transform.TransformPoint(element.anchor.transformer.InverseTransformPoint(localPos));
}
else {
return worldPoint;
}
}
#endregion
#region Contact
/// <summary>
/// Gets the set of interaction objects that are currently touching this
/// interaction controller.
/// </summary>
public ReadonlyHashSet<IInteractionBehaviour> contactingObjects { get { return _contactBehavioursSet; } }
#region Contact Bones
protected const float DEAD_ZONE_FRACTION = 0.04F;
private float _softContactDislocationDistance = 0.03F;
protected float softContactDislocationDistance {
get { return _softContactDislocationDistance; }
set { _softContactDislocationDistance = value; }
}
private static PhysicMaterial s_defaultContactBoneMaterial;
protected static PhysicMaterial defaultContactBoneMaterial {
get {
if (s_defaultContactBoneMaterial == null) {
initDefaultContactBoneMaterial();
}
return s_defaultContactBoneMaterial;
}
}
/// <summary>
/// ContactBones should have PhysicMaterials with a bounciness of
/// zero and a bounce combine set to minimum.
/// </summary>
private static void initDefaultContactBoneMaterial() {
if (s_defaultContactBoneMaterial == null) {
s_defaultContactBoneMaterial = new PhysicMaterial();
}
s_defaultContactBoneMaterial.hideFlags = HideFlags.HideAndDontSave;
s_defaultContactBoneMaterial.bounceCombine = PhysicMaterialCombine.Minimum;
s_defaultContactBoneMaterial.bounciness = 0F;
}
private bool _contactInitialized = false;
protected bool _wasContactInitialized { get { return _contactInitialized; } }
public abstract ContactBone[] contactBones { get; }
protected abstract GameObject contactBoneParent { get; }
protected float lastObjectTouchedAdjustedMassMass = 0.2f;
private Vector3[] _boneTargetPositions;
private Quaternion[] _boneTargetRotations;
/// <summary>
/// Called to initialize contact colliders. See remarks for implementation
/// requirements.
/// </summary>
/// <remarks>
/// initContact() should:
/// - Return false at any time if initialization cannot be performed.
/// - Ensure the "contactBones" property returns all contact colliders.
/// - (Construct contact colliders if they don't already exist.)
/// - Ensure the "contactBoneParent" property returns the common parent of all
/// contact colliders.
/// - (Construct the contact bone parent if it doesn't already exist.)
/// - Return true if initialization was successful.
///
/// Contact will only begin updating after initialization succeeds, otherwise
/// it will try to initialize again on the next fixed frame.
///
/// After initialization, the contact bone parent's layer will be set to
/// the Interaction Manager's contactBoneLayer.
/// </remarks>
protected abstract bool initContact();
private void finishInitContact() {
contactBoneParent.layer = manager.contactBoneLayer;
contactBoneParent.transform.parent = manager.transform;
var comment = contactBoneParent.GetComponent<ContactBoneParent>();
if (comment == null) {
comment = contactBoneParent.AddComponent<ContactBoneParent>();
}
comment.controller = this;
foreach (var contactBone in contactBones) {
contactBone.rigidbody.maxAngularVelocity = 30F;
contactBone.gameObject.layer = manager.contactBoneLayer;
}
_boneTargetPositions = new Vector3[contactBones.Length];
_boneTargetRotations = new Quaternion[contactBones.Length];
}
private void fixedUpdateContact() {
// Make sure contact data is initialized.
if (!_contactInitialized) {
if (initContact()) {
finishInitContact();
_contactInitialized = true;
if (OnContactInitialized != null) OnContactInitialized(this);
}
else {
return;
}
}
// Clear contact data if we lose tracking.
if (!isTracked && _contactBehaviours.Count > 0) {
_contactBehaviours.Clear();
// Also clear soft contact state if tracking is lost.
_softContactCollisions.Clear();
}
// Disable contact bone parent if we lose tracking.
if (!isTracked) {
contactBoneParent.SetActive(false);
return;
}
else {
if (!contactBoneParent.activeSelf) {
contactBoneParent.SetActive(true);
}
}
// Request and store target bone positions and rotations
// for use during the contact update.
using (new ProfilerSample("Update Contact Bone Targets")) {
for (int i = 0; i < contactBones.Length; i++) {
getColliderBoneTargetPositionRotation(i, out _boneTargetPositions[i],
out _boneTargetRotations[i]);
}
}
using (new ProfilerSample("Update Contact Bones")) {
normalizeBoneMasses();
for (int i = 0; i < contactBones.Length; i++) {
updateContactBone(i, _boneTargetPositions[i], _boneTargetRotations[i]);
}
}
using (new ProfilerSample("Update Soft Contact")) {
fixedUpdateSoftContact();
}
using (new ProfilerSample("Update Contact Callbacks")) {
fixedUpdateContactState();
}
}
/// <summary>
/// If your controller features no moving colliders relative to itself, simply
/// return the desired position and rotation for the given indexed contact bone
/// in the contactBones array. (For example, by recording the local position and
/// local rotation of each contact bone in initContact()). More complex controllers,
/// such as InteractionHand, uses this method to set ContactBone target positions and
/// rotations based on the tracked Leap hand.
/// </summary>
protected abstract void getColliderBoneTargetPositionRotation(int contactBoneIndex,
out Vector3 targetPosition,
out Quaternion targetRotation);
private void normalizeBoneMasses() {
//If any of the contact bones have contacted an object that the others have not
//Propagate that change in mass to the rest of the bones in the hand
float tempAdjustedMass = lastObjectTouchedAdjustedMassMass;
for (int i = 0; i < contactBones.Length; i++) {
if (contactBones[i]._lastObjectTouchedAdjustedMass != tempAdjustedMass) {
tempAdjustedMass = contactBones[i]._lastObjectTouchedAdjustedMass;
for (int j = 0; j < contactBones.Length; j++) {
contactBones[j]._lastObjectTouchedAdjustedMass = tempAdjustedMass;
}
break;
}
}
lastObjectTouchedAdjustedMassMass = tempAdjustedMass;
}
private void updateContactBone(int contactBoneIndex, Vector3 targetPosition, Quaternion targetRotation) {
ContactBone contactBone = contactBones[contactBoneIndex];
Rigidbody body = contactBone.rigidbody;
// Infer ahead if the Interaction Manager has a moving frame of reference.
//manager.TransformAheadByFixedUpdate(targetPosition, targetRotation, out targetPosition, out targetRotation);
// Set a fixed rotation for bones; otherwise most friction is lost
// as any capsule or spherical bones will roll on contact.
using (new ProfilerSample("updateContactBone: MoveRotation")) {
body.MoveRotation(targetRotation);
}
// Calculate how far off its target the contact bone is.
float errorDistance = 0f;
float errorFraction = 0f;
using (new ProfilerSample("updateContactBone: errorDistance, errorFraction")) {
Vector3 lastTargetPositionTransformedAhead = contactBone.lastTargetPosition;
if (manager.hasMovingFrameOfReference) {
manager.TransformAheadByFixedUpdate(contactBone.lastTargetPosition, out lastTargetPositionTransformedAhead);
}
errorDistance = Vector3.Distance(lastTargetPositionTransformedAhead, body.position);
errorFraction = errorDistance / contactBone.width;
}
// Adjust the mass of the contact bone based on the mass of
// the object it is currently touching.
float speed = 0f;
using (new ProfilerSample("updateContactBone: speed & massScale")) {
speed = velocity.magnitude;
float massScale = Mathf.Clamp(1.0F - (errorFraction * 2.0F), 0.1F, 1.0F)
* Mathf.Clamp(speed * 10F, 1F, 10F);
body.mass = massScale * contactBone._lastObjectTouchedAdjustedMass;
}
// Potentially enable Soft Contact if our error is too large.
using (new ProfilerSample("updateContactBone: maybe enable Soft Contact")) {
if (!_softContactEnabled && errorDistance >= softContactDislocationDistance
&& speed < 1.5F
/* && boneArrayIndex != NUM_FINGERS * BONES_PER_FINGER */) {
EnableSoftContact();
}
}
// Attempt to move the contact bone to its target position and rotation
// by setting its target velocity and angular velocity. Include a "deadzone"
// for position to avoid tiny vibrations.
using (new ProfilerSample("updateContactBone: Move to target, with deadzone")) {
float deadzone = Mathf.Min(DEAD_ZONE_FRACTION * contactBone.width, 0.01F * scale);
Vector3 delta = (targetPosition - body.position);
float deltaMag = delta.magnitude;
if (deltaMag <= deadzone) {
body.velocity = Vector3.zero;
contactBone.lastTargetPosition = body.position;
}
else {
delta *= (deltaMag - deadzone) / deltaMag;
contactBone.lastTargetPosition = body.position + delta;
Vector3 targetVelocity = delta / Time.fixedDeltaTime;
float targetVelocityMag = targetVelocity.magnitude;
body.velocity = (targetVelocity / targetVelocityMag)
* Mathf.Clamp(targetVelocityMag, 0F, 100F);
}
Quaternion deltaRot = targetRotation * Quaternion.Inverse(body.rotation);
body.angularVelocity = PhysicsUtility.ToAngularVelocity(deltaRot, Time.fixedDeltaTime);
}
}
#endregion
#region Soft Contact
private bool _softContactEnabled = false;
public bool softContactEnabled { get { return _softContactEnabled; } }
private bool _disableSoftContactEnqueued = false;
private IEnumerator _delayedDisableSoftContactCoroutine;
private Collider[] _softContactColliderBuffer = new Collider[32];
private bool _notTrackedLastFrame = true;
private void fixedUpdateSoftContact() {
if (!isTracked) {
_notTrackedLastFrame = true;
return;
}
else {
// If the hand was just initialized, initialize with soft contact.
if (_notTrackedLastFrame) {
EnableSoftContact();
}
_notTrackedLastFrame = false;
}
if (_softContactEnabled) {
foreach (var contactBone in contactBones) {
#if UNITY_ANDROID
//for(int i = 0; i < _softContactColliderBuffer.Length; i++) {
// _softContactColliderBuffer[i] = null;
//}
// HACK: assume only using hands on android
// TODO: This probably doesn't take into accoutn ignoreContact settings
PhysicsUtility.generateSphereContacts(contactBone.rigidbody.position,
0.02f * manager.SimulationScale,
contactBone.rigidbody.velocity,
manager.interactionLayer.layerMask,
ref manager._softContacts,
ref manager._softContactOriginalVelocities,
ref _softContactColliderBuffer);
//for (int i = 0; i < _softContactColliderBuffer.Length; i++) {
// if (_softContactColliderBuffer[i] != null) {
// NotifySoftContactOverlap(contactBone, _softContactColliderBuffer[i]);
// }
//}
#else
Collider contactBoneCollider = contactBone.collider;
if (contactBoneCollider is SphereCollider) {
var boneSphere = contactBoneCollider as SphereCollider;
int numCollisions = Physics.OverlapSphereNonAlloc(contactBone.transform.TransformPoint(boneSphere.center),
contactBone.transform.lossyScale.x * boneSphere.radius,
_softContactColliderBuffer,
manager.GetInteractionLayerMask(),
QueryTriggerInteraction.Ignore);
for (int i = 0; i < numCollisions; i++) {
//NotifySoftContactOverlap(contactBone, _softContactColliderBuffer[i]);
// If the rigidbody is null, the object may have been destroyed.
if (_softContactColliderBuffer[i].attachedRigidbody == null) continue;
IInteractionBehaviour intObj;
if (manager.interactionObjectBodies.TryGetValue(_softContactColliderBuffer[i].attachedRigidbody, out intObj)) {
// Skip soft contact if the object is ignoring contact.
if (intObj.ignoreContact) continue;
if (intObj.isGrasped) continue;
}
PhysicsUtility.generateSphereContact(boneSphere, 0, _softContactColliderBuffer[i],
ref manager._softContacts,
ref manager._softContactOriginalVelocities);
}
}
else if (contactBoneCollider is CapsuleCollider) {
var boneCapsule = contactBoneCollider as CapsuleCollider;
Vector3 point0, point1;
boneCapsule.GetCapsulePoints(out point0, out point1);
int numCollisions = Physics.OverlapCapsuleNonAlloc(point0, point1,
contactBone.transform.lossyScale.x * boneCapsule.radius,
_softContactColliderBuffer,
manager.GetInteractionLayerMask(),
QueryTriggerInteraction.Ignore);
for (int i = 0; i < numCollisions; i++) {
//NotifySoftContactOverlap(contactBone, _softContactColliderBuffer[i]);
// If the rigidbody is null, the object may have been destroyed.
if (_softContactColliderBuffer[i].attachedRigidbody == null) continue;
IInteractionBehaviour intObj;
if (manager.interactionObjectBodies.TryGetValue(_softContactColliderBuffer[i].attachedRigidbody, out intObj)) {
// Skip soft contact if the object is ignoring contact.
if (intObj.ignoreContact) continue;
if (intObj.isGrasped) continue;
}
PhysicsUtility.generateCapsuleContact(boneCapsule, 0,
_softContactColliderBuffer[i],
ref manager._softContacts,
ref manager._softContactOriginalVelocities);
}
}
else {
var boneBox = contactBoneCollider as BoxCollider;
if (boneBox == null) {
Debug.LogError("Unsupported collider type in ContactBone. Supported "
+ "types are SphereCollider, CapsuleCollider, and "
+ "BoxCollider.", this);
continue;
}
int numCollisions = Physics.OverlapBoxNonAlloc(boneBox.transform.TransformPoint(boneBox.center),
Vector3.Scale(boneBox.size * 0.5F, contactBone.transform.lossyScale),
_softContactColliderBuffer,
boneBox.transform.rotation,
manager.GetInteractionLayerMask(),
QueryTriggerInteraction.Ignore);
for (int i = 0; i < numCollisions; i++) {
//NotifySoftContactOverlap(contactBone, _softContactColliderBuffer[i]);
// If the rigidbody is null, the object may have been destroyed.
if (_softContactColliderBuffer[i].attachedRigidbody == null) continue;
IInteractionBehaviour intObj;
if (manager.interactionObjectBodies.TryGetValue(_softContactColliderBuffer[i].attachedRigidbody, out intObj)) {
// Skip soft contact if the object is ignoring contact.
if (intObj.ignoreContact) continue;
if (intObj.isGrasped) continue;
}
PhysicsUtility.generateBoxContact(boneBox, 0, _softContactColliderBuffer[i],
ref manager._softContacts,
ref manager._softContactOriginalVelocities);
}
}
#endif
}
// TODO: Implement me to replace trigger colliders
//FinishSoftContactOverlapChecks();
//for (int i = 0; i < contactBones.Length; i++) {
// Vector3 bonePosition = _boneTargetPositions[i];
// Quaternion boneRotation = _boneTargetRotations[i];
// Generate soft contact data based on spheres at each bonePosition
// of radius softContactBoneRadius.
// bool sphereIntersecting;
// using (new ProfilerSample("Generate Soft Contacts")) {
// sphereIntersecting = PhysicsUtility.generateSphereContacts(bonePosition,
// _softContactBoneRadius,
// (bonePosition - _bonePositionsLastFrame[i]) / Time.fixedDeltaTime,
// 1 << manager.interactionLayer,
// ref manager._softContacts,
// ref manager._softContactOriginalVelocities,
// ref _tempColliderArray);
// }
// _bonePositionsLastFrame[i] = bonePosition;
// softlyContacting = sphereIntersecting ? true : softlyContacting;
//}
if (_softContactCollisions.Count > 0) {
_disableSoftContactEnqueued = false;
if (_delayedDisableSoftContactCoroutine != null) {
manager.StopCoroutine(_delayedDisableSoftContactCoroutine);
}
}
else {
// If there are no detected Contacts, exit soft contact mode.
DisableSoftContact();
}
}
}
/// <summary>
/// Optionally override this method to perform logic just before soft contact
/// is enabled for this controller.
///
/// The InteractionHand implementation takes the opportunity to reset its contact
/// bone's joints, which may have initialized slightly out of alignment on initial
/// construction.
/// </summary>
protected virtual void onPreEnableSoftContact() { }
/// <summary>
/// Optionally override this method to perform logic just after soft contact
/// is disabled for this controller.
///
/// The InteractionHand implementation takes the opportunity to reset its contact
/// bone's joints, which my have initialized slightly out of alignment on initial
/// construction.
/// </summary>
protected virtual void onPostDisableSoftContact() { }
public void EnableSoftContact() {
if (!isTracked) return;
using (new ProfilerSample("Enable Soft Contact")) {
_disableSoftContactEnqueued = false;
if (!_softContactEnabled) {
onPreEnableSoftContact();
_softContactEnabled = true;
if (_delayedDisableSoftContactCoroutine != null) {
manager.StopCoroutine(_delayedDisableSoftContactCoroutine);
}
if (contactBones != null) {
for (int i = 0; i < contactBones.Length; i++) {
if (contactBones[i].collider == null) continue;
disableContactBoneCollision();
}
}
}
}
}
public void DisableSoftContact() {
using (new ProfilerSample("Enqueue Disable Soft Contact")) {
if (!_disableSoftContactEnqueued) {
_delayedDisableSoftContactCoroutine = DelayedDisableSoftContact();
manager.StartCoroutine(_delayedDisableSoftContactCoroutine);
_disableSoftContactEnqueued = true;
}
}
}
private IEnumerator DelayedDisableSoftContact() {
yield return new WaitForSecondsRealtime(0.3f);
if (_disableSoftContactEnqueued) {
using (new ProfilerSample("Disable Soft Contact")) {
_softContactEnabled = false;
for (int i = 0; i < contactBones.Length; i++) {
enableContactBoneCollision();
}
onPostDisableSoftContact();
}
}
}
#region Soft Contact Collision Tracking
/*
// TODO: Make this a thing so we aren't using triggers
private void NotifySoftContactOverlap(ContactBone contactBone, Collider otherCollider) {
}
// TODO: Make this a thing so we aren't using triggers
private void FinishSoftContactOverlapChecks() {
}*/
// TODO: Maintaining a reference to the interaction object doesn't appear to be
// necessary here, so get rid of the Pair class as a small optimization
private Dictionary<BoneIntObjPair, HashSet<Collider>> _softContactCollisions = new Dictionary<BoneIntObjPair, HashSet<Collider>>();
private struct BoneIntObjPair : IEquatable<BoneIntObjPair> {
public ContactBone bone;
public IInteractionBehaviour intObj;
public override bool Equals(object obj) {
return obj is BoneIntObjPair && this == (BoneIntObjPair)obj;
}
public bool Equals(BoneIntObjPair other) {
return this == other;
}
public static bool operator !=(BoneIntObjPair one, BoneIntObjPair other) {
return !(one == other);
}
public static bool operator ==(BoneIntObjPair one, BoneIntObjPair other) {
return one.bone == other.bone && one.intObj == other.intObj;
}
public override int GetHashCode() {
return bone.GetHashCode() ^ intObj.GetHashCode();
}
}
public void NotifySoftContactCollisionEnter(ContactBone bone,
IInteractionBehaviour intObj,
Collider collider) {
var pair = new BoneIntObjPair() { bone = bone, intObj = intObj };
if (!_softContactCollisions.ContainsKey(pair)) {
_softContactCollisions[pair] = new HashSet<Collider>();
}
_softContactCollisions[pair].Add(collider);
}
public void NotifySoftContactCollisionExit(ContactBone bone,
IInteractionBehaviour intObj,
Collider collider) {
var pair = new BoneIntObjPair() { bone = bone, intObj = intObj };
if (!_softContactCollisions.ContainsKey(pair)) {
Debug.LogError("No collision set found for this pair of collisions; Exit method "
+ "was called without a prior, corresponding Enter method!", this);
}
_softContactCollisions[pair].Remove(collider);
if (_softContactCollisions[pair].Count == 0) {
_softContactCollisions.Remove(pair);
}
}
#endregion
#endregion
#region Contact Callbacks
private HashSet<IInteractionBehaviour> _contactBehavioursSet = new HashSet<IInteractionBehaviour>();
private Dictionary<IInteractionBehaviour, int> _contactBehaviours = new Dictionary<IInteractionBehaviour, int>();
private HashSet<IInteractionBehaviour> _contactBehavioursLastFrame = new HashSet<IInteractionBehaviour>();
private List<IInteractionBehaviour> _contactBehaviourRemovalCache = new List<IInteractionBehaviour>();
private HashSet<IInteractionBehaviour> _contactEndedBuffer = new HashSet<IInteractionBehaviour>();
private HashSet<IInteractionBehaviour> _contactBeganBuffer = new HashSet<IInteractionBehaviour>();
public void NotifyContactBoneCollisionEnter(ContactBone contactBone, IInteractionBehaviour interactionObj) {
int count;
if (_contactBehaviours.TryGetValue(interactionObj, out count)) {
_contactBehaviours[interactionObj] = count + 1;
}
else {
_contactBehaviours[interactionObj] = 1;
_contactBehavioursSet.Add(interactionObj);
}
}
public void NotifyContactBoneCollisionStay(ContactBone contactBone, IInteractionBehaviour interactionObj) {
// If Contact state is cleared manually or due to the controller being disabled,
// it will be restored here.
int count;
if (!_contactBehaviours.TryGetValue(interactionObj, out count)) {
_contactBehaviours[interactionObj] = 1;
_contactBehavioursSet.Add(interactionObj);
}
}
public void NotifyContactBoneCollisionExit(ContactBone contactBone, IInteractionBehaviour interactionObj) {
if (interactionObj.ignoreContact) {
if (_contactBehaviours.ContainsKey(interactionObj)) _contactBehaviours.Remove(interactionObj);
return;
}
// Sometimes when the controller is disabled and re-enabled, we might be missing the
// key in the dictionary already.
if (!_contactBehaviours.ContainsKey(interactionObj)) return;
int count = _contactBehaviours[interactionObj];
if (count == 1) {
_contactBehaviours.Remove(interactionObj);
_contactBehavioursSet.Remove(interactionObj);
}
else {
_contactBehaviours[interactionObj] = count - 1;
}
}
/// <summary>
/// Clears contact state for this controller and fires the appropriate ContactEnd
/// callbacks on currently-contacted interaction objects immediately.
///
/// If the controller is still contacting objects and it and its manager are still
/// active, contact will begin anew on the next fixed frame.
/// </summary>
public void ClearContactTracking() {
_controllerListBuffer.Clear();
_controllerListBuffer.Add(this);
var tempObjs = Pool<HashSet<IInteractionBehaviour>>.Spawn();
try {
foreach (var intObj in contactingObjects) {
tempObjs.Add(intObj);
}
foreach (var intObj in tempObjs) {
_contactBehavioursSet.Remove(intObj);
_contactBehaviours.Remove(intObj);
_contactBehavioursLastFrame.Remove(intObj);
intObj.EndContact(_controllerListBuffer);
}
}
finally {
Pool<HashSet<IInteractionBehaviour>>.Recycle(tempObjs);
}
}
/// <summary>
/// Clears contact state for the specified object and fires its ContactEnd callbacks
/// immediately.
///
/// If the controller is still contacting the object and it and its manager are still
/// active, contact will begin anew on the next fixed frame.
/// </summary>
public void ClearContactTrackingForObject(IInteractionBehaviour intObj) {
if (!contactingObjects.Contains(intObj)) return;
_contactBehavioursSet.Remove(intObj);
_contactBehaviours.Remove(intObj);
_contactBehavioursLastFrame.Remove(intObj);
_controllerListBuffer.Clear();
_controllerListBuffer.Add(this);
intObj.EndContact(_controllerListBuffer);
}
/// <summary>
/// Called as a part of the Interaction Hand's general fixed frame update,
/// before any specific-callback-related updates.
/// </summary>
private void fixedUpdateContactState() {
_contactEndedBuffer.Clear();
_contactBeganBuffer.Clear();
// Update contact ended state.
_contactBehaviourRemovalCache.Clear();
foreach (var interactionObj in _contactBehavioursLastFrame) {
if (!_contactBehaviours.ContainsKey(interactionObj)
|| !contactBoneParent.activeInHierarchy
/* || !contactEnabled TODO: Use properties to support disabling contact at runtime! */) {
_contactEndedBuffer.Add(interactionObj);
_contactBehaviourRemovalCache.Add(interactionObj);
}
}
foreach (var interactionObj in _contactBehaviourRemovalCache) {
_contactBehavioursLastFrame.Remove(interactionObj);
}
// Update contact began state.
if (contactBoneParent.activeInHierarchy /* && contactEnabled TODO: can this just be removed cleanly?*/) {
foreach (var intObjCountPair in _contactBehaviours) {
var interactionObj = intObjCountPair.Key;
if (!_contactBehavioursLastFrame.Contains(interactionObj)) {
_contactBeganBuffer.Add(interactionObj);
_contactBehavioursLastFrame.Add(interactionObj);
}
}
}
}
private List<IInteractionBehaviour> _removeContactObjsBuffer = new List<IInteractionBehaviour>();
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Outputs interaction objects that stopped being touched by this hand this frame into contactEndedObjects
/// and returns whether the output set is empty.
/// </summary>
bool IInternalInteractionController.CheckContactEnd(out HashSet<IInteractionBehaviour> contactEndedObjects) {
// Ensure contact objects haven't been destroyed or set to ignore contact
_removeContactObjsBuffer.Clear();
foreach (var objTouchCountPair in _contactBehaviours) {
if (objTouchCountPair.Key.gameObject == null
|| objTouchCountPair.Key.rigidbody == null
|| objTouchCountPair.Key.ignoreContact
|| !isTracked) {
_removeContactObjsBuffer.Add(objTouchCountPair.Key);
}
}
// Clean out removed, invalid, or ignoring-contact objects
foreach (var intObj in _removeContactObjsBuffer) {
_contactBehaviours.Remove(intObj);
_contactEndedBuffer.Add(intObj);
}
contactEndedObjects = _contactEndedBuffer;
return _contactEndedBuffer.Count > 0;
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Outputs interaction objects that started being touched by this hand this frame into contactBeganObjects
/// and returns whether the output set is empty.
/// </summary>
bool IInternalInteractionController.CheckContactBegin(out HashSet<IInteractionBehaviour> contactBeganObjects) {
contactBeganObjects = _contactBeganBuffer;
return _contactBeganBuffer.Count > 0;
}
private HashSet<IInteractionBehaviour> _contactedObjects = new HashSet<IInteractionBehaviour>();
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Outputs interaction objects that are currently being touched by the hand into contactedObjects
/// and returns whether the output set is empty.
/// </summary>
bool IInternalInteractionController.CheckContactStay(out HashSet<IInteractionBehaviour> contactedObjects) {
_contactedObjects.Clear();
foreach (var objCountPair in _contactBehaviours) {
_contactedObjects.Add(objCountPair.Key);
}
contactedObjects = _contactedObjects;
return contactedObjects.Count > 0;
}
#endregion
private void disableContactBoneCollision() {
foreach (var contactBone in contactBones) {
contactBone.collider.isTrigger = true;
}
}
private void enableContactBoneCollision() {
foreach (var contactBone in contactBones) {
contactBone.collider.isTrigger = false;
}
}
private void resetContactBonePose() {
int index = 0;
foreach (var contactBone in contactBones) {
Vector3 position;
Quaternion rotation;
getColliderBoneTargetPositionRotation(index++, out position, out rotation);
contactBone.rigidbody.position = position;
contactBone.rigidbody.rotation = rotation;
contactBone.rigidbody.velocity = Vector3.zero;
contactBone.rigidbody.angularVelocity = Vector3.zero;
}
}
#endregion
#region Grasping
/// <summary> Gets whether the controller is currently grasping an object. </summary>
public bool isGraspingObject { get { return _graspedObject != null; } }
/// <summary> Gets the object the controller is currently grasping, or null if there is no such object. </summary>
public IInteractionBehaviour graspedObject { get { return _graspedObject; } }
/// <summary> Gets the set of objects currently considered graspable. </summary>
public ReadonlyHashSet<IInteractionBehaviour> graspCandidates { get { return graspActivityManager.ActiveObjects; } }
/// <summary>
/// Gets the points of the controller to add to the calculation to determine how
/// held objects should move as the controller moves. Interaction Controllers utilize
/// the Kabsch algorithm to determine this, which is most noticeable when using
/// Leap hands via InteractionHands to manipulate held objects. Rigid controllers
/// may simply return a single rigid point on the controller. Refer to InteractionHand
/// for a reference implementation for dynamic controllers (e.g. hands).
/// </summary>
public abstract List<Vector3> graspManipulatorPoints { get; }
/// <summary>
/// Returns approximately where the controller is grasping the currently grasped
/// InteractionBehaviour.
/// This method will print an error if the controller is not currently grasping an object.
/// </summary>
public abstract Vector3 GetGraspPoint();
/// <summary>
/// Checks if the provided interaction object can be grasped by this interaction
/// controller in its current state. If so, the controller will initiate a grasp and
/// this method will return true, otherwise this method returns false.
/// </summary>
public bool TryGrasp(IInteractionBehaviour intObj) {
if (checkShouldGraspAtemporal(intObj)) {
_graspedObject = intObj;
OnGraspBegin();
return true;
}
return false;
}
/// <summary>
/// Seamlessly swap the currently grasped object for a replacement object. It will
/// behave like the hand released the current object, and then grasped the new object.
///
/// This method will not teleport the replacement object or move it in any way, it will
/// just cause it to be grasped. That means that you will be responsible for moving
/// the replacement object into a reasonable position for it to be grasped.
/// </summary>
public virtual void SwapGrasp(IInteractionBehaviour replacement) {
if (_graspedObject == null) {
throw new InvalidOperationException("Cannot swap grasp if we are not currently grasping.");
}
if (replacement == null) {
throw new ArgumentNullException("The replacement object is null!");
}
if (replacement.isGrasped && !replacement.allowMultiGrasp) {
throw new InvalidOperationException("Cannot swap grasp if the replacement object is already grasped and does not support multi grasp.");
}
//Notify the currently grasped object that it is being released
_releasingControllersBuffer.Clear();
_releasingControllersBuffer.Add(this);
_graspedObject.EndGrasp(_releasingControllersBuffer);
OnGraspEnd();
//Switch to the replacement object
_graspedObject = replacement;
var tempControllers = Pool<List<InteractionController>>.Spawn();
try {
//Let the replacement object know that it is being grasped
tempControllers.Add(this);
replacement.BeginGrasp(tempControllers);
OnGraspBegin();
}
finally {
tempControllers.Clear();
Pool<List<InteractionController>>.Recycle(tempControllers);
}
}
/// <summary>
/// Checks if the provided interaction object can be grasped by this interaction
/// controller in its current state. If so, the controller will initiate a grasp and
/// this method will return true, otherwise this method returns false.
///
/// This method is useful if the controller requires conditions to initiate a grasp
/// that differ from the conditions necessary to maintain a grasp after it has been
/// initiated. This method allows a grasp to occur if certain initiation conditions
/// are not met, such as the motion of a hand's fingers towards the palm,
/// but if the grasp holding conditions are met, such as the penetration of a hand's
/// fingers inside the interaction object.
/// </summary>
protected abstract bool checkShouldGraspAtemporal(IInteractionBehaviour intObj);
private Func<Collider, IInteractionBehaviour> graspActivityFilter;
private IInteractionBehaviour graspFilterFunc(Collider collider) {
Rigidbody body = collider.attachedRigidbody;
IInteractionBehaviour intObj = null;
bool validForGrasping = body != null
&& manager.interactionObjectBodies.TryGetValue(body, out intObj)
&& !intObj.ignoreGrasping;
if (validForGrasping) return intObj;
return null;
}
// Layer mask for the hover acitivity manager.
private Func<int> graspLayerMaskAccessor;
// Grasp Activity Manager
private ActivityManager<IInteractionBehaviour> _graspActivityManager;
/// <summary> Determines which objects are graspable any given frame. </summary>
private ActivityManager<IInteractionBehaviour> graspActivityManager {
get {
if (_graspActivityManager == null) {
if (graspActivityFilter == null) graspActivityFilter = graspFilterFunc;
if (graspLayerMaskAccessor == null) graspLayerMaskAccessor = manager.GetInteractionLayerMask;
_graspActivityManager = new ActivityManager<IInteractionBehaviour>(1F, graspActivityFilter);
_graspActivityManager.activationLayerFunction = graspLayerMaskAccessor;
}
return _graspActivityManager;
}
}
private IInteractionBehaviour _graspedObject = null;
private void fixedUpdateGrasping() {
using (new ProfilerSample("Fixed Update Controller Grasping")) {
Vector3? graspPoint = isTracked ? (Vector3?)hoverPoint : null;
graspActivityManager.UpdateActivityQuery(graspPoint, LeapSpace.allEnabled);
fixedUpdateGraspingState();
}
}
/// <summary>
/// Called every fixed frame if grasping is enabled in the Interaction Manager.
///
/// graspActivityManager.ActiveObjects will contain objects around the hoverPoint
/// within the grasping radius -- in other words, objects eligible to be grasped
/// by the controller. Refer to it to avoid checking grasp eligibility against all
/// graspable objects in your scene.
/// </summary>
protected abstract void fixedUpdateGraspingState();
/// <summary>
/// Optionally override this method to perform logic just before a grasped object is
/// released because it is no longer eligible to be grasped by this controller or
/// ReleaseGrasp() was manually called on the controller.
/// </summary>
protected virtual void onGraspedObjectForciblyReleased(IInteractionBehaviour objectToBeReleased) { }
/// <summary>
/// Returns whether this controller should grasp an object this fixed frame, and if so,
/// sets objectToGrasp to the object the controller should grasp.
/// </summary>
protected abstract bool checkShouldGrasp(out IInteractionBehaviour objectToGrasp);
/// <summary>
/// Returns whether this controller should release an object this fixed frame, and if so,
/// sets objectToRelease to the object the controller should release.
/// </summary>
protected abstract bool checkShouldRelease(out IInteractionBehaviour objectToRelease);
private List<InteractionController> _releasingControllersBuffer = new List<InteractionController>();
/// <summary>
/// Releases the object this hand is holding and returns true if the hand was holding an object,
/// or false if there was no object to release. The released object will dispatch OnGraspEnd()
/// immediately. The hand is guaranteed not to be holding an object directly after this method
/// is called.
/// </summary>
public bool ReleaseGrasp() {
if (_graspedObject == null) {
return false;
}
else {
// Release this controller's grasp.
_releasingControllersBuffer.Clear();
_releasingControllersBuffer.Add(this);
// Calling things in the right order requires we remember the object we're
// releasing.
var tempGraspedObject = _graspedObject;
// Clear controller grasped object, and enable soft contact.
OnGraspEnd();
_graspedObject = null;
EnableSoftContact();
// Fire object's grasp-end callback.
tempGraspedObject.EndGrasp(_releasingControllersBuffer);
// The grasped object was forcibly released; some controllers hook into this
// by virtual method implementation.
onGraspedObjectForciblyReleased(tempGraspedObject);
return true;
}
}
/// <summary>
/// Helper static method for forcing multiple controllers to release their grasps
/// on a single object simultaneously. All of the provided controllers must be
/// grasping the argument interaction object.
/// </summary>
/// <details>
/// The input controllers List is copied to a temporary (pooled) buffer before
/// release operations are actually carried out. This prevents errors that might
/// arise from modifying a held-controllers list while enumerating through the same
/// list.
/// </details>
public static void ReleaseGrasps(IInteractionBehaviour graspedObj,
ReadonlyHashSet<InteractionController> controllers) {
var controllersBuffer = Pool<List<InteractionController>>.Spawn();
try {
foreach (var controller in controllers) {
if (controller.graspedObject != graspedObj) {
Debug.LogError("Argument intObj " + graspedObj.name + " is not held by "
+ "controller " + controller.name + "; skipping release for this "
+ "controller.");
continue;
}
controllersBuffer.Add(controller);
}
// Enable soft contact on releasing controllers, and clear grasp state.
// Note: controllersBuffer is iterated twice to preserve state modification order.
// For reference order, see InteractionController.ReleaseGrasp() above.
foreach (var controller in controllersBuffer) {
// Fire grasp end callback for the controller.
controller.OnGraspEnd();
// Clear grasped object state.
controller._graspedObject = null;
// Avoid "popping" of released objects by enabling soft contact on releasing
// controllers.
controller.EnableSoftContact();
}
// Evaluate object logic for being released by each controller.
graspedObj.EndGrasp(controllersBuffer);
// Object was forcibly released, so fire virtual callbacks on each controller.
foreach (var controller in controllersBuffer) {
controller.onGraspedObjectForciblyReleased(graspedObj);
}
}
finally {
controllersBuffer.Clear();
Pool<List<InteractionController>>.Recycle(controllersBuffer);
}
}
/// <summary>
/// As ReleaseGrasp(), but also outputs the released object into releasedObject if the hand
/// successfully released an object.
/// </summary>
public bool ReleaseGrasp(out IInteractionBehaviour releasedObject) {
releasedObject = _graspedObject;
if (ReleaseGrasp()) {
// releasedObject will be non-null
return true;
}
// releasedObject will be null
return false;
}
/// <summary>
/// Attempts to release this hand's object, but only if the argument object is the object currently
/// grasped by this hand. If the hand was holding the argument object, returns true, otherwise returns false.
/// </summary>
public bool ReleaseObject(IInteractionBehaviour toRelease) {
if (toRelease == null) return false;
if (_graspedObject == toRelease) {
ReleaseGrasp();
return true;
}
else {
return false;
}
}
#region Grasp State Checking
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Returns true if the hand just released an object and outputs the released object into releasedObject.
/// </summary>
bool IInternalInteractionController.CheckGraspEnd(out IInteractionBehaviour releasedObject) {
releasedObject = null;
bool shouldReleaseObject = false;
// Check releasing against interaction state.
if (_graspedObject == null) {
return false;
}
else if (_graspedObject.ignoreGrasping) {
onGraspedObjectForciblyReleased(_graspedObject);
releasedObject = _graspedObject;
shouldReleaseObject = true;
}
// Actually check whether the controller implementation will release its grasp.
if (!shouldReleaseObject) shouldReleaseObject = checkShouldRelease(out releasedObject);
if (shouldReleaseObject) {
OnGraspEnd();
_graspedObject = null;
EnableSoftContact(); // prevent objects popping out of the hand on release
return true;
}
return false;
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Returns true if the hand just grasped an object and outputs the grasped object into graspedObject.
/// </summary>
bool IInternalInteractionController.CheckGraspBegin(out IInteractionBehaviour newlyGraspedObject) {
newlyGraspedObject = null;
// Check grasping against interaction state.
if (_graspedObject != null) {
// Can't grasp any object if we're already grasping one or
// if grasping is disabled.
return false;
}
// Actually check whether the controller implementation will grasp.
bool shouldGraspObject = checkShouldGrasp(out newlyGraspedObject);
if (shouldGraspObject) {
_graspedObject = newlyGraspedObject;
OnGraspBegin();
return true;
}
return false;
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Returns whether there the hand is currently grasping an object and, if it is, outputs that
/// object into graspedObject.
/// </summary>
bool IInternalInteractionController.CheckGraspHold(out IInteractionBehaviour graspedObject) {
graspedObject = _graspedObject;
if (graspedObject != null) OnGraspStay();
return graspedObject != null;
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Returns whether the hand began suspending an object this frame and, if it did, outputs that
/// object into suspendedObject.
/// </summary>
bool IInternalInteractionController.CheckSuspensionBegin(out IInteractionBehaviour suspendedObject) {
suspendedObject = null;
if (_graspedObject != null && !isTracked && !_graspedObject.isSuspended) {
suspendedObject = _graspedObject;
}
return suspendedObject != null;
}
/// <summary>
/// Called by the Interaction Manager every fixed frame.
/// Returns whether the hand stopped suspending an object this frame and, if it did, outputs that
/// object into resumedObject.
/// </summary>
bool IInternalInteractionController.CheckSuspensionEnd(out IInteractionBehaviour resumedObject) {
resumedObject = null;
if (_graspedObject != null && isTracked && _graspedObject.isSuspended) {
resumedObject = _graspedObject;
}
return resumedObject != null;
}
#endregion
#endregion
#region Gizmos
public static class GizmoColors {
public static Color ContactBone { get { return Color.green.WithAlpha(0.5F); } }
public static Color SoftContactBone { get { return Color.white.WithAlpha(0.5F); } }
public static Color HoverPoint { get { return Color.yellow.WithAlpha(0.5F); } }
public static Color PrimaryHoverPoint { get { return Color.Lerp(Color.red, Color.yellow, 0.5F).WithAlpha(0.5F); } }
public static Color GraspPoint { get { return Color.Lerp(Color.blue, Color.cyan, 0.3F).WithAlpha(0.5F); } }
public static Color Graspable { get { return Color.cyan.WithAlpha(0.5F); } }
}
/// <summary>
/// By default, this method will draw all of the colliders found in the
/// contactBoneParent hierarchy, or draw the controller's soft contact
/// representation when in soft contact mode. Optionally override this
/// method to modify its behavior.
/// </summary>
public virtual void OnDrawRuntimeGizmos(RuntimeGizmoDrawer drawer) {
if (!this.isActiveAndEnabled) return;
if (contactBoneParent != null) {
if (!softContactEnabled) {
drawer.color = GizmoColors.ContactBone;
}
else {
drawer.color = GizmoColors.SoftContactBone;
}
drawer.DrawColliders(contactBoneParent, true, true, true);
}
// Hover Point
if (hoverEnabled) {
drawHoverPoint(drawer, hoverPoint);
}
// Primary Hover Points
if (hoverEnabled) {
foreach (var point in primaryHoverPoints) {
if (point == null) continue;
drawPrimaryHoverPoint(drawer, point.position);
}
}
}
protected static void drawHoverPoint(RuntimeGizmoDrawer drawer, Vector3 pos) {
drawer.color = GizmoColors.HoverPoint;
drawer.DrawWireSphere(pos, 0.03F);
}
protected static void drawPrimaryHoverPoint(RuntimeGizmoDrawer drawer, Vector3 pos) {
drawer.color = GizmoColors.PrimaryHoverPoint;
drawer.DrawWireSphere(pos, 0.015F);
}
#endregion
}
}
| 40.733333 | 144 | 0.661687 | [
"BSD-3-Clause"
] | HyperLethalVector/ChristmasEsky | Assets/Plugins/LeapMotion/Modules/InteractionEngine/Scripts/InteractionController.cs | 86,151 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Json;
using System.Threading.Tasks;
namespace IdentityModel.Client;
/// <summary>
/// Models an OAuth 2.0 introspection response
/// </summary>
/// <seealso cref="IdentityModel.Client.ProtocolResponse" />
public class TokenIntrospectionResponse : ProtocolResponse
{
/// <summary>
/// Allows to initialize instance specific data.
/// </summary>
/// <param name="initializationData">The initialization data.</param>
/// <returns></returns>
protected override Task InitializeAsync(object initializationData = null)
{
if (!IsError)
{
var issuer = Json.TryGetString("iss");
var claims = Json.ToClaims(issuer, "scope").ToList();
// due to a bug in identityserver - we need to be able to deal with the scope list both in array as well as space-separated list format
var scope = Json.TryGetValue("scope");
// scope element exists
// if (scope != null)
// {
// it's an array
if (scope.ValueKind == JsonValueKind.Array)
{
foreach (var item in scope.EnumerateArray())
{
claims.Add(new Claim("scope", item.ToString(), ClaimValueTypes.String, issuer));
}
}
else
{
// it's a string
var scopeString = scope.ToString();
var scopes = scopeString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var scopeValue in scopes)
{
claims.Add(new Claim("scope", scopeValue, ClaimValueTypes.String, issuer));
}
}
// }
Claims = claims;
}
else
{
Claims = Enumerable.Empty<Claim>();
}
return Task.CompletedTask;
}
/// <summary>
/// Gets a value indicating whether the token is active.
/// </summary>
/// <value>
/// <c>true</c> if the token is active; otherwise, <c>false</c>.
/// </value>
public bool IsActive => Json.TryGetBoolean("active").Value;
/// <summary>
/// Gets the claims.
/// </summary>
/// <value>
/// The claims.
/// </value>
public IEnumerable<Claim> Claims { get; protected set; }
} | 31.27381 | 147 | 0.56871 | [
"Apache-2.0"
] | AndreReise/IdentityModel | src/Client/Messages/TokenIntrospectionResponse.cs | 2,629 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices;
using Microsoft.PowerShell.EditorServices.Test.Shared;
using System;
using System.IO;
using System.Linq;
using Xunit;
namespace PSLanguageService.Test
{
public class ScriptFileChangeTests
{
#if CoreCLR
private static readonly Version PowerShellVersion = new Version(6, 1);
#else
private static readonly Version PowerShellVersion = new Version(5, 1);
#endif
[Fact]
public void CanApplySingleLineInsert()
{
this.AssertFileChange(
"This is a test.",
"This is a working test.",
new FileChange
{
Line = 1,
EndLine = 1,
Offset = 10,
EndOffset = 10,
InsertString = " working"
});
}
[Fact]
public void CanApplySingleLineReplace()
{
this.AssertFileChange(
"This is a potentially broken test.",
"This is a working test.",
new FileChange
{
Line = 1,
EndLine = 1,
Offset = 11,
EndOffset = 29,
InsertString = "working"
});
}
[Fact]
public void CanApplySingleLineDelete()
{
this.AssertFileChange(
"This is a test of the emergency broadcasting system.",
"This is a test.",
new FileChange
{
Line = 1,
EndLine = 1,
Offset = 15,
EndOffset = 52,
InsertString = ""
});
}
[Fact]
public void CanApplyMultiLineInsert()
{
this.AssertFileChange(
TestUtilities.NormalizeNewlines("first\nsecond\nfifth"),
TestUtilities.NormalizeNewlines("first\nsecond\nthird\nfourth\nfifth"),
new FileChange
{
Line = 3,
EndLine = 3,
Offset = 1,
EndOffset = 1,
InsertString = TestUtilities.NormalizeNewlines("third\nfourth\n")
});
}
[Fact]
public void CanApplyMultiLineReplace()
{
this.AssertFileChange(
TestUtilities.NormalizeNewlines("first\nsecoXX\nXXfth"),
TestUtilities.NormalizeNewlines("first\nsecond\nthird\nfourth\nfifth"),
new FileChange
{
Line = 2,
EndLine = 3,
Offset = 5,
EndOffset = 3,
InsertString = TestUtilities.NormalizeNewlines("nd\nthird\nfourth\nfi")
});
}
[Fact]
public void CanApplyMultiLineReplaceWithRemovedLines()
{
this.AssertFileChange(
TestUtilities.NormalizeNewlines("first\nsecoXX\nREMOVE\nTHESE\nLINES\nXXfth"),
TestUtilities.NormalizeNewlines("first\nsecond\nthird\nfourth\nfifth"),
new FileChange
{
Line = 2,
EndLine = 6,
Offset = 5,
EndOffset = 3,
InsertString = TestUtilities.NormalizeNewlines("nd\nthird\nfourth\nfi")
});
}
[Fact]
public void CanApplyMultiLineDelete()
{
this.AssertFileChange(
TestUtilities.NormalizeNewlines("first\nsecond\nREMOVE\nTHESE\nLINES\nthird"),
TestUtilities.NormalizeNewlines("first\nsecond\nthird"),
new FileChange
{
Line = 3,
EndLine = 6,
Offset = 1,
EndOffset = 1,
InsertString = ""
});
}
[Fact]
public void CanApplyEditsToEndOfFile()
{
this.AssertFileChange(
TestUtilities.NormalizeNewlines("line1\nline2\nline3\n\n"),
TestUtilities.NormalizeNewlines("line1\nline2\nline3\n\n\n\n"),
new FileChange
{
Line = 5,
EndLine = 5,
Offset = 1,
EndOffset = 1,
InsertString = Environment.NewLine + Environment.NewLine
});
}
[Fact]
public void CanAppendToEndOfFile()
{
this.AssertFileChange(
TestUtilities.NormalizeNewlines("line1\nline2\nline3"),
TestUtilities.NormalizeNewlines("line1\nline2\nline3\nline4\nline5"),
new FileChange
{
Line = 4,
EndLine = 5,
Offset = 1,
EndOffset = 1,
InsertString = $"line4{Environment.NewLine}line5"
}
);
}
[Fact]
public void FindsDotSourcedFiles()
{
string exampleScriptContents = TestUtilities.PlatformNormalize(
". ./athing.ps1\n"+
". ./somefile.ps1\n"+
". ./somefile.ps1\n"+
"Do-Stuff $uri\n"+
". simpleps.ps1");
using (StringReader stringReader = new StringReader(exampleScriptContents))
{
ScriptFile scriptFile =
new ScriptFile(
"DotSourceTestFile.ps1",
"DotSourceTestFile.ps1",
stringReader,
PowerShellVersion);
Assert.Equal(3, scriptFile.ReferencedFiles.Length);
System.Console.Write("a" + scriptFile.ReferencedFiles[0]);
Assert.Equal(TestUtilities.NormalizePath("./athing.ps1"), scriptFile.ReferencedFiles[0]);
}
}
[Fact]
public void ThrowsExceptionWithEditOutsideOfRange()
{
Assert.Throws<ArgumentOutOfRangeException>(
() =>
{
this.AssertFileChange(
TestUtilities.NormalizeNewlines("first\nsecond\nREMOVE\nTHESE\nLINES\nthird"),
TestUtilities.NormalizeNewlines("first\nsecond\nthird"),
new FileChange
{
Line = 3,
EndLine = 8,
Offset = 1,
EndOffset = 1,
InsertString = ""
});
});
}
[Fact]
public void CanDeleteFromEndOfFile()
{
this.AssertFileChange(
TestUtilities.NormalizeNewlines("line1\nline2\nline3\nline4"),
TestUtilities.NormalizeNewlines("line1\nline2"),
new FileChange
{
Line = 3,
EndLine = 5,
Offset = 1,
EndOffset = 1,
InsertString = ""
}
);
}
internal static ScriptFile CreateScriptFile(string initialString)
{
using (StringReader stringReader = new StringReader(initialString))
{
// Create an in-memory file from the StringReader
ScriptFile fileToChange =
new ScriptFile(
"TestFile.ps1",
"TestFile.ps1",
stringReader,
PowerShellVersion);
return fileToChange;
}
}
private void AssertFileChange(
string initialString,
string expectedString,
FileChange fileChange)
{
// Create an in-memory file from the StringReader
ScriptFile fileToChange = CreateScriptFile(initialString);
// Apply the FileChange and assert the resulting contents
fileToChange.ApplyChange(fileChange);
Assert.Equal(expectedString, fileToChange.Contents);
}
}
public class ScriptFileGetLinesTests
{
private static readonly string TestString_NoTrailingNewline = TestUtilities.NormalizeNewlines(
"Line One\nLine Two\nLine Three\nLine Four\nLine Five");
private static readonly string TestString_TrailingNewline = TestUtilities.NormalizeNewlines(
TestString_NoTrailingNewline + "\n");
private static readonly string[] s_newLines = new string[] { Environment.NewLine };
private static readonly string[] s_testStringLines_noTrailingNewline = TestString_NoTrailingNewline.Split(s_newLines, StringSplitOptions.None);
private static readonly string[] s_testStringLines_trailingNewline = TestString_TrailingNewline.Split(s_newLines, StringSplitOptions.None);
private ScriptFile _scriptFile_trailingNewline;
private ScriptFile _scriptFile_noTrailingNewline;
public ScriptFileGetLinesTests()
{
_scriptFile_noTrailingNewline = ScriptFileChangeTests.CreateScriptFile(
TestString_NoTrailingNewline);
_scriptFile_trailingNewline = ScriptFileChangeTests.CreateScriptFile(
TestString_TrailingNewline);
}
[Fact]
public void CanGetWholeLine()
{
string[] lines =
_scriptFile_noTrailingNewline.GetLinesInRange(
new BufferRange(5, 1, 5, 10));
Assert.Single(lines);
Assert.Equal("Line Five", lines[0]);
}
[Fact]
public void CanGetMultipleWholeLines()
{
string[] lines =
_scriptFile_noTrailingNewline.GetLinesInRange(
new BufferRange(2, 1, 4, 10));
Assert.Equal(s_testStringLines_noTrailingNewline.Skip(1).Take(3), lines);
}
[Fact]
public void CanGetSubstringInSingleLine()
{
string[] lines =
_scriptFile_noTrailingNewline.GetLinesInRange(
new BufferRange(4, 3, 4, 8));
Assert.Single(lines);
Assert.Equal("ne Fo", lines[0]);
}
[Fact]
public void CanGetEmptySubstringRange()
{
string[] lines =
_scriptFile_noTrailingNewline.GetLinesInRange(
new BufferRange(4, 3, 4, 3));
Assert.Single(lines);
Assert.Equal("", lines[0]);
}
[Fact]
public void CanGetSubstringInMultipleLines()
{
string[] expectedLines = new string[]
{
"Two",
"Line Three",
"Line Fou"
};
string[] lines =
_scriptFile_noTrailingNewline.GetLinesInRange(
new BufferRange(2, 6, 4, 9));
Assert.Equal(expectedLines, lines);
}
[Fact]
public void CanGetRangeAtLineBoundaries()
{
string[] expectedLines = new string[]
{
"",
"Line Three",
""
};
string[] lines =
_scriptFile_noTrailingNewline.GetLinesInRange(
new BufferRange(2, 9, 4, 1));
Assert.Equal(expectedLines, lines);
}
[Fact]
public void CanSplitLines_NoTrailingNewline()
{
Assert.Equal(s_testStringLines_noTrailingNewline, _scriptFile_noTrailingNewline.FileLines);
}
[Fact]
public void CanSplitLines_TrailingNewline()
{
Assert.Equal(s_testStringLines_trailingNewline, _scriptFile_trailingNewline.FileLines);
}
[Fact]
public void CanGetSameLinesWithUnixLineBreaks()
{
var unixFile = ScriptFileChangeTests.CreateScriptFile(TestString_NoTrailingNewline.Replace("\r\n", "\n"));
Assert.Equal(_scriptFile_noTrailingNewline.FileLines, unixFile.FileLines);
}
[Fact]
public void CanGetLineForEmptyString()
{
var emptyFile = ScriptFileChangeTests.CreateScriptFile(string.Empty);
Assert.Single(emptyFile.FileLines);
Assert.Equal(string.Empty, emptyFile.FileLines[0]);
}
[Fact]
public void CanGetLineForSpace()
{
var spaceFile = ScriptFileChangeTests.CreateScriptFile(" ");
Assert.Single(spaceFile.FileLines);
Assert.Equal(" ", spaceFile.FileLines[0]);
}
}
public class ScriptFilePositionTests
{
private ScriptFile scriptFile;
public ScriptFilePositionTests()
{
this.scriptFile =
ScriptFileChangeTests.CreateScriptFile(@"
First line
Second line is longer
Third line
");
}
[Fact]
public void CanOffsetByLine()
{
this.AssertNewPosition(
1, 1,
2, 0,
3, 1);
this.AssertNewPosition(
3, 1,
-2, 0,
1, 1);
}
[Fact]
public void CanOffsetByColumn()
{
this.AssertNewPosition(
2, 1,
0, 2,
2, 3);
this.AssertNewPosition(
2, 5,
0, -3,
2, 2);
}
[Fact]
public void ThrowsWhenPositionOutOfRange()
{
// Less than line range
Assert.Throws<ArgumentOutOfRangeException>(
() =>
{
scriptFile.CalculatePosition(
new BufferPosition(1, 1),
-10, 0);
});
// Greater than line range
Assert.Throws<ArgumentOutOfRangeException>(
() =>
{
scriptFile.CalculatePosition(
new BufferPosition(1, 1),
10, 0);
});
// Less than column range
Assert.Throws<ArgumentOutOfRangeException>(
() =>
{
scriptFile.CalculatePosition(
new BufferPosition(1, 1),
0, -10);
});
// Greater than column range
Assert.Throws<ArgumentOutOfRangeException>(
() =>
{
scriptFile.CalculatePosition(
new BufferPosition(1, 1),
0, 10);
});
}
[Fact]
public void CanFindBeginningOfLine()
{
this.AssertNewPosition(
4, 12,
pos => pos.GetLineStart(),
4, 5);
}
[Fact]
public void CanFindEndOfLine()
{
this.AssertNewPosition(
4, 12,
pos => pos.GetLineEnd(),
4, 15);
}
[Fact]
public void CanComposePositionOperations()
{
this.AssertNewPosition(
4, 12,
pos => pos.AddOffset(-1, 1).GetLineStart(),
3, 3);
}
private void AssertNewPosition(
int originalLine, int originalColumn,
int lineOffset, int columnOffset,
int expectedLine, int expectedColumn)
{
this.AssertNewPosition(
originalLine, originalColumn,
pos => pos.AddOffset(lineOffset, columnOffset),
expectedLine, expectedColumn);
}
private void AssertNewPosition(
int originalLine, int originalColumn,
Func<FilePosition, FilePosition> positionOperation,
int expectedLine, int expectedColumn)
{
var newPosition =
positionOperation(
new FilePosition(
this.scriptFile,
originalLine,
originalColumn));
Assert.Equal(expectedLine, newPosition.Line);
Assert.Equal(expectedColumn, newPosition.Column);
}
}
public class ScriptFileConstructorTests
{
private static readonly Version PowerShellVersion = new Version("5.0");
[Fact]
public void PropertiesInitializedCorrectlyForFile()
{
var path = "TestFile.ps1";
var scriptFile = ScriptFileChangeTests.CreateScriptFile("");
Assert.Equal(path, scriptFile.FilePath);
Assert.Equal(path, scriptFile.ClientFilePath);
Assert.True(scriptFile.IsAnalysisEnabled);
Assert.False(scriptFile.IsInMemory);
Assert.Empty(scriptFile.ReferencedFiles);
Assert.Empty(scriptFile.DiagnosticMarkers);
Assert.Single(scriptFile.ScriptTokens);
Assert.Single(scriptFile.FileLines);
}
[Fact]
public void PropertiesInitializedCorrectlyForUntitled()
{
var path = "untitled:untitled-1";
// 3 lines and 10 tokens in this script.
var script = @"function foo() {
'foo'
}";
using (StringReader stringReader = new StringReader(script))
{
// Create an in-memory file from the StringReader
var scriptFile = new ScriptFile(path, path, stringReader, PowerShellVersion);
Assert.Equal(path, scriptFile.FilePath);
Assert.Equal(path, scriptFile.ClientFilePath);
Assert.Equal(path, scriptFile.DocumentUri);
Assert.True(scriptFile.IsAnalysisEnabled);
Assert.True(scriptFile.IsInMemory);
Assert.Empty(scriptFile.ReferencedFiles);
Assert.Empty(scriptFile.DiagnosticMarkers);
Assert.Equal(10, scriptFile.ScriptTokens.Length);
Assert.Equal(3, scriptFile.FileLines.Count);
}
}
[Fact]
public void DocumentUriRetunsCorrectStringForAbsolutePath()
{
string path;
ScriptFile scriptFile;
var emptyStringReader = new StringReader("");
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
path = @"C:\Users\AmosBurton\projects\Rocinate\ProtoMolecule.ps1";
scriptFile = new ScriptFile(path, path, emptyStringReader, PowerShellVersion);
Assert.Equal("file:///c%3A/Users/AmosBurton/projects/Rocinate/ProtoMolecule.ps1", scriptFile.DocumentUri);
path = @"c:\Users\BobbyDraper\projects\Rocinate\foo's_~#-[@] +,;=%.ps1";
scriptFile = new ScriptFile(path, path, emptyStringReader, PowerShellVersion);
Assert.Equal("file:///c%3A/Users/BobbyDraper/projects/Rocinate/foo%27s_~%23-%5B%40%5D%20%2B%2C%3B%3D%25.ps1", scriptFile.DocumentUri);
}
else
{
// Test the following only on Linux and macOS.
path = "/home/AlexKamal/projects/Rocinate/ProtoMolecule.ps1";
scriptFile = new ScriptFile(path, path, emptyStringReader, PowerShellVersion);
Assert.Equal("file:///home/AlexKamal/projects/Rocinate/ProtoMolecule.ps1", scriptFile.DocumentUri);
path = "/home/BobbyDraper/projects/Rocinate/foo's_~#-[@] +,;=%.ps1";
scriptFile = new ScriptFile(path, path, emptyStringReader, PowerShellVersion);
Assert.Equal("file:///home/BobbyDraper/projects/Rocinate/foo%27s_~%23-%5B%40%5D%20%2B%2C%3B%3D%25.ps1", scriptFile.DocumentUri);
path = "/home/NaomiNagata/projects/Rocinate/Proto:Mole:cule.ps1";
scriptFile = new ScriptFile(path, path, emptyStringReader, PowerShellVersion);
Assert.Equal("file:///home/NaomiNagata/projects/Rocinate/Proto%3AMole%3Acule.ps1", scriptFile.DocumentUri);
path = "/home/JamesHolden/projects/Rocinate/Proto:Mole\\cule.ps1";
scriptFile = new ScriptFile(path, path, emptyStringReader, PowerShellVersion);
Assert.Equal("file:///home/JamesHolden/projects/Rocinate/Proto%3AMole%5Ccule.ps1", scriptFile.DocumentUri);
}
}
}
}
| 33.491987 | 151 | 0.516006 | [
"MIT"
] | Benny1007/PowerShellEditorServices | test/PowerShellEditorServices.Test/Session/ScriptFileTests.cs | 20,901 | C# |
//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
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("InvisibleParam")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("InvisibleParam")]
[assembly: AssemblyCopyright("Copyright © Autodesk, Inc. 2009")]
[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("30a6e51d-ee60-452c-aaf8-087ca3aa9882")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.627119 | 85 | 0.733417 | [
"MIT"
] | xin1627/RevitSdkSamples | SDK/Samples/InvisibleParam/CS/Properties/AssemblyInfo.cs | 2,400 | C# |
#pragma checksum "..\..\..\Pages\StopScan.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5138EC26EA86B24DB4B5A072C146B909F2CE76DA"
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using AntiVirusApp.Pages;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace AntiVirusApp.Pages {
/// <summary>
/// StopScan
/// </summary>
public partial class StopScan : System.Windows.Controls.Page, System.Windows.Markup.IComponentConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/AntiVirusApp;component/pages/stopscan.xaml", System.UriKind.Relative);
#line 1 "..\..\..\Pages\StopScan.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
}
| 38.118421 | 141 | 0.664826 | [
"MIT"
] | 1TreeForest/AntiVirusApp | AntiVirusApp/obj/Debug/Pages/StopScan.g.i.cs | 3,005 | C# |
//this source code was auto-generated by tolua#, do not modify it
using System;
using LuaInterface;
public class UnityEngine_U2D_SpriteAtlasManagerWrap
{
public static void Register(LuaState L)
{
L.BeginStaticLibs("SpriteAtlasManager");
L.RegVar("atlasRequested", get_atlasRequested, set_atlasRequested);
L.RegVar("atlasRegistered", get_atlasRegistered, set_atlasRegistered);
L.EndStaticLibs();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_atlasRequested(IntPtr L)
{
ToLua.Push(L, new EventObject(typeof(System.Action<string,System.Action<UnityEngine.U2D.SpriteAtlas>>)));
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_atlasRegistered(IntPtr L)
{
ToLua.Push(L, new EventObject(typeof(System.Action<UnityEngine.U2D.SpriteAtlas>)));
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_atlasRequested(IntPtr L)
{
try
{
EventObject arg0 = null;
if (LuaDLL.lua_isuserdata(L, 2) != 0)
{
arg0 = (EventObject)ToLua.ToObject(L, 2);
}
else
{
return LuaDLL.luaL_throw(L, "The event 'UnityEngine.U2D.SpriteAtlasManager.atlasRequested' can only appear on the left hand side of += or -= when used outside of the type 'UnityEngine.U2D.SpriteAtlasManager'");
}
if (arg0.op == EventOp.Add)
{
System.Action<string,System.Action<UnityEngine.U2D.SpriteAtlas>> ev = (System.Action<string,System.Action<UnityEngine.U2D.SpriteAtlas>>)arg0.func;
UnityEngine.U2D.SpriteAtlasManager.atlasRequested += ev;
}
else if (arg0.op == EventOp.Sub)
{
System.Action<string,System.Action<UnityEngine.U2D.SpriteAtlas>> ev = (System.Action<string,System.Action<UnityEngine.U2D.SpriteAtlas>>)arg0.func;
UnityEngine.U2D.SpriteAtlasManager.atlasRequested -= ev;
}
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_atlasRegistered(IntPtr L)
{
try
{
EventObject arg0 = null;
if (LuaDLL.lua_isuserdata(L, 2) != 0)
{
arg0 = (EventObject)ToLua.ToObject(L, 2);
}
else
{
return LuaDLL.luaL_throw(L, "The event 'UnityEngine.U2D.SpriteAtlasManager.atlasRegistered' can only appear on the left hand side of += or -= when used outside of the type 'UnityEngine.U2D.SpriteAtlasManager'");
}
if (arg0.op == EventOp.Add)
{
System.Action<UnityEngine.U2D.SpriteAtlas> ev = (System.Action<UnityEngine.U2D.SpriteAtlas>)arg0.func;
UnityEngine.U2D.SpriteAtlasManager.atlasRegistered += ev;
}
else if (arg0.op == EventOp.Sub)
{
System.Action<UnityEngine.U2D.SpriteAtlas> ev = (System.Action<UnityEngine.U2D.SpriteAtlas>)arg0.func;
UnityEngine.U2D.SpriteAtlasManager.atlasRegistered -= ev;
}
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
}
| 29 | 215 | 0.724138 | [
"MIT"
] | getker/Kerven_Client | Assets/ToLua/Source/Generate/UnityEngine_U2D_SpriteAtlasManagerWrap.cs | 2,902 | C# |
namespace NiceHashMinerLegacy.Common.Enums
{
/// <summary>
/// AlgorithmType enum should/must mirror the values from https://www.nicehash.com/?p=api
/// Some algorithms are not used anymore on the client, rename them with _UNUSED postfix so we can catch compile time errors if they are used.
/// </summary>
public enum AlgorithmType
{
// dual algos for grouping
AutolykosZil = -73,
DaggerOctopus = -17,
DaggerKAWPOW = -16,
DaggerAutolykos = -15,
DaggerHashimoto4GB = -12,
DaggerHandshake = -11,
DaggerEaglesong = -10,
DaggerHashimoto3GB = -9,
DaggerKeccak = -8,
DaggerBlake2s = -7,
DaggerSia = -6,
DaggerDecred = -5,
DaggerLbry = -4,
DaggerPascal = -3,
INVALID = -2,
NONE = -1,
#region NiceHashAPI
//Scrypt_UNUSED = 0,
//SHA256_UNUSED = 1,
//ScryptNf_UNUSED = 2,
//X11_UNUSED = 3,
//X13 = 4,
Keccak = 5,
//X15 = 6,
Nist5 = 7,
//NeoScrypt = 8,
//Lyra2RE = 9,
//WhirlpoolX = 10,
//Qubit = 11,
//Quark = 12,
//Axiom_UNUSED = 13,
//Lyra2REv2 = 14,
//ScryptJaneNf16_UNUSED = 15,
//Blake256r8 = 16,
//Blake256r14 = 17, // NOT USED ANYMORE?
//Blake256r8vnl = 18,
//Hodl = 19,
//DaggerHashimoto = 20,
//Decred = 21,
//CryptoNight = 22,
//Lbry = 23,
//Equihash = 24,
//Pascal = 25
// UNUSED START
Scrypt_UNUSED = 0,
SHA256_UNUSED = 1,
ScryptNf_UNUSED = 2,
X11_UNUSED = 3,
X13_UNUSED = 4,
//Keccak_UNUSED = 5,
X15_UNUSED = 6,
//Nist5_UNUSED = 7,
WhirlpoolX_UNUSED = 10,
Qubit_UNUSED = 11,
Quark_UNUSED = 12,
Axiom_UNUSED = 13,
ScryptJaneNf16_UNUSED = 15,
Blake256r8_UNUSED = 16,
Blake256r14_UNUSED = 17,
Blake256r8vnl_UNUSED = 18,
// UNUSED END
NeoScrypt = 8,
Lyra2RE_UNUSED = 9,
Lyra2REv2 = 14,
Hodl_UNUSED = 19,
DaggerHashimoto = 20,
Decred = 21,
CryptoNight_UNUSED = 22,
Lbry_UNUSED = 23,
Equihash_UNUSED = 24,
Pascal_UNUSED = 25,
X11Gost_UNUSED = 26,
Sia_UNUSED = 27,
Blake2s = 28,
Skunk_UNUSED = 29,
CryptoNightV7_UNUSED = 30,
// Tentative
CryptoNightHeavy_UNUSED = 31,
Lyra2z = 32,
X16R = 33,
CryptoNightV8_UNUSED = 34,
sha256asicboost_UNUSED = 35,
ZHash = 36,
Beam_UNUSED = 37,
GrinCuckaroo29 = 38,
GrinCuckatoo31 = 39,
Lyra2REv3 = 40,
MTP = 41,
CryptoNightR_UNUSED = 42,
CuckooCycle = 43,
GrinCuckarood29 = 44,
BeamV2 = 45,
X16RV2 = 46,
RandomX = 47,
Eaglesong_UNUSED = 48,
Cuckaroom = 49,
GrinCuckatoo32 = 50,
Handshake_UNUSED = 51,
KAWPOW = 52,
Cuckaroo29BFC_UNUSED = 53,
BeamV3 = 54,
CuckaRooz29 = 55,
Octopus = 56,
Autolykos = 57
#endregion // NiceHashAPI
}
}
| 26.590164 | 146 | 0.516954 | [
"MIT"
] | angelbbs/NiceHashMinerLegacy | NiceHashMinerLegacy.Common/Enums/AlgorithmType.cs | 3,246 | 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.
//
// Revision history:
//
// BD - January 2017 - Created this file.
//
#pragma warning disable IDE0079 // Remove unnecessary suppression.
#pragma warning disable CA1062 // Omitted null checks similar to expression tree visitors.
namespace System.Linq.Expressions
{
public partial class ExpressionOptimizer
{
/// <summary>
/// Tries to change the static type of the specified <paramref name="expression"/> to the
/// specified <paramref name="type"/>.
/// </summary>
/// <param name="expression">The expression whose static type to change.</param>
/// <param name="type">The type to change the static type of the expression to.</param>
/// <param name="result">The resulting expression with the specified static type.</param>
/// <returns><c>true</c> if a change of type was possible; otherwise, <c>false</c>.</returns>
protected virtual bool TryChangeType(Expression expression, Type type, out Expression result)
{
if (expression.Type == type)
{
result = expression;
return true;
}
switch (expression.NodeType)
{
case ExpressionType.Block:
var block = (BlockExpression)expression;
result = Expression.Block(type, block.Variables, block.Expressions);
return true;
case ExpressionType.Conditional:
var conditional = (ConditionalExpression)expression;
result = Expression.Condition(conditional.Test, conditional.IfTrue, conditional.IfFalse, type);
return true;
case ExpressionType.Constant:
if (type == typeof(void))
{
result = Expression.Empty();
return true;
}
else
{
var constant = (ConstantExpression)expression;
result = Expression.Constant(constant.Value, type);
return true;
}
case ExpressionType.Default:
result = Expression.Default(type);
return true;
case ExpressionType.Goto:
var @goto = (GotoExpression)expression;
result = Expression.MakeGoto(@goto.Kind, @goto.Target, @goto.Value, type);
return true;
case ExpressionType.Switch:
var @switch = (SwitchExpression)expression;
result = Expression.Switch(type, @switch.SwitchValue, @switch.DefaultBody, @switch.Comparison, @switch.Cases);
return true;
case ExpressionType.Throw:
var @throw = (UnaryExpression)expression;
result = Expression.Throw(@throw.Operand, type);
return true;
case ExpressionType.Try:
var @try = (TryExpression)expression;
result = Expression.MakeTry(type, @try.Body, @try.Finally, @try.Fault, @try.Handlers);
return true;
}
if (type == typeof(void))
{
// TODO: Check whether this can result in invalid trees, e.g. jump into a block situations?
result = Expression.Block(typeof(void), expression);
return true;
}
result = Expression.Convert(expression, type);
return true;
}
/// <summary>
/// Changes the static type of the specified <paramref name="expression"/> to the
/// specified <paramref name="type"/>.
/// </summary>
/// <param name="expression">The expression whose static type to change.</param>
/// <param name="type">The type to change the static type of the expression to.</param>
/// <returns>The resulting expression with the specified static type.</returns>
protected Expression ChangeType(Expression expression, Type type)
{
if (!TryChangeType(expression, type, out var res))
{
throw new InvalidOperationException($"Can't change the type of expression '{expression}' to type '{type}'.");
}
return res;
}
/// <summary>
/// Gets the runtime type of the result of evaluating the specified <paramref name="expression"/>.
/// </summary>
/// <param name="expression">The expression whose runtime type to get.</param>
/// <returns>The runtime type of the expression, if statically known; otherwise, <c>null</c>.</returns>
/// <remarks>
/// This method checks if the specified <paramref name="expression"/> does not throw in order to
/// determine the runtime type. If an exception can occur during evaluation of the expression,
/// a <c>null</c> reference is returned.
/// </remarks>
protected Type GetRuntimeType(Expression expression)
{
if (NeverThrows(expression))
{
if (HasConstantValue(expression))
{
var value = GetConstantValue(expression);
if (value != null)
{
return value.GetType();
}
}
//
// NB: For these, we know the exact type of the instance being
// created (because of `newobj`).
//
switch (expression.NodeType)
{
case ExpressionType.New:
case ExpressionType.MemberInit:
case ExpressionType.ListInit:
return expression.Type;
}
// NB: Check if we can infer the runtime type from the static
// shape of the node. We also need to make sure the operand
// can't be null.
if (HasExactType(expression) && IsNeverNull(expression))
{
return expression.Type;
}
}
return null;
}
/// <summary>
/// Checks if the specified <paramref name="expression"/>'s static type matches the runtime type when
/// evaluating the expression.
/// </summary>
/// <param name="expression">The expression to check.</param>
/// <returns><c>true</c> if the static type and the runtime type match; otherwise, <c>false</c>.</returns>
/// <remarks>
/// This method can return <c>true</c> even if the specified <paramref name="expression"/> may throw.
/// </remarks>
protected virtual bool HasExactType(Expression expression)
{
// Nodes where the static type of the node matches the runtime
// type of the node's evaluation result.
switch (expression.NodeType)
{
// TODO: Consider adding more.
case ExpressionType.Constant:
var constant = (ConstantExpression)expression;
return constant.Value?.GetType() == constant.Type;
case ExpressionType.Default:
var @default = (DefaultExpression)expression;
return @default.Type.IsValueType && !@default.Type.IsNullableType();
// `newarr`
case ExpressionType.NewArrayBounds:
case ExpressionType.NewArrayInit:
// `newobj`
case ExpressionType.New:
case ExpressionType.MemberInit:
case ExpressionType.ListInit:
// always returns bool
case ExpressionType.TypeEqual:
case ExpressionType.TypeIs:
case ExpressionType.IsTrue:
case ExpressionType.IsFalse:
// factory calls .GetType() on expression operand
// REVIEW: changes in .NET Core (returning first available public type)
case ExpressionType.Quote:
return true;
}
if (expression.Type.IsValueType)
{
if (!expression.Type.IsNullableType())
{
return true;
}
}
else if (expression.Type.IsSealed)
{
return true;
}
return false;
}
}
}
| 40.547945 | 130 | 0.532207 | [
"MIT"
] | Botcoin-com/reaqtor | Nuqleon/Core/LINQ/Nuqleon.Linq.Expressions.Optimizers/System/Linq/Expressions/ExpressionOptimizer.Typing.cs | 8,882 | C# |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit
{
using System;
using System.Collections.Generic;
using System.Linq;
using Automatonymous;
using Automatonymous.Scoping;
using AutomatonymousStructureMapIntegration;
using Internals.Extensions;
using StructureMap;
public static class StructureMapStateMachineLoadSagaExtensions
{
/// <summary>
/// Scans the lifetime scope and registers any state machines sagas which are found in the scope using the StructureMap saga repository
/// and the appropriate state machine saga repository under the hood.
/// </summary>
/// <param name="configurator"></param>
/// <param name="container"></param>
public static void LoadStateMachineSagas(this IReceiveEndpointConfigurator configurator, IContainer container)
{
IList<Type> sagaTypes = FindStateMachineSagaTypes(container);
var stateMachineFactory = new StructureMapSagaStateMachineFactory(container);
var repositoryFactory = new StructureMapStateMachineSagaRepositoryFactory(container);
foreach (var sagaType in sagaTypes)
{
StateMachineSagaConfiguratorCache.Configure(sagaType, configurator, stateMachineFactory, repositoryFactory);
}
}
public static IList<Type> FindStateMachineSagaTypes(IContainer container)
{
return container
.Model
.PluginTypes
.Where(x => x.PluginType.HasInterface(typeof(SagaStateMachine<>)))
.Select(i => i.PluginType.GetClosingArguments(typeof(SagaStateMachine<>)).First())
.Distinct()
.ToList();
}
}
} | 41.948276 | 144 | 0.662968 | [
"Apache-2.0"
] | Aneskov/MassTransit | src/Containers/MassTransit.Automatonymous.StructureMapIntegration/StructureMapStateMachineLoadSagaExtensions.cs | 2,435 | C# |
using System;
using System.Runtime.InteropServices;
using ObjCRuntime;
namespace StoreKit {
partial class SKReceiptRefreshRequest {
[iOS (7,1), Mac (10,14)]
[DllImport (Constants.StoreKitLibrary, EntryPoint = "SKTerminateForInvalidReceipt")]
static extern public void TerminateForInvalidReceipt ();
}
} | 26 | 86 | 0.778846 | [
"BSD-3-Clause"
] | FlavioGoncalves-Cayas/xamarin-macios | src/StoreKit/NativeMethods.cs | 312 | C# |
using System;
using System.Collections.Generic;
namespace Core
{
public partial class Usuario
{
public Usuario()
{
Solicitacaomedicamento = new HashSet<Solicitacaomedicamento>();
}
public int IdUsuario { get; set; }
public int IdFarmacia { get; set; }
public string TipoUsuario { get; set; }
public string Nome { get; set; }
public string Cpf { get; set; }
public string Telefone { get; set; }
public string Sexo { get; set; }
public string Logradouro { get; set; }
public string Estado { get; set; }
public string Cidade { get; set; }
public string Bairro { get; set; }
public string Email { get; set; }
public string Senha { get; set; }
public virtual Farmacia IdFarmaciaNavigation { get; set; }
public virtual ICollection<Solicitacaomedicamento> Solicitacaomedicamento { get; set; }
}
}
| 31.032258 | 95 | 0.60395 | [
"MIT"
] | marcosdosea/IDrug | Codigo/Core/Usuario.cs | 964 | C# |
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace AspNetCore.Mvc.Extensions.Email
{
public static class EmailTemplateCallbackExtensions
{
public static async Task SendWelcomeEmailAsync(this IEmailService emailService, string templatePath, string email)
{
var emailHtml = File.ReadAllText(templatePath);
await emailService.SendEmailAsync(email, "Welcome", "", emailHtml);
}
public static async Task SendResetPasswordEmailAsync(this IEmailService emailService, IUrlHelper urlHelper, string templatePath, string email, string callbackUrl, string userId, string code, string scheme)
{
//var callbackUrl = urlHelper.ResetPasswordCallbackLink(userId, code, scheme);
callbackUrl = $"{callbackUrl}?email={email}&code={WebUtility.UrlEncode(code)}";
var emailHtml = File.ReadAllText(templatePath).Replace("{callbackUrl}", callbackUrl);
await emailService.SendEmailAsync(email, "Reset Password", "", emailHtml);
}
}
}
| 43.96 | 213 | 0.709736 | [
"MIT"
] | davidikin45/AspNetCore.Mvc.Extensions | src/AspNetCore.Mvc.Extensions/Email/EmailTemplateCallbackExtensions.cs | 1,101 | C# |
using FluentValidation;
using SFA.DAS.Events.Application.Commands.CreateApprenticeshipEvent;
using SFA.DAS.Events.Domain.Entities;
namespace SFA.DAS.Events.Application.Commands.BulkUploadCreateApprenticeshipEvents
{
public class BulkUploadCreateApprentieshipEventsCommandValidator : AbstractValidator<BulkUploadCreateApprenticeshipEventsCommand>
{
public BulkUploadCreateApprentieshipEventsCommandValidator()
{
RuleFor(x => x.ApprenticeshipEvents).SetCollectionValidator(new ApprenticeshipEventValidator());
}
public class ApprenticeshipEventValidator : AbstractValidator<ApprenticeshipEvent>
{
public ApprenticeshipEventValidator()
{
RuleFor(x => x.TransferSenderName)
.NotEmpty()
.When(x => x.TransferSenderId.HasValue && x.TransferSenderId > 0)
.WithMessage("'Transfer Sender Name' should not be empty if 'Transfer Sender Id' is specified");
RuleFor(x => x.TransferSenderId)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.When(x => !string.IsNullOrWhiteSpace(x.TransferSenderName))
.WithMessage("'Transfer Sender Id' should not be empty if 'Transfer Sender Name' is specified");
RuleFor(x => x.TransferSenderId)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.When(x => x.TransferApprovalStatus.HasValue)
.WithMessage("'Transfer Sender Id' should not be empty if 'Transfer Approval Status' is set");
}
}
}
}
| 45.157895 | 133 | 0.631702 | [
"MIT"
] | SkillsFundingAgency/das-events | src/SFA.DAS.Events.Application/Commands/BulkUploadCreateApprenticeshipEvents/BulkUploadCreateApprentieshipEventsCommandValidator.cs | 1,718 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotVVM.Framework.ViewModel;
namespace SampleApp1.ViewModels.MasterPages
{
public class SiteViewModel : LayoutViewModel
{
}
}
| 16.533333 | 48 | 0.717742 | [
"Apache-2.0"
] | riganti/dotvvm-selenium-generator | src/Samples/SampleApp1/ViewModels/MasterPages/SiteViewModel.cs | 248 | C# |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// 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.
#endregion
using System;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
namespace MigraDoc.Rendering
{
/// <summary>
/// Rendering information for tables.
/// </summary>
internal class TableRenderInfo : RenderInfo
{
internal TableRenderInfo()
{
}
internal override FormatInfo FormatInfo
{
get { return this.formatInfo; }
}
private TableFormatInfo formatInfo = new TableFormatInfo();
internal override MigraDoc.DocumentObjectModel.DocumentObject DocumentObject
{
get { return this.table; }
}
internal Table table;
}
}
| 34.694915 | 81 | 0.718613 | [
"MIT"
] | dankennedy/MigraDoc | code/MigraDoc.Rendering/MigraDoc.Rendering/TableRenderInfo.cs | 2,047 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using Mono.Cecil;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;
using System.Collections.Specialized;
namespace SpacechemPatch
{
class Program : Form
{
private string gameFolder;
private string currentExePath;
private string originalExePath;
private string patchedExePath;
HashSet<Patch> enabledPatches = new HashSet<Patch>();
private Label labelPath;
private TextBox textBoxPath;
private Button buttonBrowse;
private Button buttonPatch;
private OpenFileDialog openFileDialogSCExe;
private DataGridView dataGridViewPatches;
private LinkLabel linkLabelGithub;
private Button buttonRestore;
private CheckBox checkBoxParanoia;
private DataGridViewCheckBoxColumn ColumnEnabled;
private DataGridViewTextBoxColumn ColumnType;
private DataGridViewTextBoxColumn ColumnName;
private DataGridViewTextBoxColumn ColumnDescr;
private DataGridViewTextBoxColumn ColumnInternalConflicts;
private DataGridViewTextBoxColumn ColumnConflicts;
private Label explanation;
private LinkLabel disclaimer;
Program()
{
InitializeComponent();
string prevPath = (string)Properties.Settings.Default["SCPath"];
textBoxPath.Text = String.IsNullOrEmpty(prevPath) ? ExecutableUtils.GetDefaultPath() : prevPath;
// Fill grid and after enable the `Changed` callback
foreach (Patch patch in Enum.GetValues(typeof(Patch)))
{
PatchInfo info = PatchInfo.allPatches[patch];
string conflicts = String.Join(", ", info.ConflictingPatches.Select(p => p.ToString()).ToArray());
dataGridViewPatches.Rows.Add(false, info.Type, patch, info.Description, info.ConflictingPatches, conflicts);
}
this.dataGridViewPatches.CellValueChanged += this.dataGridViewPatches_CellValueChanged;
// restore checkboxes
StringCollection selectedPatches = (StringCollection)Properties.Settings.Default["SelectedPatches"];
if (selectedPatches != null) {
foreach (DataGridViewRow row in dataGridViewPatches.Rows)
{
string patch = ((Patch)row.Cells["ColumnName"].Value).ToString();
row.Cells[0].Value = selectedPatches.Contains(patch);
}
}
#if DEBUG
checkBoxParanoia.Checked = true;
#endif
}
private void PatchExe()
{
if (enabledPatches.Count == 0)
{
MessageBox.Show("No patch selected");
return;
}
if (!File.Exists(currentExePath))
{
MessageBox.Show("Can't find game executable in \"" + currentExePath + "\"!" + Environment.NewLine +
"Please give the correct path in the \"Path\" box");
return;
}
if (!File.Exists(originalExePath) && ExecutableUtils.IsRecognizedExe(currentExePath))
{
File.Copy(currentExePath, originalExePath);
}
if (!ExecutableUtils.IsRecognizedExe(originalExePath))
{
MessageBox.Show("Unrecognized SpaceChem executable, patching will not be executed");
return;
}
bool isSteam = ExecutableUtils.IsSteamExe(originalExePath);
using (ModuleDefinition spacechemAssembly = ModuleDefinition.ReadModule(originalExePath))
using (ModuleDefinition jsonAssembly = ModuleDefinition.ReadModule(Path.Combine(gameFolder, "Newtonsoft.Json.dll")))
using (ModuleDefinition ownAssembly = ModuleDefinition.ReadModule(System.Reflection.Assembly.GetExecutingAssembly().Location))
{
Patcher patcher = new Patcher(ownAssembly, spacechemAssembly, jsonAssembly);
ISymbolTranslator translator;
if (isSteam)
{
translator = new NoOpSymbolTranslator();
}
else
{
translator = new DictBasedSymbolTranslator(Equivalences.GOG_MAPPINGS);
}
patcher.ApplyPatches(enabledPatches, translator);
spacechemAssembly.Write(patchedExePath);
}
File.Delete(currentExePath);
File.Move(patchedExePath, currentExePath);
string message = "Patching executed successfully, added:" + Environment.NewLine;
foreach (Patch p in enabledPatches)
{
message += Environment.NewLine + p.ToString();
}
MessageBox.Show(message);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Program());
}
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Program));
this.labelPath = new System.Windows.Forms.Label();
this.textBoxPath = new System.Windows.Forms.TextBox();
this.buttonBrowse = new System.Windows.Forms.Button();
this.buttonPatch = new System.Windows.Forms.Button();
this.checkBoxParanoia = new System.Windows.Forms.CheckBox();
this.openFileDialogSCExe = new System.Windows.Forms.OpenFileDialog();
this.dataGridViewPatches = new System.Windows.Forms.DataGridView();
this.ColumnEnabled = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.ColumnType = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDescr = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnInternalConflicts = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnConflicts = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.linkLabelGithub = new System.Windows.Forms.LinkLabel();
this.buttonRestore = new System.Windows.Forms.Button();
this.explanation = new System.Windows.Forms.Label();
this.disclaimer = new System.Windows.Forms.LinkLabel();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewPatches)).BeginInit();
this.SuspendLayout();
//
// labelPath
//
this.labelPath.AutoSize = true;
this.labelPath.Location = new System.Drawing.Point(14, 66);
this.labelPath.Name = "labelPath";
this.labelPath.Size = new System.Drawing.Size(32, 13);
this.labelPath.TabIndex = 0;
this.labelPath.Text = "Path:";
//
// textBoxPath
//
this.textBoxPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxPath.Location = new System.Drawing.Point(61, 63);
this.textBoxPath.Name = "textBoxPath";
this.textBoxPath.Size = new System.Drawing.Size(460, 20);
this.textBoxPath.TabIndex = 1;
this.textBoxPath.TextChanged += new System.EventHandler(this.textBoxPath_TextChanged);
//
// buttonBrowse
//
this.buttonBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonBrowse.Location = new System.Drawing.Point(527, 63);
this.buttonBrowse.Name = "buttonBrowse";
this.buttonBrowse.Size = new System.Drawing.Size(75, 22);
this.buttonBrowse.TabIndex = 2;
this.buttonBrowse.Text = "Browse";
this.buttonBrowse.UseVisualStyleBackColor = true;
this.buttonBrowse.Click += new System.EventHandler(this.buttonBrowse_Click);
//
// buttonPatch
//
this.buttonPatch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonPatch.Enabled = false;
this.buttonPatch.Location = new System.Drawing.Point(12, 526);
this.buttonPatch.Name = "buttonPatch";
this.buttonPatch.Size = new System.Drawing.Size(205, 27);
this.buttonPatch.TabIndex = 3;
this.buttonPatch.Text = "PATCH!";
this.buttonPatch.UseVisualStyleBackColor = true;
this.buttonPatch.Click += new System.EventHandler(this.buttonPatch_Click);
//
// checkBoxParanoia
//
this.checkBoxParanoia.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.checkBoxParanoia.Location = new System.Drawing.Point(12, 484);
this.checkBoxParanoia.Name = "checkBoxParanoia";
this.checkBoxParanoia.Size = new System.Drawing.Size(590, 36);
this.checkBoxParanoia.TabIndex = 4;
this.checkBoxParanoia.Text = "I understand the risks, enable the PATCH button";
this.checkBoxParanoia.UseVisualStyleBackColor = true;
this.checkBoxParanoia.CheckedChanged += new System.EventHandler(this.checkBoxParanoia_CheckedChanged);
//
// openFileDialogSCExe
//
this.openFileDialogSCExe.FileName = "SpaceChem.exe";
this.openFileDialogSCExe.Filter = "SpaceChem Executable|SpaceChem.exe";
this.openFileDialogSCExe.Title = "Select the SpaceChem executable";
//
// dataGridViewPatches
//
this.dataGridViewPatches.AllowUserToAddRows = false;
this.dataGridViewPatches.AllowUserToDeleteRows = false;
this.dataGridViewPatches.AllowUserToOrderColumns = true;
this.dataGridViewPatches.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridViewPatches.BackgroundColor = System.Drawing.SystemColors.Control;
this.dataGridViewPatches.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewPatches.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnEnabled,
this.ColumnType,
this.ColumnName,
this.ColumnDescr,
this.ColumnInternalConflicts,
this.ColumnConflicts});
this.dataGridViewPatches.Location = new System.Drawing.Point(12, 104);
this.dataGridViewPatches.Name = "dataGridViewPatches";
this.dataGridViewPatches.RowHeadersVisible = false;
this.dataGridViewPatches.RowTemplate.Height = 24;
this.dataGridViewPatches.Size = new System.Drawing.Size(590, 208);
this.dataGridViewPatches.TabIndex = 5;
this.dataGridViewPatches.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewPatches_CellContentClick);
//
// ColumnEnabled
//
this.ColumnEnabled.FillWeight = 51.10733F;
this.ColumnEnabled.HeaderText = "Enabled";
this.ColumnEnabled.Name = "ColumnEnabled";
this.ColumnEnabled.Width = 60;
//
// ColumnType
//
this.ColumnType.FillWeight = 69.49702F;
this.ColumnType.HeaderText = "Type";
this.ColumnType.Name = "ColumnType";
this.ColumnType.ReadOnly = true;
this.ColumnType.Width = 82;
//
// ColumnName
//
this.ColumnName.FillWeight = 85.43085F;
this.ColumnName.HeaderText = "Name";
this.ColumnName.Name = "ColumnName";
this.ColumnName.ReadOnly = true;
//
// ColumnDescr
//
this.ColumnDescr.FillWeight = 243.8279F;
this.ColumnDescr.HeaderText = "Description";
this.ColumnDescr.Name = "ColumnDescr";
this.ColumnDescr.ReadOnly = true;
this.ColumnDescr.Width = 286;
//
// ColumnInternalConflicts
//
this.ColumnInternalConflicts.HeaderText = "InternalConflicts";
this.ColumnInternalConflicts.Name = "ColumnInternalConflicts";
this.ColumnInternalConflicts.ReadOnly = true;
this.ColumnInternalConflicts.Visible = false;
//
// ColumnConflicts
//
this.ColumnConflicts.FillWeight = 50.13692F;
this.ColumnConflicts.HeaderText = "Conflicts";
this.ColumnConflicts.Name = "ColumnConflicts";
this.ColumnConflicts.ReadOnly = true;
this.ColumnConflicts.Width = 59;
//
// linkLabelGithub
//
this.linkLabelGithub.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelGithub.AutoSize = true;
this.linkLabelGithub.Location = new System.Drawing.Point(483, 531);
this.linkLabelGithub.Name = "linkLabelGithub";
this.linkLabelGithub.Size = new System.Drawing.Size(88, 13);
this.linkLabelGithub.TabIndex = 6;
this.linkLabelGithub.TabStop = true;
this.linkLabelGithub.Text = "GitHub repository";
this.linkLabelGithub.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelGithub_LinkClicked);
//
// buttonRestore
//
this.buttonRestore.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonRestore.Location = new System.Drawing.Point(223, 526);
this.buttonRestore.Name = "buttonRestore";
this.buttonRestore.Size = new System.Drawing.Size(205, 27);
this.buttonRestore.TabIndex = 3;
this.buttonRestore.Text = "Restore from backup";
this.buttonRestore.UseVisualStyleBackColor = true;
this.buttonRestore.Click += new System.EventHandler(this.buttonRestore_Click);
//
// explanation
//
this.explanation.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.explanation.Location = new System.Drawing.Point(12, 13);
this.explanation.Name = "explanation";
this.explanation.Size = new System.Drawing.Size(590, 47);
this.explanation.TabIndex = 7;
this.explanation.Text = resources.GetString("explanation.Text");
//
// disclaimer
//
this.disclaimer.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.disclaimer.LinkArea = new System.Windows.Forms.LinkArea(377, 48);
this.disclaimer.Location = new System.Drawing.Point(12, 328);
this.disclaimer.Name = "disclaimer";
this.disclaimer.Size = new System.Drawing.Size(590, 153);
this.disclaimer.TabIndex = 8;
this.disclaimer.TabStop = true;
this.disclaimer.Text = resources.GetString("disclaimer.Text");
this.disclaimer.UseCompatibleTextRendering = true;
this.disclaimer.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.disclaimer_LinkClicked);
//
// Program
//
this.ClientSize = new System.Drawing.Size(614, 565);
this.Controls.Add(this.disclaimer);
this.Controls.Add(this.explanation);
this.Controls.Add(this.linkLabelGithub);
this.Controls.Add(this.dataGridViewPatches);
this.Controls.Add(this.checkBoxParanoia);
this.Controls.Add(this.buttonRestore);
this.Controls.Add(this.buttonPatch);
this.Controls.Add(this.buttonBrowse);
this.Controls.Add(this.textBoxPath);
this.Controls.Add(this.labelPath);
this.MinimumSize = new System.Drawing.Size(580, 455);
this.Name = "Program";
this.Text = "SpaceChem Patcher";
((System.ComponentModel.ISupportInitialize)(this.dataGridViewPatches)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
private void checkBoxParanoia_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
buttonPatch.Enabled = cb.Checked;
}
private void buttonPatch_Click(object sender, EventArgs e)
{
this.Enabled = false;
// store settings
Properties.Settings.Default["SCPath"] = textBoxPath.Text;
StringCollection selectedPatches = new StringCollection();
selectedPatches.AddRange(Enumerable.Range(0, dataGridViewPatches.RowCount)
.Where(i => Convert.ToBoolean(dataGridViewPatches[0, i].Value))
.Select(i => ((Patch)i).ToString()).ToArray());
Properties.Settings.Default["SelectedPatches"] = selectedPatches;
Properties.Settings.Default.Save();
// game time started
PatchExe();
this.Enabled = true;
}
private void buttonBrowse_Click(object sender, EventArgs e)
{
if (openFileDialogSCExe.ShowDialog() == DialogResult.OK)
{
textBoxPath.Text = Path.GetDirectoryName(openFileDialogSCExe.FileName);
}
}
private void linkLabelGithub_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("https://github.com/csaboka/spacechempatch");
}
private void buttonRestore_Click(object sender, EventArgs e)
{
if (ExecutableUtils.IsRecognizedExe(currentExePath))
{
MessageBox.Show("Original exe is already in place");
}
else if (ExecutableUtils.IsRecognizedExe(originalExePath))
{
File.Delete(currentExePath);
File.Move(originalExePath, currentExePath);
MessageBox.Show("Original exe restored successfully");
}
else
{
MessageBox.Show("It was not possible to restore the original exe");
}
}
private void textBoxPath_TextChanged(object sender, EventArgs e)
{
gameFolder = textBoxPath.Text;
currentExePath = Path.Combine(gameFolder, "SpaceChem.exe");
originalExePath = Path.Combine(gameFolder, "SpaceChem.exe.original");
patchedExePath = Path.Combine(gameFolder, "SpaceChem.exe.patched");
}
// thanks https://stackoverflow.com/a/26225746/3288954
private void dataGridViewPatches_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridViewPatches.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dataGridViewPatches_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// this can fire only for checkboxes
// add patch to candidate patches
Patch patch = (Patch)dataGridViewPatches["ColumnName", e.RowIndex].Value;
if (Convert.ToBoolean(dataGridViewPatches[e.ColumnIndex, e.RowIndex].Value))
{
enabledPatches.Add(patch);
}
else
{
enabledPatches.Remove(patch);
}
// resolve conflicts
foreach (DataGridViewRow row in dataGridViewPatches.Rows)
{
Patch[] conflictingPatches = (Patch[])row.Cells["ColumnInternalConflicts"].Value;
DataGridViewCheckBoxCell CBCell = (DataGridViewCheckBoxCell)row.Cells["ColumnEnabled"];
if (conflictingPatches != null && enabledPatches.Overlaps(conflictingPatches))
{
CBCell.FlatStyle = FlatStyle.Flat;
CBCell.ReadOnly = true;
foreach (DataGridViewCell cell in row.Cells)
{
cell.Style.ForeColor = Color.DarkGray;
}
}
else
{
CBCell.FlatStyle = FlatStyle.System;
CBCell.ReadOnly = false;
foreach (DataGridViewCell cell in row.Cells)
{
cell.Style.ForeColor = default(Color);
}
}
}
}
private void disclaimer_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("https://github.com/csaboka/spacechempatch/issues");
}
}
}
| 47.361884 | 167 | 0.611086 | [
"MIT"
] | csaboka/spacechempatch | SpacechemPatch/Program.cs | 22,120 | C# |
using System;
using System.Collections;
using java.util;
namespace SolrIKVM {
public class EnumerationAdapter : Enumeration {
private readonly IEnumerator e;
private bool next;
public EnumerationAdapter(IEnumerator e) {
this.e = e;
next = e.MoveNext();
}
public bool hasMoreElements() {
return next;
}
public object nextElement() {
var o = e.Current;
next = e.MoveNext();
return o;
}
}
} | 22.4 | 52 | 0.517857 | [
"Apache-2.0"
] | bigjonroberts/SolrIKVM | SolrIKVM/EnumerationAdapter.cs | 562 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.